Programs & Examples On #Heading

How to export table as CSV with headings on Postgresql?

For version 9.5 I use, it would be like this:

COPY products_273 TO '/tmp/products_199.csv' WITH (FORMAT CSV, HEADER);

Calculate compass bearing / heading to location in Android

Here is how I have done it:

Canvas g = new Canvas( compass );
Paint p = new Paint( Paint.ANTI_ALIAS_FLAG );

float rotation = display.getOrientation() * 90;

g.translate( -box.left, -box.top );
g.rotate( -bearing - rotation, box.exactCenterX(), box.exactCenterY() );
drawCompass( g, p );
drawNeedle( g, p );

Error while installing json gem 'mkmf.rb can't find header files for ruby'

sudo apt-get --reinstall install ruby

try it for ubuntu 16.04

Understanding Python super() with __init__() methods

Super has no side effects

Base = ChildB

Base()

works as expected

Base = ChildA

Base()

gets into infinite recursion.

A python class that acts like dict

The problem with this chunk of code:

class myDict(dict):
    def __init__(self):
        self._dict = {}

    def add(id, val):
        self._dict[id] = val


md = myDict()
md.add('id', 123)

...is that your 'add' method (...and any method you want to be a member of a class) needs to have an explicit 'self' declared as its first argument, like:

def add(self, 'id', 23):

To implement the operator overloading to access items by key, look in the docs for the magic methods __getitem__ and __setitem__.

Note that because Python uses Duck Typing, there may actually be no reason to derive your custom dict class from the language's dict class -- without knowing more about what you're trying to do (e.g, if you need to pass an instance of this class into some code someplace that will break unless isinstance(MyDict(), dict) == True), you may be better off just implementing the API that makes your class sufficiently dict-like and stopping there.

Copy array by value

Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.

_x000D_
_x000D_
var arr2 = new Array(arr1);
_x000D_
_x000D_
_x000D_

Now arr1 and arr2 are two different array variables stored in separate stacks. Check this out on jsfiddle.

How can I iterate over an enum?

typedef enum{
    first = 2,
    second = 6,
    third = 17
}MyEnum;

static const int enumItems[] = {
    first,
    second,
    third
}

static const int EnumLength = sizeof(enumItems) / sizeof(int);

for(int i = 0; i < EnumLength; i++){
    //Do something with enumItems[i]
}

Merge (Concat) Multiple JSONObjects in Java

Thanks to Erel. Here is a Gson version.

/**
 * Merge "source" into "target". If fields have equal name, merge them recursively.
 * Null values in source will remove the field from the target.
 * Override target values with source values
 * Keys not supplied in source will remain unchanged in target
 * 
 * @return the merged object (target).
 */
public static JsonObject deepMerge(JsonObject source, JsonObject target) throws Exception {

    for (Map.Entry<String,JsonElement> sourceEntry : source.entrySet()) {
        String key = sourceEntry.getKey();
        JsonElement value = sourceEntry.getValue();
        if (!target.has(key)) {
            //target does not have the same key, so perhaps it should be added to target
            if (!value.isJsonNull()) //well, only add if the source value is not null
            target.add(key, value);
        } else {
            if (!value.isJsonNull()) {
                if (value.isJsonObject()) {
                    //source value is json object, start deep merge
                    deepMerge(value.getAsJsonObject(), target.get(key).getAsJsonObject());
                } else {
                    target.add(key,value);
                }
            } else {
                target.remove(key);
            }
        }
    }
    return target;
}



/**
 * simple test
 */
public static void main(String[] args) throws Exception {
    JsonParser parser = new JsonParser();
    JsonObject a = null;
    JsonObject b = null;
    a = parser.parse("{offer: {issue1: null, issue2: null}, accept: true, reject: null}").getAsJsonObject();
    b = parser.parse("{offer: {issue2: value2}, reject: false}").getAsJsonObject();
    System.out.println(deepMerge(a,b));
    // prints:
    // {"offer":{},"accept":true}
    a = parser.parse("{offer: {issue1: value1}, accept: true, reject: null}").getAsJsonObject();
    b = parser.parse("{offer: {issue2: value2}, reject: false}").getAsJsonObject();
    System.out.println(deepMerge(a,b));
    // prints:
    // {"offer":{"issue2":"value2","issue1":"value1"},"accept":true}

}

How to close existing connections to a DB

in restore wizard click "close existing connections to destination database"

in Detach Database wizard click "Drop connection" item.

How to insert a line break <br> in markdown

Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so

let markdown = `
    1. Apple
    2. Mango
     this is juicy
    3. Orange
`

Generate Controller and Model

php artisan make:controller --resource Backend/API/DemoController --model=Demo

How can I undo a `git commit` locally and on a remote after `git push`

Try using

git reset --hard <commit id> 

Please Note : Here commit id will the id of the commit you want to go to but not the id you want to reset. this was the only point where i also got stucked.

then push

git push -f <remote> <branch>

Why does range(start, end) not include end?

It's also useful for splitting ranges; range(a,b) can be split into range(a, x) and range(x, b), whereas with inclusive range you would write either x-1 or x+1. While you rarely need to split ranges, you do tend to split lists quite often, which is one of the reasons slicing a list l[a:b] includes the a-th element but not the b-th. Then range having the same property makes it nicely consistent.

Find location of a removable SD card

I came up with the following solution based on some answers found here.

CODE:

public class ExternalStorage {

    public static final String SD_CARD = "sdCard";
    public static final String EXTERNAL_SD_CARD = "externalSdCard";

    /**
     * @return True if the external storage is available. False otherwise.
     */
    public static boolean isAvailable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

    public static String getSdCardPath() {
        return Environment.getExternalStorageDirectory().getPath() + "/";
    }

    /**
     * @return True if the external storage is writable. False otherwise.
     */
    public static boolean isWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;

    }

    /**
     * @return A map of all storage locations available
     */
    public static Map<String, File> getAllStorageLocations() {
        Map<String, File> map = new HashMap<String, File>(10);

        List<String> mMounts = new ArrayList<String>(10);
        List<String> mVold = new ArrayList<String>(10);
        mMounts.add("/mnt/sdcard");
        mVold.add("/mnt/sdcard");

        try {
            File mountFile = new File("/proc/mounts");
            if(mountFile.exists()){
                Scanner scanner = new Scanner(mountFile);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    if (line.startsWith("/dev/block/vold/")) {
                        String[] lineElements = line.split(" ");
                        String element = lineElements[1];

                        // don't add the default mount path
                        // it's already in the list.
                        if (!element.equals("/mnt/sdcard"))
                            mMounts.add(element);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            File voldFile = new File("/system/etc/vold.fstab");
            if(voldFile.exists()){
                Scanner scanner = new Scanner(voldFile);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    if (line.startsWith("dev_mount")) {
                        String[] lineElements = line.split(" ");
                        String element = lineElements[2];

                        if (element.contains(":"))
                            element = element.substring(0, element.indexOf(":"));
                        if (!element.equals("/mnt/sdcard"))
                            mVold.add(element);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        for (int i = 0; i < mMounts.size(); i++) {
            String mount = mMounts.get(i);
            if (!mVold.contains(mount))
                mMounts.remove(i--);
        }
        mVold.clear();

        List<String> mountHash = new ArrayList<String>(10);

        for(String mount : mMounts){
            File root = new File(mount);
            if (root.exists() && root.isDirectory() && root.canWrite()) {
                File[] list = root.listFiles();
                String hash = "[";
                if(list!=null){
                    for(File f : list){
                        hash += f.getName().hashCode()+":"+f.length()+", ";
                    }
                }
                hash += "]";
                if(!mountHash.contains(hash)){
                    String key = SD_CARD + "_" + map.size();
                    if (map.size() == 0) {
                        key = SD_CARD;
                    } else if (map.size() == 1) {
                        key = EXTERNAL_SD_CARD;
                    }
                    mountHash.add(hash);
                    map.put(key, root);
                }
            }
        }

        mMounts.clear();

        if(map.isEmpty()){
                 map.put(SD_CARD, Environment.getExternalStorageDirectory());
        }
        return map;
    }
}

USAGE:

Map<String, File> externalLocations = ExternalStorage.getAllStorageLocations();
File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
File externalSdCard = externalLocations.get(ExternalStorage.EXTERNAL_SD_CARD);

How to keep the header static, always on top while scrolling?

_x000D_
_x000D_
.header {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 88px;_x000D_
  z-index: 10;_x000D_
  background: #eeeeee;_x000D_
  -webkit-box-shadow: 0 7px 8px rgba(0, 0, 0, 0.12);_x000D_
  -moz-box-shadow: 0 7px 8px rgba(0, 0, 0, 0.12);_x000D_
  box-shadow: 0 7px 8px rgba(0, 0, 0, 0.12);_x000D_
}_x000D_
_x000D_
.header__content-text {_x000D_
  text-align: center;_x000D_
  padding: 15px 20px;_x000D_
}_x000D_
_x000D_
.page__content-container {_x000D_
  margin: 100px auto;_x000D_
  width: 975px;_x000D_
  padding: 30px;_x000D_
}
_x000D_
<div class="header">_x000D_
  <h1 class="header__content-text">_x000D_
    Header content will come here_x000D_
  </h1>_x000D_
</div>_x000D_
<div class="page__content-container">_x000D_
  <div style="height:600px;">_x000D_
    <a href="http://imgur.com/k9hz3">_x000D_
      <img src="http://i.imgur.com/k9hz3.jpg" title="Hosted by imgur.com" alt="" />_x000D_
    </a>_x000D_
  </div>_x000D_
  <div style="height:600px;">_x000D_
    <a href="http://imgur.com/TXuFQ">_x000D_
      <img src="http://i.imgur.com/TXuFQ.jpg" title="Hosted by imgur.com" alt="" />_x000D_
    </a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add a new row to an empty numpy array

using an custom dtype definition, what worked for me was:

import numpy

# define custom dtype
type1 = numpy.dtype([('freq', numpy.float64, 1), ('amplitude', numpy.float64, 1)])
# declare empty array, zero rows but one column
arr = numpy.empty([0,1],dtype=type1)
# store row data, maybe inside a loop
row = numpy.array([(0.0001, 0.002)], dtype=type1)
# append row to the main array
arr = numpy.row_stack((arr, row))
# print values stored in the row 0
print float(arr[0]['freq'])
print float(arr[0]['amplitude'])

How do I open a Visual Studio project in design view?

Click on the form in the Solution Explorer

cannot load such file -- bundler/setup (LoadError)

This was happening in the production environment for me.

rm /vendor/bundle

then bundle install --deployment

resolved the issue.

Document directory path of Xcode Device Simulator

Where is the Documents Directory for the iOS 8 Simulator

You may have noticed that the iPhone Simulator has changed with Xcode 6, and with it – of course – the path to your simulated apps’ Documents Directory. At times we may need to take a look at it.

Finding that path is not as easy as it was once, namely Library/Application Support/iPhone Simulator/7.1/Applications/ followed by a cryptic number representing your app.

As of Xcode 6 and iOS 8 you’ll find it here: Library/Developer/CoreSimulator/Devices/cryptic number/data/Containers/Data/Application/cryptic number

http://pinkstone.co.uk/where-is-the-documents-directory-for-the-ios-8-simulator/

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

In Tomcat 8.0.44 I did this: create the JNDI on Tomcat's server.xml between the tag "GlobalNamingResources" For example:

_x000D_
_x000D_
<GlobalNamingResources>_x000D_
    <!-- Editable user database that can also be used by_x000D_
         UserDatabaseRealm to authenticate users_x000D_
    -->_x000D_
  <!-- Other previus resouces -->_x000D_
    <Resource auth="Container" driverClassName="org.postgresql.Driver" global="jdbc/your_jndi" _x000D_
    maxActive="100" maxIdle="20" maxWait="1000" minIdle="5" name="jdbc/your_jndi" password="your_password" _x000D_
    type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/your_database?user=postgres" username="database_username"/>_x000D_
  </GlobalNamingResources>
_x000D_
_x000D_
_x000D_ In your web application you need a link to that resource (ResourceLink):

project explore

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<Context reloadable="true" >_x000D_
   <ResourceLink name="jdbc/your_jndi"_x000D_
      global="jdbc/your_jndi"_x000D_
      auth="Container"_x000D_
      type="javax.sql.DataSource" />_x000D_
</Context>
_x000D_
_x000D_
_x000D_

So if you're using Hiberte with spring you can tell to him to use the JNDI in your persistence.xml

persistence.xml location

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"_x000D_
 version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">_x000D_
 <persistence-unit name="UNIT_NAME" transaction-type="RESOURCE_LOCAL">_x000D_
  <provider>org.hibernate.ejb.HibernatePersistence</provider>_x000D_
_x000D_
  <properties>_x000D_
   <property name="javax.persistence.jdbc.driver"   value="org.postgresql.Driver" />_x000D_
   <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />_x000D_
   _x000D_
   <!--  <property name="hibernate.jdbc.time_zone" value="UTC"/>-->_x000D_
   <property name="hibernate.hbm2ddl.auto" value="update" />_x000D_
   <property name="hibernate.show_sql" value="false" />_x000D_
   <property name="hibernate.format_sql" value="true"/>     _x000D_
  </properties>_x000D_
 </persistence-unit>_x000D_
</persistence>
_x000D_
_x000D_
_x000D_

So in your spring.xml you can do that:

_x000D_
_x000D_
<bean id="postGresDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">_x000D_
   <property name="jndiName" value="java:comp/env/jdbc/your_jndi" />_x000D_
  </bean>_x000D_
     _x000D_
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">_x000D_
              <property name="persistenceUnitName" value="UNIT_NAME" />_x000D_
              <property name="dataSource" ref="postGresDataSource" />_x000D_
              <property name="jpaVendorAdapter"> _x000D_
                 <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />_x000D_
              </property>_x000D_
        </bean>
_x000D_
_x000D_
_x000D_ Look above that entityManagerFactory bean refers to your UNIT_NAME configured at persistence xml and the bean postGresDataSource has a property that points to your JNDI resource in Tomcat.

_x000D_
_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />
_x000D_
_x000D_
_x000D_

In this example I used spring with xml but you can do this programmaticaly if you prefer.

That's it, I hope helped.

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):

virtualenv is a tool to create isolated Python environments.

The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.

In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).

That's why people consider insert(0, to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.

Getting the class name of an instance?

Do you want the name of the class as a string?

instance.__class__.__name__

Error when trying to access XAMPP from a network

In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:

# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>

and add

"Allow from all"

after Allow from ::1 127.0.0.0/8 {line}

Restart xampp, and you are done.

In later versions of Xampp

...you can simply remove this part

#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

from the same file and it should work over the local network.

Removing special characters VBA Excel

In the case that you not only want to exclude a list of special characters, but to exclude all characters that are not letters or numbers, I would suggest that you use a char type comparison approach.

For each character in the String, I would check if the unicode character is between "A" and "Z", between "a" and "z" or between "0" and "9". This is the vba code:

Function cleanString(text As String) As String
    Dim output As String
    Dim c 'since char type does not exist in vba, we have to use variant type.
    For i = 1 To Len(text)
        c = Mid(text, i, 1) 'Select the character at the i position
        If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
            output = output & c 'add the character to your output.
        Else
            output = output & " " 'add the replacement character (space) to your output
        End If
    Next
    cleanString = output
End Function

The Wikipedia list of Unicode characers is a good quick-start if you want to customize this function a little more.

This solution has the advantage to be functionnal even if the user finds a way to introduce new special characters. It also faster than comparing two lists together.

Create a hidden field in JavaScript

You can use jquery for create element on the fly

$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');

or other way

$('<input>').attr({
    type: 'hidden',
    id: 'fieldId',
    name: 'fieldname'
}).appendTo('form')

Why does .NET foreach loop throw NullRefException when collection is null?

A foreach loop calls the GetEnumerator method.
If the collection is null, this method call results in a NullReferenceException.

It is bad practice to return a null collection; your methods should return an empty collection instead.

Add custom icons to font awesome

If you want some icons (or all) from font-awesome including yout custom svg icons you can:

1- Go to http://fontawesome.io/ Download the zip and extract-it for example in your Desktop.

2- Go to http://fontastic.me/ use your email to create an account.

3- Once you have been logged-in click on the header option: Add More Icons.

4- Select the SVG of font-awesome located in your extracted zip inside fonts.

5- Repeat the procces uploading your own svg files.

6- Inside Home (at the header of the page) Select the icons you want to download, customize them to give your custom names and select publish to have a link or download the fonts and css.

Sorry about my english ! :D

svn list of files that are modified in local copy

Right click folder -> Click Tortoise SVN -> Check for modification

How to set a default Value of a UIPickerView

This is How to set a default Value of a UIPickerView

[self.picker selectRow:4 inComponent:0 animated:YES];

How to fire a button click event from JavaScript in ASP.NET

You can fill a hidden field from your JavaScript code and do an explicit postback from JavaScript. Then from the server side, check that hiddenfield and do whatever necessary.

Installing tkinter on ubuntu 14.04

To get this to work with pyenv on Ubuntu 16.04, I had to:

$ sudo apt-get install python-tk python3-tk tk-dev

Then install the version of Python I wanted via pyenv:

$ pyenv install 3.6.2

Then I could import tkinter just fine:

import tkinter

getting the difference between date in days in java

Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
  dateFormat.format(startDate)+" and "+
  dateFormat.format(endDate)+" is "+
  diffDays+" days.");

This will not work when crossing daylight savings time (or leap seconds) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java before 8 I know is to use Calendar's add and before/after methods to check and adjust the calculation:

start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
    start.add(Calendar.DAY_OF_MONTH, 1);
    diffDays++;
}
while (start.after(end)) {
    start.add(Calendar.DAY_OF_MONTH, -1);
    diffDays--;
}

Converting xml to string using C#

   public string GetXMLAsString(XmlDocument myxml)
    {
        using (var stringWriter = new StringWriter())
        {
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
               myxml.WriteTo(xmlTextWriter);
               return stringWriter.ToString();
            }

        }    
}

How can I exclude a directory from Visual Studio Code "Explore" tab?

Use files.exclude:

  • Go to File -> Preferences -> Settings (or on Mac Code -> Preferences -> Settings)
  • Pick the workspace settings tab
  • Add this code to the settings.json file displayed on the right side:

    // Place your settings in this file to overwrite default and user settings.
    
    {
        "settings": {
            "files.exclude": {
                "**/.git": true,         // this is a default value
                "**/.DS_Store": true,    // this is a default value
    
                "**/node_modules": true, // this excludes all folders 
                                        // named "node_modules" from 
                                        // the explore tree
    
                // alternative version
                "node_modules": true    // this excludes the folder 
                                        // only from the root of
                                        // your workspace 
            }
        }
    }
    

If you chose File -> Preferences -> User Settings then you configure the exclude folders globally for your current user.

View the change history of a file using Git versioning

git log --follow -p -- path-to-file

This will show the entire history of the file (including history beyond renames and with diffs for each change).

In other words, if the file named bar was once named foo, then git log -p bar (without the --follow option) will only show the file's history up to the point where it was renamed -- it won't show the file's history when it was known as foo. Using git log --follow -p bar will show the file's entire history, including any changes to the file when it was known as foo. The -p option ensures that diffs are included for each change.

Password encryption/decryption code in .NET

You can use the managed .Net cryptography library, then save the encrypted string into the database. When you want to verify the password you can compare the stored database string with the hashed value of the user input. See here for more info about SHA512Managed

using System.Security.Cryptography;

    public static string EncryptSHA512Managed(string password)
    {
        UnicodeEncoding uEncode = new UnicodeEncoding();
        byte[] bytPassword = uEncode.GetBytes(password);
        SHA512Managed sha = new SHA512Managed();
        byte[] hash = sha.ComputeHash(bytPassword);
        return Convert.ToBase64String(hash);
    }

How can I replace a newline (\n) using sed?

sed -i ':a;N;$!ba;s/\n/,/g' test.txt

tr "\n" <file name>

Using textures in THREE.js

In version r82 of Three.js TextureLoader is the object to use for loading a texture.

Loading one texture (source code, demo)

Extract (test.js):

var scene = new THREE.Scene();
var ratio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight,
  0.1, 50);

var renderer = ...

[...]

/**
 * Will be called when load completes.
 * The argument will be the loaded texture.
 */
var onLoad = function (texture) {
  var objGeometry = new THREE.BoxGeometry(20, 20, 20);
  var objMaterial = new THREE.MeshPhongMaterial({
    map: texture,
    shading: THREE.FlatShading
  });

  var mesh = new THREE.Mesh(objGeometry, objMaterial);

  scene.add(mesh);

  var render = function () {
    requestAnimationFrame(render);

    mesh.rotation.x += 0.010;
    mesh.rotation.y += 0.010;

    renderer.render(scene, camera);
  };

  render();
}

// Function called when download progresses
var onProgress = function (xhr) {
  console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};

// Function called when download errors
var onError = function (xhr) {
  console.log('An error happened');
};

var loader = new THREE.TextureLoader();
loader.load('texture.jpg', onLoad, onProgress, onError);

Loading multiple textures (source code, demo)

In this example the textures are loaded inside the constructor of the mesh, multiple texture are loaded using Promises.

Extract (Globe.js):

Create a new container using Object3D for having two meshes in the same container:

var Globe = function (radius, segments) {

  THREE.Object3D.call(this);

  this.name = "Globe";

  var that = this;

  // instantiate a loader
  var loader = new THREE.TextureLoader();

A map called textures where every object contains the url of a texture file and val for storing the value of a Three.js texture object.

  // earth textures
  var textures = {
    'map': {
      url: 'relief.jpg',
      val: undefined
    },
    'bumpMap': {
      url: 'elev_bump_4k.jpg',
      val: undefined
    },
    'specularMap': {
      url: 'wateretopo.png',
      val: undefined
    }
  };

The array of promises, for each object in the map called textures push a new Promise in the array texturePromises, every Promise will call loader.load. If the value of entry.val is a valid THREE.Texture object, then resolve the promise.

  var texturePromises = [], path = './';

  for (var key in textures) {
    texturePromises.push(new Promise((resolve, reject) => {
      var entry = textures[key]
      var url = path + entry.url

      loader.load(url,
        texture => {
          entry.val = texture;
          if (entry.val instanceof THREE.Texture) resolve(entry);
        },
        xhr => {
          console.log(url + ' ' + (xhr.loaded / xhr.total * 100) +
            '% loaded');
        },
        xhr => {
          reject(new Error(xhr +
            'An error occurred loading while loading: ' +
            entry.url));
        }
      );
    }));
  }

Promise.all takes the promise array texturePromises as argument. Doing so makes the browser wait for all the promises to resolve, when they do we can load the geometry and the material.

  // load the geometry and the textures
  Promise.all(texturePromises).then(loadedTextures => {

    var geometry = new THREE.SphereGeometry(radius, segments, segments);
    var material = new THREE.MeshPhongMaterial({
      map: textures.map.val,
      bumpMap: textures.bumpMap.val,
      bumpScale: 0.005,
      specularMap: textures.specularMap.val,
      specular: new THREE.Color('grey')
    });

    var earth = that.earth = new THREE.Mesh(geometry, material);
    that.add(earth);
  });

For the cloud sphere only one texture is necessary:

  // clouds
  loader.load('n_amer_clouds.png', map => {
    var geometry = new THREE.SphereGeometry(radius + .05, segments, segments);
    var material = new THREE.MeshPhongMaterial({
      map: map,
      transparent: true
    });

    var clouds = that.clouds = new THREE.Mesh(geometry, material);
    that.add(clouds);
  });
}

Globe.prototype = Object.create(THREE.Object3D.prototype);
Globe.prototype.constructor = Globe;

JSON serialization/deserialization in ASP.Net Core

.net core

using System.Text.Json;

To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft side

Sort array of objects by object fields

If everything fails here is another solution:

$names = array(); 
foreach ($my_array as $my_object) {
    $names[] = $my_object->name; //any object field
}

array_multisort($names, SORT_ASC, $my_array);

return $my_array;

Display number always with 2 decimal places in <input>

If you are using Angular 2 (apparently it also works for Angular 4 too), you can use the following to round to two decimal places{{ exampleNumber | number : '1.2-2' }}, as in:

<ion-input value="{{ exampleNumber | number : '1.2-2' }}"></ion-input>

BREAKDOWN

'1.2-2' means {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}:

  • A minimum of 1 digit will be shown before decimal point
  • It will show at least 2 digits after decimal point
  • But not more than 2 digits

Credit due here and here

What does the "On Error Resume Next" statement do?

It enables error handling. The following is partly from https://msdn.microsoft.com/en-us/library/5hsw66as.aspx

' Enable error handling. When a run-time error occurs, control goes to the statement 
' immediately following the statement where the error occurred, and execution
' continues from that point.
On Error Resume Next

SomeCodeHere

If Err.Number = 0 Then
    WScript.Echo "No Error in SomeCodeHere."
Else
  WScript.Echo "Error in SomeCodeHere: " & Err.Number & ", " & Err.Source & ", " & Err.Description
  ' Clear the error or you'll see it again when you test Err.Number
  Err.Clear
End If

SomeMoreCodeHere

If Err.Number <> 0 Then
  WScript.Echo "Error in SomeMoreCodeHere:" & Err.Number & ", " & Err.Source & ", " & Err.Description
  ' Clear the error or you'll see it again when you test Err.Number
  Err.Clear
End If

' Disables enabled error handler in the current procedure and resets it to Nothing.
On Error Goto 0

' There are also `On Error Goto -1`, which disables the enabled exception in the current 
' procedure and resets it to Nothing, and `On Error Goto line`, 
' which enables the error-handling routine that starts at the line specified in the 
' required line argument. The line argument is any line label or line number. If a run-time 
' error occurs, control branches to the specified line, making the error handler active. 
' The specified line must be in the same procedure as the On Error statement, 
' or a compile-time error will occur.

how to sort pandas dataframe from one column

This one worked for me:

df=df.sort_values(by=[2])

Whereas:

df=df.sort_values(by=['2']) 

is not working.

Count the number of occurrences of a string in a VARCHAR field?

Here is a function that will do that.

CREATE FUNCTION count_str(haystack TEXT, needle VARCHAR(32))
  RETURNS INTEGER DETERMINISTIC
  BEGIN
    RETURN ROUND((CHAR_LENGTH(haystack) - CHAR_LENGTH(REPLACE(haystack, needle, ""))) / CHAR_LENGTH(needle));
  END;

Closing a Userform with Unload Me doesn't work

Without seeing your full code, this is impossible to answer with any certainty. The error usually occurs when you are trying to unload a control rather than the form.

Make sure that you don't have the "me" in brackets.

Also if you can post the full code for the userform it would help massively.

What does [STAThread] do?

The STAThreadAttribute is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.

MSDN explains the reason in slightly more detail:

STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.

This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).

Difference between "on-heap" and "off-heap"

The on-heap store refers to objects that will be present in the Java heap (and also subject to GC). On the other hand, the off-heap store refers to (serialized) objects that are managed by EHCache, but stored outside the heap (and also not subject to GC). As the off-heap store continues to be managed in memory, it is slightly slower than the on-heap store, but still faster than the disk store.

The internal details involved in management and usage of the off-heap store aren't very evident in the link posted in the question, so it would be wise to check out the details of Terracotta BigMemory, which is used to manage the off-disk store. BigMemory (the off-heap store) is to be used to avoid the overhead of GC on a heap that is several Megabytes or Gigabytes large. BigMemory uses the memory address space of the JVM process, via direct ByteBuffers that are not subject to GC unlike other native Java objects.

ASP.NET Bundles how to disable minification

Conditional compilation directives are your friend:

#if DEBUG
            var jsBundle = new Bundle("~/Scripts/js");
#else
            var jsBundle = new ScriptBundle("~/Scripts/js");
#endif

How to iterate through a DataTable

foreach (DataRow row in myDataTable.Rows)
{
   Console.WriteLine(row["ImagePath"]);
}

I am writing this from memory.
Hope this gives you enough hint to understand the object model.

DataTable -> DataRowCollection -> DataRow (which one can use & look for column contents for that row, either using columnName or ordinal).

-> = contains.

How do I return a string from a regex match in python?

Considering there might be several img tags I would recommend re.findall:

import re

with open("sample.txt", 'r') as f_in, open('writetest.txt', 'w') as f_out:
    for line in f_in:
        for img in re.findall('<img[^>]+>', line):
            print >> f_out, "yo it's a {}".format(img)

Get a Div Value in JQuery

You could use

jQuery('#gregsButton').click(function() { 
    var mb = jQuery('#myDiv').text(); 
    alert("Value of div is: " + mb); 
});

Looks like there may be a conflict with using the $. Remember that the variable 'mb' will not be accessible outside of the event handler. Also, the text() function returns a string, no need to get mb.value.

Converting Symbols, Accent Letters to English Alphabet

String tested : ÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝß

Tested :

  • Output from Apache Commons Lang3 : AAAAAÆCEEEEIIIIÐNOOOOOØUUUUYß
  • Output from ICU4j : AAAAAÆCEEEEIIIIÐNOOOOOØUUUUYß
  • Output from JUnidecode : AAAAAAECEEEEIIIIDNOOOOOOUUUUUss (problem with Ý and another issue)
  • Output from Unidecode : AAAAAAECEEEEIIIIDNOOOOOOUUUUYss

The last choice is the best.

In Linux, how to tell how much memory processes are using?

First get the pid:

ps ax | grep [process name]

And then:

top -p PID

You can watch various processes in the same time:

top -p PID1 -p PID2 

How to remove focus around buttons on click

If you use the rule :focus { outline: none; } to remove outlines, the link or control will be focusable but with no indication of focus for keyboard users. Methods to remove it such with JS like onfocus="blur()" are even worse and will result in keyboard users being unable to interact with the control.

The hacks you can use, that are sort of OK, includes adding :focus { outline: none; } rules when users interacts with the mouse and remove them again if keyboard interaction is detected. Lindsay Evans has made a lib for this: https://github.com/lindsayevans/outline.js

But i would prefer to setting a class on the html or body tag. And have control in the CSS file of when to use this.

For example (inline event handlers is for demonstration purposes only):

<html>
<head>
<style>
  a:focus, button:focus {
    outline: 3px solid #000;
  }
  .no-focus a, .no-focus button {
    outline: none;
  } 
</style>
</head>
<body id="thebody" 
onmousedown="document.getElementById('thebody').classList.add('no-focus');"
onkeydown="document.getElementById('thebody').classList.remove('no-focus');">
    <p>This her is <a href="#">a link</a></p>   
    <button>Click me</button>
</body>
</html>

I did put togheter a Pen: http://codepen.io/snobojohan/pen/RWXXmp

But beware there are performance issues. This forces repaint every time the user switches between mouse and keyboard. More about Avoiding Unnecessary Paints http://www.html5rocks.com/en/tutorials/speed/unnecessary-paints/

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.

The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).

Numeric Type Attributes.

How to open a page in a new window or tab from code-behind

Target= "_blank"

This does it in html, give it a try in C#

What does 'public static void' mean in Java?

It means that:

  • public - it can be called from anywhere
  • static - it doesn't have any object state, so you can call it without instantiating an object
  • void - it doesn't return anything

You'd think that the lack of a return means it isn't doing much, but it might be saving things in the database, for example.

angular js unknown provider

I had same problem. I fixed that using $('body').attr("ng-app", 'MyApp') instead of <body ng-app="MyApp"> to boostrap.

Because I did

angular.element(document).ready(function () {        
    angular.bootstrap(document, [App.Config.Settings.AppName]);
})

for architecture requirements.

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:

print(*L)

and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

"query function not defined for Select2 undefined error"

I got the same error. I have been using select2-3.5.2

This was my code which had error

    $('#carstatus-select').select2().val([1,2])

Below code fixed the issue.

    $('#carstatus-select').val([1,2]);

How to upload image in CodeIgniter?

Simple Image upload in codeigniter

Find below code for easy image upload

public function doupload()
     {
        $upload_path="https://localhost/project/profile"  
        $uid='10'; //creare seperate folder for each user 
        $upPath=upload_path."/".$uid;
        if(!file_exists($upPath)) 
        {
                   mkdir($upPath, 0777, true);
        }
        $config = array(
        'upload_path' => $upPath,
        'allowed_types' => "gif|jpg|png|jpeg",
        'overwrite' => TRUE,
        'max_size' => "2048000", 
        'max_height' => "768",
        'max_width' => "1024"
        );
        $this->load->library('upload', $config);
        if(!$this->upload->do_upload('userpic'))
        { 
            $data['imageError'] =  $this->upload->display_errors();

        }
        else
        {
            $imageDetailArray = $this->upload->data();
            $image =  $imageDetailArray['file_name'];
        }

     }

Hope this helps you to upload image

What is apache's maximum url length?

Allowed default size of URI is 8177 characters in GET request. Simple code in python for such testing.

#!/usr/bin/env python2

import sys
import socket

if __name__ == "__main__":
    string = sys.argv[1]
    buf_get = "x" * int(string)
    buf_size = 1024
    request = "HEAD %s HTTP/1.1\nHost:localhost\n\n" % buf_get
    print "===>", request

    sock_http = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_http.connect(("localhost", 80))
    sock_http.send(request)
    while True:
       print "==>", sock_http.recv(buf_size)
       if not sock_http.recv(buf_size):
           break
    sock_http.close()

On 8178 characters you will get such message: HTTP/1.1 414 Request-URI Too Large

Properties file in python (similar to Java Properties)

You can use a file-like object in ConfigParser.RawConfigParser.readfp defined here -> https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.readfp

Define a class that overrides readline that adds a section name before the actual contents of your properties file.

I've packaged it into the class that returns a dict of all the properties defined.

import ConfigParser

class PropertiesReader(object):

    def __init__(self, properties_file_name):
        self.name = properties_file_name
        self.main_section = 'main'

        # Add dummy section on top
        self.lines = [ '[%s]\n' % self.main_section ]

        with open(properties_file_name) as f:
            self.lines.extend(f.readlines())

        # This makes sure that iterator in readfp stops
        self.lines.append('')

    def readline(self):
        return self.lines.pop(0)

    def read_properties(self):
        config = ConfigParser.RawConfigParser()

        # Without next line the property names will be lowercased
        config.optionxform = str

        config.readfp(self)
        return dict(config.items(self.main_section))

if __name__ == '__main__':
    print PropertiesReader('/path/to/file.properties').read_properties()

How to avoid .pyc files?

Solution for ipython 6.2.1 using python 3.5.2 (Tested on Ubuntu 16.04 and Windows 10):

Ipython doesn’t respect %env PYTHONDONTWRITEBYTECODE =1 if set in the ipython interpretor or during startup in ~/.ipython/profile-default/startup/00-startup.ipy. Instead using the following in your ~.ipython/profile-default/startup/00-startup.py

import sys
sys.dont_write_bytecode=True

Initialise numpy array of unknown length

You can do this:

a = np.array([])
for x in y:
    a = np.append(a, x)

How to keep a git branch in sync with master

Run the following commands:

$ git checkout mobiledevice
$ git pull origin master 

This would merge all the latest commits to your branch. If the merge results in some conflicts, you'll need to fix them.

I don't know if this is the best practice but works for me.

How can I get the current stack trace in Java?

You can use Thread.currentThread().getStackTrace().

That returns an array of StackTraceElements that represent the current stack trace of a program.

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

The type of expression

" quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'"

is std::string. However function system has declaration

int system(const char *s);

that is it accepts an argumnet of type const char *

There is no conversion operator that would convert implicitly an object of type std::string to object of type const char *.

Nevertheless class std::string has two functions that do this conversion explicitly. They are c_str() and data() (the last can be used only with compiler that supports C++11)

So you can write

string name = "john";

system( (" quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'").c_str() );

There is no need to use an intermediate variable for the expression.

Rerender view on browser resize with React

Thank you all for the answers. Here's my React + Recompose. It's a High Order Function that includes the windowHeight and windowWidth properties to the component.

const withDimensions = compose(
 withStateHandlers(
 ({
   windowHeight,
   windowWidth
 }) => ({
   windowHeight: window.innerHeight,
   windowWidth: window.innerWidth
 }), {
  handleResize: () => () => ({
    windowHeight: window.innerHeight,
    windowWidth: window.innerWidth
  })
 }),
 lifecycle({
   componentDidMount() {
   window.addEventListener('resize', this.props.handleResize);
 },
 componentWillUnmount() {
  window.removeEventListener('resize');
 }})
)

where does MySQL store database files?

Check your my.cnf file in your MySQL program directory, look for

[mysqld]
datadir=

The datadir is the location where your MySQL database is stored.

preg_match(); - Unknown modifier '+'

Try this code:

preg_match('/[a-zA-Z]+<\/a>.$/', $lastgame, $match);
print_r($match);

Using / as a delimiter means you also need to escape it here, like so: <\/a>.

UPDATE

preg_match('/<a.*<a.*>(.*)</', $lastgame, $match);
echo'['.$match[1].']';

Might not be the best way...

How to input a regex in string.replace?

replace method of string objects does not accept regular expressions but only fixed strings (see documentation: http://docs.python.org/2/library/stdtypes.html#str.replace).

You have to use re module:

import re
newline= re.sub("<\/?\[[0-9]+>", "", line)

Link to reload current page

For me, the answers previously provided here, were opening a new tab/window (probably because of my browser settings). But i wanted to reload/refresh on the same page. So, the above solutions did not work for me.

However, the good news is, the following (either of two) worked for me.

  1. <a onclick="javascript:window.location.reload();"> refresh</a>
  2. <a onclick="window.location.href=this">refresh</a>

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

Deleting an SVN branch

You can also delete the branch on the remote directly. Having done that, the next update will remove it from your working copy.

svn rm "^/reponame/branches/name_of_branch" -m "cleaning up old branch name_of_branch"

The ^ is short for the URL of the remote, as seen in 'svn info'. The double quotes are necessary on Windows command line, because ^ is a special character.

This command will also work if you have never checked out the branch.

AngularJS passing data to $http.get request

An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request.

angular.http provides an option for it called params.

$http({
    url: user.details_path, 
    method: "GET",
    params: {user_id: user.id}
 });

See: http://docs.angularjs.org/api/ng.$http#get and https://docs.angularjs.org/api/ng/service/$http#usage (shows the params param)

favicon not working in IE

Check the response headers for your favicon. They must not include "Cache-Control: no-cache".

You can check this from the command line using:

curl -I http://example.com/favicon.ico

or

wget --server-response --spider http://example.com/favicon.ico

(or use some other tool that will show you response headers)

If you see "Cache-Control: no-cache" in there, adjust your server configuration to either remove that header from the favicon response or set a max-age.

How to retrieve Request Payload

Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).

... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)

UPDATE

Also docs say that:

The encode option should only be set to true when a root is defined

So, probably, writer's root config is required.

How to get unique values in an array

These days, you can use ES6's Set data type to convert your array to a unique Set. Then, if you need to use array methods, you can turn it back into an Array:

var arr = ["a", "a", "b"];
var uniqueSet = new Set(arr); // {"a", "b"}
var uniqueArr = Array.from(uniqueSet); // ["a", "b"]
//Then continue to use array methods:
uniqueArr.join(", "); // "a, b"

How can I create download link in HTML?

Like this

<a href="www.yoursite.com/theThingYouWantToDownload">Link name</a>

So a file name.jpg on a site example.com would look like this

<a href="www.example.com/name.jpg">Image</a>

Why do abstract classes in Java have constructors?

I guess root of this question is that people believe that a call to a constructor creates the object. That is not the case. Java nowhere claims that a constructor call creates an object. It just does what we want constructor to do, like initialising some fields..that's all. So an abstract class's constructor being called doesn't mean that its object is created.

How to calculate a Mod b in Casio fx-991ES calculator

It all falls back to the definition of modulus: It is the remainder, for example, 7 mod 3 = 1. This because 7 = 3(2) + 1, in which 1 is the remainder.

To do this process on a simple calculator do the following: Take the dividend (7) and divide by the divisor (3), note the answer and discard all the decimals -> example 7/3 = 2.3333333, only worry about the 2. Now multiply this number by the divisor (3) and subtract the resulting number from the original dividend.

so 2*3 = 6, and 7 - 6 = 1, thus 1 is 7mod3

Scroll to a specific Element Using html

Yes, you may use an anchor by specifying the id attribute of an element and then linking to it with a hash.

For example (taken from the W3 specification):

You may read more about this in <A href="#section2">Section Two</A>.
...later in the document
<H2 id="section2">Section Two</H2>
...later in the document
<P>Please refer to <A href="#section2">Section Two</A> above
for more details.

forward declaration of a struct in C?

Try this

#include <stdio.h>

struct context;

struct funcptrs{
  void (*func0)(struct context *ctx);
  void (*func1)(void);
};

struct context{
    struct funcptrs fps;
}; 

void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }

void getContext(struct context *con){
    con->fps.func0 = func0;  
    con->fps.func1 = func1;  
}

int main(int argc, char *argv[]){
 struct context c;
   c.fps.func0 = func0;
   c.fps.func1 = func1;
   getContext(&c);
   c.fps.func0(&c);
   getchar();
   return 0;
}

Mask output of `The following objects are masked from....:` after calling attach() function

You use attach without detach - every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach or do not use attach at all. Nice discussion and tips are here.

Start script missing error when running npm start

I am getting this error with a ruby on rails app, I don't know what script name to put in my package.json file. I tried:

"scripts": {
      "start": "webpack-dev-server --hot"
  }

But I got this error:

remote: App container failed to start!!
=====> taaalk web container output:
       > [email protected] start
       > webpack-dev-server --hot
       /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- bundler/setup (LoadError)
        from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
        from /app/bin/webpack-dev-server:10:in `<main>'
       npm ERR! code 1
       npm ERR! path /app
       npm ERR! command failed
       npm ERR! command sh -c webpack-dev-server --hot
       npm ERR! A complete log of this run can be found in:
       npm ERR!     /app/.npm/_logs/2020-11-27T01_01_54_386Z-debug.log
       > [email protected] start
       > webpack-dev-server --hot
       /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- bundler/setup (LoadError)
        from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
        from /app/bin/webpack-dev-server:10:in `<main>'
       npm ERR! code 1
       npm ERR! path /app
       npm ERR! command failed
       npm ERR! command sh -c webpack-dev-server --hot
       npm ERR! A complete log of this run can be found in:
       npm ERR!     /app/.npm/_logs/2020-11-27T01_01_55_590Z-debug.log
       > [email protected] start
       > webpack-dev-server --hot
       /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- bundler/setup (LoadError)
        from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
        from /app/bin/webpack-dev-server:10:in `<main>'
       npm ERR! code 1
       npm ERR! path /app
       npm ERR! command failed
       npm ERR! command sh -c webpack-dev-server --hot
       npm ERR! A complete log of this run can be found in:
       npm ERR!     /app/.npm/_logs/2020-11-27T01_01_56_835Z-debug.log
       > [email protected] start
       > webpack-dev-server --hot
       /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- bundler/setup (LoadError)
        from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
        from /app/bin/webpack-dev-server:10:in `<main>'
       npm ERR! code 1
       npm ERR! path /app
       npm ERR! command failed
       npm ERR! command sh -c webpack-dev-server --hot
       npm ERR! A complete log of this run can be found in:
       npm ERR!     /app/.npm/_logs/2020-11-27T01_01_58_249Z-debug.log
       > [email protected] start
       > webpack-dev-server --hot
       /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- bundler/setup (LoadError)
        from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
        from /app/bin/webpack-dev-server:10:in `<main>'
       npm ERR! code 1
       npm ERR! path /app
       npm ERR! command failed
       npm ERR! command sh -c webpack-dev-server --hot
       npm ERR! A complete log of this run can be found in:
       npm ERR!     /app/.npm/_logs/2020-11-27T01_02_00_063Z-debug.log
       > [email protected] start
       > webpack-dev-server --hot
       /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- bundler/setup (LoadError)
        from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
        from /app/bin/webpack-dev-server:10:in `<main>'
       npm ERR! code 1
       npm ERR! path /app
       npm ERR! command failed
       npm ERR! command sh -c webpack-dev-server --hot
       npm ERR! A complete log of this run can be found in:
       npm ERR!     /app/.npm/_logs/2020-11-27T01_02_02_705Z-debug.log
=====> end taaalk web container output
To taaalk.co:taaalk
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to '[email protected]:taaalk'

I am not very familiar with these sorts of problems so am a bit lost!

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

PHP - Check if the page run on Mobile or Desktop browser

There are many great open source projects that make detection a lot easier. To name two:

  1. PHP mobile detect
  2. WURFL

how to check for datatype in node js- specifically for integer

I just made some tests in node.js v4.2.4 (but this is true in any javascript implementation):

> typeof NaN
'number'
> isNaN(NaN)
true
> isNaN("hello")
true

the surprise is the first one as type of NaN is "number", but that is how it is defined in javascript.

So the next test brings up unexpected result

> typeof Number("hello")
"number"

because Number("hello") is NaN

The following function makes results as expected:

function isNumeric(n){
  return (typeof n == "number" && !isNaN(n));
}

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

If you are just targeting specific domains you can try and add this in your application's Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

How to fix .pch file missing on build?

Precompiled Header (pch) use is a two-step process.

In step one, you compile a stub file (In VS200x it's usually called stdafx.cpp. Newer versions use pch.cpp.). This stub file indirectly includes only the headers you want precompiled. Typically, one small header (usually stdafx.h or pch.hpp) lists standard headers such as <iostream> and <string>, and this is then included in the stub file. Compiling this creates the .pch file.

In step 2, your actual source code includes the same small header from step 1 as the first header. The compiler, when it encounters this special header, reads the corresponding .pch file instead. That means it doesn't have to (re)compile those standard headers every time.

In your case, it seems step 1 fails. Is the stub file still present? In your case, that would probably be xxxxx.cpp. It must be a file that's compiled with /Yc:xxxxx.pch, since that's the compiler flag to indicate it's step 1 of the PCH process. If xxxxx.cpp is present, and is such a stub file, then it's probably missing its /Yc: compiler option.

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

asp.net: How can I remove an item from a dropdownlist?

There is also a slightly simpler way of removing the value.

mydropdownid.Items.Remove("Chicago"); 
<dropdown id=mydropdown .....>

values

  • Florida
  • Texas
  • Utah
  • Chicago

Get the latest record from mongodb collection

I need a query with constant time response

By default, the indexes in MongoDB are B-Trees. Searching a B-Tree is a O(logN) operation, so even find({_id:...}) will not provide constant time, O(1) responses.

That stated, you can also sort by the _id if you are using ObjectId for you IDs. See here for details. Of course, even that is only good to the last second.

You may to resort to "writing twice". Write once to the main collection and write again to a "last updated" collection. Without transactions this will not be perfect, but with only one item in the "last updated" collection it will always be fast.

How do I pass the this context to a function?

You can use the bind function to set the context of this within a function.

function myFunc() {
  console.log(this.str)
}
const myContext = {str: "my context"}
const boundFunc = myFunc.bind(myContext);
boundFunc(); // "my context"

How to terminate a Python script

My two cents.

Python 3.8.1, Windows 10, 64-bit.

sys.exit() does not work directly for me.

I have several nexted loops.

First I declare a boolean variable, which I call immediateExit.

So, in the beginning of the program code I write:

immediateExit = False

Then, starting from the most inner (nested) loop exception, I write:

            immediateExit = True
            sys.exit('CSV file corrupted 0.')

Then I go into the immediate continuation of the outer loop, and before anything else being executed by the code, I write:

    if immediateExit:
        sys.exit('CSV file corrupted 1.')

Depending on the complexity, sometimes the above statement needs to be repeated also in except sections, etc.

    if immediateExit:
        sys.exit('CSV file corrupted 1.5.')

The custom message is for my personal debugging, as well, as the numbers are for the same purpose - to see where the script really exits.

'CSV file corrupted 1.5.'

In my particular case I am processing a CSV file, which I do not want the software to touch, if the software detects it is corrupted. Therefore for me it is very important to exit the whole Python script immediately after detecting the possible corruption.

And following the gradual sys.exit-ing from all the loops I manage to do it.

Full code: (some changes were needed because it is proprietory code for internal tasks):

immediateExit = False
start_date = '1994.01.01'
end_date = '1994.01.04'
resumedDate = end_date


end_date_in_working_days = False
while not end_date_in_working_days:
    try:
        end_day_position = working_days.index(end_date)

        end_date_in_working_days = True
    except ValueError: # try statement from end_date in workdays check
        print(current_date_and_time())
        end_date = input('>> {} is not in the list of working days. Change the date (YYYY.MM.DD): '.format(end_date))
        print('New end date: ', end_date, '\n')
        continue


    csv_filename = 'test.csv'
    csv_headers = 'date,rate,brand\n' # not real headers, this is just for example
    try:
        with open(csv_filename, 'r') as file:
            print('***\nOld file {} found. Resuming the file by re-processing the last date lines.\nThey shall be deleted and re-processed.\n***\n'.format(csv_filename))
            last_line = file.readlines()[-1]
            start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
            resumedDate = start_date

            if last_line == csv_headers:
                pass
            elif start_date not in working_days:
                print('***\n\n{} file might be corrupted. Erase or edit the file to continue.\n***'.format(csv_filename))
                immediateExit = True
                sys.exit('CSV file corrupted 0.')
            else:
                start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
                print('\nLast date:', start_date)
                file.seek(0) # setting the cursor at the beginnning of the file
                lines = file.readlines() # reading the file contents into a list
                count = 0 # nr. of lines with last date
                for line in lines: #cycling through the lines of the file
                    if line.split(',')[0] == start_date: # cycle for counting the lines with last date in it.
                        count = count + 1
        if immediateExit:
            sys.exit('CSV file corrupted 1.')
        for iter in range(count): # removing the lines with last date
            lines.pop()
        print('\n{} lines removed from date: {} in {} file'.format(count, start_date, csv_filename))



        if immediateExit:
            sys.exit('CSV file corrupted 1.2.')
        with open(csv_filename, 'w') as file:
            print('\nFile', csv_filename, 'open for writing')
            file.writelines(lines)

            print('\nRemoving', count, 'lines from', csv_filename)

        fileExists = True

    except:
        if immediateExit:
            sys.exit('CSV file corrupted 1.5.')
        with open(csv_filename, 'w') as file:
            file.write(csv_headers)
            fileExists = False
    if immediateExit:
        sys.exit('CSV file corrupted 2.')

MSSQL Select statement with incremental integer column... not from a table

Try ROW_NUMBER()

http://msdn.microsoft.com/en-us/library/ms186734.aspx

Example:

SELECT
  col1,
  col2,
  ROW_NUMBER() OVER (ORDER BY col1) AS rownum
FROM tbl

com.android.build.transform.api.TransformException

This error began appearing for me when I added some new methods to my project. I knew that I was nowhere near the 65k method limit and did not want to enable multiDex support for my project if I could help it.

I resolved it by increasing the memory available to the :app:transformClassesForDexForDebug task. I did this by specifying javaMaxHeapSize in gradle.build.

gradle.build

android {
    ...
    dexOptions {
        javaMaxHeapSize "4g" //specify the heap size for the dex process
    }
}

I tried this after having had no success with other common solutions to this problem:

  • Running a project clean
  • Manually deleting the /app/build and /build directories from my project
  • Invalidating Gradle Cache and restarting Android Studio

Error

Error:Execution failed for task > ':app:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

Note: increasing the memory available to the DEX task can cause performance problems on systems with lower memory - link.

Docker official registry (Docker Hub) URL

For those wanting to explicitly declare they are pulling from dockerhub when using fabric8 maven plugin, add a new property: <docker.pull.registry>registry.hub.docker.com/library</docker.pull.registry>

I arrived on this page trying to solve problem of pulling from my AWS ECR registry when building Docker images using fabric8.

Line continue character in C#

You must use one of the following ways:

    string s = @"loooooooooooooooooooooooong loooooong
                  long long long";

string s = "loooooooooong loooong" +
           " long long" ;

The mysqli extension is missing. Please check your PHP configuration

I know this is a while ago but I encountered this and followed the other answers here but to no avail, I found the solution via this question (Stackoverflow Question)

Essentially just needed to edit the php.ini file (mine was found at c:\xampp\php\php.ini) and uncomment these lines...

;extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_pdo_mysql.dll

After restarting apache all was working as expected.

Easy way to export multiple data.frame to multiple Excel worksheets

You can also use the openxlsx library to export multiple datasets to multiple sheets in a single workbook.The advantage of openxlsx over xlsx is that openxlsx removes the dependencies on java libraries.

Write a list of data.frames to individual worksheets using list names as worksheet names.

require(openxlsx)
list_of_datasets <- list("Name of DataSheet1" = dataframe1, "Name of Datasheet2" = dataframe2)
write.xlsx(list_of_datasets, file = "writeXLSX2.xlsx")

What's the meaning of exception code "EXC_I386_GPFLT"?

EXC_I386_GPFLT is surely referring to "General Protection fault", which is the x86's way to tell you that "you did something that you are not allowed to do". It typically DOESN'T mean that you access out of memory bounds, but it could be that your code is going out of bounds and causing bad code/data to be used in a way that makes for an protection violation of some sort.

Unfortunately it can be hard to figure out exactly what the problem is without more context, there are 27 different causes listed in my AMD64 Programmer's Manual, Vol 2 from 2005 - by all accounts, it is likely that 8 years later would have added a few more.

If it is a 64-bit system, a plausible scenario is that your code is using a "non-canonical pointer" - meaning that a 64-bit address is formed in such a way that the upper 16 bits of the address aren't all copies of the top of the lower 48 bits (in other words, the top 16 bits of an address should all be 0 or all 1, based on the bit just below 16 bits). This rule is in place to guarantee that the architecture can "safely expand the number of valid bits in the address range". This would indicate that the code is either overwriting some pointer data with other stuff, or going out of bounds when reading some pointer value.

Another likely causes is unaligned access with an SSE register - in other word, reading a 16-byte SSE register from an address that isn't 16-byte aligned.

There are, as I said, many other possible reasons, but most of those involve things that "normal" code wouldn't be doing in a 32- or 64-bit OS (such as loading segment registers with invalid selector index or writing to MSR's (model specific registers)).

Return date as ddmmyyyy in SQL Server

select replace(convert(VARCHAR,getdate(),103),'/','')

select right(convert(VARCHAR,getdate(),112),2) + 
       substring(convert(VARCHAR,getdate(),112),5,2) + 
       left(convert(VARCHAR,getdate(),112),4)

jQuery change URL of form submit

Send the data from the form:

$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
  type: "PUT"
  url: url
  dataType: "script"
  data: postData

Is there a unique Android device ID?

My two cents - NB this is for a device (err) unique ID - not the installation one as discussed in the Android developers's blog.

Of note that the solution provided by @emmby falls back in a per application ID as the SharedPreferences are not synchronized across processes (see here and here). So I avoided this altogether.

Instead, I encapsulated the various strategies for getting a (device) ID in an enum - changing the order of the enum constants affects the priority of the various ways of getting the ID. The first non-null ID is returned or an exception is thrown (as per good Java practices of not giving null a meaning). So for instance I have the TELEPHONY one first - but a good default choice would be the ANDROID_ID beta:

import android.Manifest.permission;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;

// TODO : hash
public final class DeviceIdentifier {

    private DeviceIdentifier() {}

    /** @see http://code.google.com/p/android/issues/detail?id=10603 */
    private static final String ANDROID_ID_BUG_MSG = "The device suffers from "
        + "the Android ID bug - its ID is the emulator ID : "
        + IDs.BUGGY_ANDROID_ID;
    private static volatile String uuid; // volatile needed - see EJ item 71
    // need lazy initialization to get a context

    /**
     * Returns a unique identifier for this device. The first (in the order the
     * enums constants as defined in the IDs enum) non null identifier is
     * returned or a DeviceIDException is thrown. A DeviceIDException is also
     * thrown if ignoreBuggyAndroidID is false and the device has the Android ID
     * bug
     *
     * @param ctx
     *            an Android constant (to retrieve system services)
     * @param ignoreBuggyAndroidID
     *            if false, on a device with the android ID bug, the buggy
     *            android ID is not returned instead a DeviceIDException is
     *            thrown
     * @return a *device* ID - null is never returned, instead a
     *         DeviceIDException is thrown
     * @throws DeviceIDException
     *             if none of the enum methods manages to return a device ID
     */
    public static String getDeviceIdentifier(Context ctx,
            boolean ignoreBuggyAndroidID) throws DeviceIDException {
        String result = uuid;
        if (result == null) {
            synchronized (DeviceIdentifier.class) {
                result = uuid;
                if (result == null) {
                    for (IDs id : IDs.values()) {
                        try {
                            result = uuid = id.getId(ctx);
                        } catch (DeviceIDNotUniqueException e) {
                            if (!ignoreBuggyAndroidID)
                                throw new DeviceIDException(e);
                        }
                        if (result != null) return result;
                    }
                    throw new DeviceIDException();
                }
            }
        }
        return result;
    }

    private static enum IDs {
        TELEPHONY_ID {

            @Override
            String getId(Context ctx) {
                // TODO : add a SIM based mechanism ? tm.getSimSerialNumber();
                final TelephonyManager tm = (TelephonyManager) ctx
                        .getSystemService(Context.TELEPHONY_SERVICE);
                if (tm == null) {
                    w("Telephony Manager not available");
                    return null;
                }
                assertPermission(ctx, permission.READ_PHONE_STATE);
                return tm.getDeviceId();
            }
        },
        ANDROID_ID {

            @Override
            String getId(Context ctx) throws DeviceIDException {
                // no permission needed !
                final String andoidId = Secure.getString(
                    ctx.getContentResolver(),
                    android.provider.Settings.Secure.ANDROID_ID);
                if (BUGGY_ANDROID_ID.equals(andoidId)) {
                    e(ANDROID_ID_BUG_MSG);
                    throw new DeviceIDNotUniqueException();
                }
                return andoidId;
            }
        },
        WIFI_MAC {

            @Override
            String getId(Context ctx) {
                WifiManager wm = (WifiManager) ctx
                        .getSystemService(Context.WIFI_SERVICE);
                if (wm == null) {
                    w("Wifi Manager not available");
                    return null;
                }
                assertPermission(ctx, permission.ACCESS_WIFI_STATE); // I guess
                // getMacAddress() has no java doc !!!
                return wm.getConnectionInfo().getMacAddress();
            }
        },
        BLUETOOTH_MAC {

            @Override
            String getId(Context ctx) {
                BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
                if (ba == null) {
                    w("Bluetooth Adapter not available");
                    return null;
                }
                assertPermission(ctx, permission.BLUETOOTH);
                return ba.getAddress();
            }
        }
        // TODO PSEUDO_ID
        // http://www.pocketmagic.net/2011/02/android-unique-device-id/
        ;

        static final String BUGGY_ANDROID_ID = "9774d56d682e549c";
        private final static String TAG = IDs.class.getSimpleName();

        abstract String getId(Context ctx) throws DeviceIDException;

        private static void w(String msg) {
            Log.w(TAG, msg);
        }

        private static void e(String msg) {
            Log.e(TAG, msg);
        }
    }

    private static void assertPermission(Context ctx, String perm) {
        final int checkPermission = ctx.getPackageManager().checkPermission(
            perm, ctx.getPackageName());
        if (checkPermission != PackageManager.PERMISSION_GRANTED) {
            throw new SecurityException("Permission " + perm + " is required");
        }
    }

    // =========================================================================
    // Exceptions
    // =========================================================================
    public static class DeviceIDException extends Exception {

        private static final long serialVersionUID = -8083699995384519417L;
        private static final String NO_ANDROID_ID = "Could not retrieve a "
            + "device ID";

        public DeviceIDException(Throwable throwable) {
            super(NO_ANDROID_ID, throwable);
        }

        public DeviceIDException(String detailMessage) {
            super(detailMessage);
        }

        public DeviceIDException() {
            super(NO_ANDROID_ID);
        }
    }

    public static final class DeviceIDNotUniqueException extends
            DeviceIDException {

        private static final long serialVersionUID = -8940090896069484955L;

        public DeviceIDNotUniqueException() {
            super(ANDROID_ID_BUG_MSG);
        }
    }
}

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

This workaround works most of the time. It uses eclipse's 'smart insert' features instead:

  1. Control X to erase the selected block of text, and keep it for pasting.
  2. Control+Shift Enter, to open a new line for editing above the one you are at.
  3. You might want to adjust the tabbing position at this point. This is where tabbing will start, unless you are at the beginning of the line.
  4. Control V to paste back the buffer.

Hope this helps until Shift+TAB is implemented in Eclipse.

How to handle windows file upload using Selenium WebDriver?

// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");

Hey, that's mine from somewhere :).


In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:

driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");

In the case of the Uploadify web, you're in a pickle, since the upload thing is no input, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).

So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name input. Please, make sure this assumption is true in your case, too.

If not, you could try to jump to it by pressing Alt + N, at least on Windows...

If yes, you can "blindly" type the path into it using the Robot class. In your case, that would be something in the way of:

driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C);        // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON);    // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH);    // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path

r.keyPress(KeyEvent.VK_ENTER);    // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);

It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar() which does similar work, but is available only from JDK7).


For Flash, the only alternative I know (from this discussion) is to use the dark technique:

First, you modify the source code of you the flash application, exposing internal methods using the ActionScript's ExternalInterface API. Once exposed, these methods will be callable by JavaScript in the browser.

Second, now that JavaScript can call internal methods in your flash app, you use WebDriver to make a JavaScript call in the web page, which will then call into your flash app.

This technique is explained further in the docs of the flash-selenium project. (http://code.google.com/p/flash-selenium/), but the idea behind the technique applies just as well to WebDriver.

List<String> to ArrayList<String> conversion issue

In Kotlin List can be converted into ArrayList through passing it as a constructor parameter.

ArrayList(list)

How to select rows that have current day's timestamp?

This could be the easiest in my opinion:

SELECT * FROM `table` WHERE `timestamp` like concat(CURDATE(),'%');

Is there an easy way to check the .NET Framework version?

I had a situation where my .NET 4.0 class library might be called from an .NET 4.0 or higher version assemblies.

A specific method call would only work if executed from an 4.5+ assembly.

In Order to decide if I should call the method or not I needed to determine the current executing framework version and this is a pretty good solution for that

var frameworkName = new System.Runtime.Versioning.FrameworkName(
    AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName
);

if (frameworkName.Version >= new Version(4, 5)) 
{
    // run code
}

VS 2017 Metadata file '.dll could not be found

I had the same issue. My problem was someone else on the team moved a class folder, and the project was looking for it.

For me, there were 44 errors; 43 ended in .dll (searching for a dependency) and the first one in the error list ended with .cs (searching for the actual class). I tried clean-build, and clean, unload, reload, build, but nothing working. I ended up locating the class in the project, and just deleted it, as it was showing up as unavailable anyways, followed by a clean-build.

That did the trick for me! Hope this helps.

Generate random numbers uniformly over an entire range

If you are able to, use Boost. I have had good luck with their random library.

uniform_int should do what you want.

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

Hide Text with CSS, Best Practice?

If you're willing to accomodate this in your markup (as you are in your question with the holding the text), I'd go with whatever jQuery UI went with in their CSS helpers:

.ui-helper-hidden-accessible { 
    position: absolute !important; 
    clip: rect(1px 1px 1px 1px); 
    clip: rect(1px,1px,1px,1px); 
}

The image replacement techniques are good if you absolutely refuse to add extra markup for the text to be hidden in the container for the image.

Redirect to external URL with return in laravel

Also, adding class

      use Illuminate\Http\RedirectResponse;

and after, like this:

 public function show($id){

    $link = Link::findOrFail($id);  // get data from db table Links

    return new RedirectResponse($link->url);  // and this my external link, 
 }

or -

 return  new RedirectResponse("http://www.google.com?andParams=yourParams"); 

For external links have to be used full URL string with 'http' in begin.

Display Images Inline via CSS

You have a line break <br> in-between the second and third images in your markup. Get rid of that, and it'll show inline.

How to get first character of a string in SQL?

It is simple to achieve by the following

DECLARE @SomeString NVARCHAR(20) = 'This is some string'
DECLARE @Result NVARCHAR(20)

Either

SET @Result = SUBSTRING(@SomeString, 2, 3)
SELECT @Result

@Result = his

or

SET @Result = LEFT(@SomeString, 6)
SELECT @Result

@Result = This i

Converting an integer to a hexadecimal string in Ruby

You can give to_s a base other than 10:

10.to_s(16)  #=> "a"

Note that in ruby 2.4 FixNum and BigNum were unified in the Integer class. If you are using an older ruby check the documentation of FixNum#to_s and BigNum#to_s

How to configure custom PYTHONPATH with VM and PyCharm?

For PyCharm 5 (or 2016.1), you can:

  1. select Preferences > Project Interpreter
  2. to the right of interpreter selector there is a "..." button, click it
  3. select "more..."
  4. pop up a new "Project Interpreters" window
  5. select the rightest button (named "show paths for the selected interpreter")
  6. pop up a "Interpreter Paths" window
  7. click the "+" buttom > select your desired PYTHONPATH directory (the folder which contains python modules) and click OK
  8. Done! Enjoy it!

enter image description here

enter image description here

enter image description here enter image description here

C# DateTime.ParseExact

try this

var  insert = DateTime.ParseExact(line[i], "M/d/yyyy h:mm", CultureInfo.InvariantCulture);

How do I get git to default to ssh and not https for new repositories

You may have accidentally cloned the repository in https instead of ssh. I've made this mistake numerous times on github. Make sure that you copy the ssh link in the first place when cloning, instead of the https link.

Python: call a function from string name

If it's in a class, you can use getattr:

class MyClass(object):
    def install(self):
          print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
    method = getattr(my_cls, method_name)
except AttributeError:
    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method()

or if it's a function:

def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

Peak detection in a 2D array

This problem has been studied in some depth by physicists. There is a good implementation in ROOT. Look at the TSpectrum classes (especially TSpectrum2 for your case) and the documentation for them.

References:

  1. M.Morhac et al.: Background elimination methods for multidimensional coincidence gamma-ray spectra. Nuclear Instruments and Methods in Physics Research A 401 (1997) 113-132.
  2. M.Morhac et al.: Efficient one- and two-dimensional Gold deconvolution and its application to gamma-ray spectra decomposition. Nuclear Instruments and Methods in Physics Research A 401 (1997) 385-408.
  3. M.Morhac et al.: Identification of peaks in multidimensional coincidence gamma-ray spectra. Nuclear Instruments and Methods in Research Physics A 443(2000), 108-125.

...and for those who don't have access to a subscription to NIM:

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

How to write to a JSON file in the correct format

Require the JSON library, and use to_json.

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(tempHash.to_json)
end

Your temp.json file now looks like:

{"key_a":"val_a","key_b":"val_b"}

Can I map a hostname *and* a port with /etc/hosts?

If you really need to do this, use reverse proxy.

For example, with nginx as reverse proxy

server {
  listen       api.mydomain.com:80;
  server_name  api.mydomain.com;
  location / {
    proxy_pass http://127.0.0.1:8000;
  }
}

Convert an enum to List<string>

I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:

  public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes
}

In a helper class (HelperMethods) I created the following method:

 public static List<string> GetListOfDescription<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
    }

When you call this helper you will get the list of item descriptions.

 List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.

 public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
        /* how to use
            MyEnum x = MyEnum.NeedMoreCoffee;
            string description = x.GetDescription();
        */

    }

Determining type of an object in ruby

variable_name.class

Here variable name is "a" a.class

Check if file is already open

On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using

fileIsLocked = !file.renameTo(file)

most useful, as it avoids false positives when processing write protected (or readonly) files.

How to test Spring Data repositories?

If you're using Spring Boot, you can simply use @SpringBootTest to load in your ApplicationContext (which is what your stacktrace is barking at you about). This allows you to autowire in your spring-data repositories. Be sure to add @RunWith(SpringRunner.class) so the spring-specific annotations are picked up:

@RunWith(SpringRunner.class)
@SpringBootTest
public class OrphanManagementTest {

  @Autowired
  private UserRepository userRepository;

  @Test
  public void saveTest() {
    User user = new User("Tom");
    userRepository.save(user);
    Assert.assertNotNull(userRepository.findOne("Tom"));
  }
}

You can read more about testing in spring boot in their docs.

Default Activity not found in Android Studio

  1. In Android Studio

  2. Go to edit Configuration .

  3. Select the app.

  4. choose the lunch Activity path.

  5. apply, OK.

    Thanks!!

How to destroy JWT Tokens on logout?

While other answers provide detailed solutions for various setups, this might help someone who is just looking for a general answer.

There are three general options, pick one or more:

  1. On the client side, delete the cookie from the browser using javascript.

  2. On the server side, set the cookie value to an empty string or something useless (for example "deleted"), and set the cookie expiration time to a time in the past.

  3. On the server side, update the refreshtoken stored in your database. Use this option to log out the user from all devices where they are logged in (their refreshtokens will become invalid and they have to log in again).

Count number of records returned by group by

How about using a COUNT OVER (PARTITION BY {column to group by}) partitioning function in SQL Server?

For example, if you want to group product sales by ItemID and you want a count of each distinct ItemID, simply use:

SELECT
{columns you want} ,
COUNT(ItemID) OVER (PARTITION BY ItemID) as BandedItemCount ,
{more columns you want}... ,
FROM {MyTable}

If you use this approach, you can leave the GROUP BY out of the picture -- assuming you want to return the entire list (as you might do report banding where you need to know the entire count of items you are going to band without having to display the entire set of data, i.e. Reporting Services).

MySQL Job failed to start

I had the same problem. But i discover that my hd is full.

$ sudo cat /var/log/upstart/mysql.log
/proc/self/fd/9: ERROR: The partition with /var/lib/mysql is too full!

So, I run

$ df -h

And I got the message

/dev/xvda1      7.8G  7.4G     0 100% /

Then I found out which folder was full by running the following command on the terminal

$ cd /var/www
$ for i in *; do echo $i; find $i |wc -l; done

This give me the number of files on each folder on /var/www. I logged into the folder with most files, and deleted some backup files, and i continued deleting useless files and cache files.

then I run $ sudo /etc/init.d/mysql start and it work again

How to add a where clause in a MySQL Insert statement?

To add a WHERE clause inside an INSERT statement simply;

INSERT INTO table_name (column1,column2,column3)
SELECT column1, column2, column3 FROM  table_name
WHERE column1 = 'some_value'

Can I call a function of a shell script from another shell script?

The problem

The currenly accepted answer works only under important condition. Given...

/foo/bar/first.sh:

function func1 {  
   echo "Hello $1"
}

and

/foo/bar/second.sh:

#!/bin/bash

source ./first.sh
func1 World

this works only if the first.sh is executed from within the same directory where the first.sh is located. Ie. if the current working path of shell is /foo, the attempt to run command

cd /foo
./bar/second.sh

prints error:

/foo/bar/second.sh: line 4: func1: command not found

That's because the source ./first.sh is relative to current working path, not the path of the script. Hence one solution might be to utilize subshell and run

(cd /foo/bar; ./second.sh)

More generic solution

Given...

/foo/bar/first.sh:

function func1 {  
   echo "Hello $1"
}

and

/foo/bar/second.sh:

#!/bin/bash

source $(dirname "$0")/first.sh

func1 World

then

cd /foo
./bar/second.sh

prints

Hello World

How it works

  • $0 returns relative or absolute path to the executed script
  • dirname returns relative path to directory, where the $0 script exists
  • $( dirname "$0" ) the dirname "$0" command returns relative path to directory of executed script, which is then used as argument for source command
  • in "second.sh", /first.sh just appends the name of imported shell script
  • source loads content of specified file into current shell

How to check whether an array is empty using PHP?

I ran the benchmark included at the end of the post. To compare the methods:

  • count($arr) == 0 : count
  • empty($arr) : empty
  • $arr == [] : comp
  • (bool) $arr : cast

and got the following results

Contents  \method |    count     |    empty     |     comp     |     cast     |
------------------|--------------|--------------|--------------|--------------|
            Empty |/* 1.213138 */|/* 1.070011 */|/* 1.628529 */|   1.051795   |
          Uniform |/* 1.206680 */|   1.047339   |/* 1.498836 */|/* 1.052737 */|
          Integer |/* 1.209668 */|/* 1.079858 */|/* 1.486134 */|   1.051138   |
           String |/* 1.242137 */|   1.049148   |/* 1.630259 */|/* 1.056610 */|
            Mixed |/* 1.229072 */|/* 1.068569 */|/* 1.473339 */|   1.064111   |
      Associative |/* 1.206311 */|   1.053642   |/* 1.480637 */|/* 1.137740 */|
------------------|--------------|--------------|--------------|--------------|
            Total |/* 7.307005 */|   6.368568   |/* 9.197733 */|/* 6.414131 */|

The difference between empty and casting to a boolean are insignificant. I've run this test multiple times and they appear to be essentially equivalent. The contents of the arrays do not seem to play a significant role. The two produce the opposite results but the logical negation is barely enough to push casting to winning most of the time so I personally prefer empty for the sake of legibility in either case.

#!/usr/bin/php
<?php

//    012345678
$nt = 90000000;

$arr0 = [];
$arr1 = [];
$arr2 = [];
$arr3 = [];
$arr4 = [];
$arr5 = [];

for ($i = 0; $i < 500000; $i++) {
    $arr1[] = 0;
    $arr2[] = $i;
    $arr3[] = md5($i);
    $arr4[] = $i % 2 ? $i : md5($i);
    $arr5[md5($i)] = $i;
}

$t00 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr0) == 0;
}
$t01 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr0);
}
$t02 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr0 == [];
}
$t03 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr0;
}
$t04 = microtime(true);

$t10 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr1) == 0;
}
$t11 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr1);
}
$t12 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr1 == [];
}
$t13 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr1;
}
$t14 = microtime(true);

/* ------------------------------ */

$t20 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr2) == 0;
}
$t21 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr2);
}
$t22 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr2 == [];
}
$t23 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr2;
}
$t24 = microtime(true);

/* ------------------------------ */

$t30 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr3) == 0;
}
$t31 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr3);
}
$t32 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr3 == [];
}
$t33 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr3;
}
$t34 = microtime(true);

/* ------------------------------ */

$t40 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr4) == 0;
}
$t41 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr4);
}
$t42 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr4 == [];
}
$t43 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr4;
}
$t44 = microtime(true);

/* ----------------------------------- */

$t50 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    count($arr5) == 0;
}
$t51 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    empty($arr5);
}
$t52 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    $arr5 == [];
}
$t53 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
    (bool) $arr5;
}
$t54 = microtime(true);

/* ----------------------------------- */

$t60 = $t00 + $t10 + $t20 + $t30 + $t40 + $t50;
$t61 = $t01 + $t11 + $t21 + $t31 + $t41 + $t51;
$t62 = $t02 + $t12 + $t22 + $t32 + $t42 + $t52;
$t63 = $t03 + $t13 + $t23 + $t33 + $t43 + $t53;
$t64 = $t04 + $t14 + $t24 + $t34 + $t44 + $t54;

/* ----------------------------------- */

$ts0[1] = number_format(round($t01 - $t00, 6), 6);
$ts0[2] = number_format(round($t02 - $t01, 6), 6);
$ts0[3] = number_format(round($t03 - $t02, 6), 6);
$ts0[4] = number_format(round($t04 - $t03, 6), 6);

$min_idx = array_keys($ts0, min($ts0))[0];
foreach ($ts0 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts0[$idx] = "   $val   ";
    } else {
        $ts0[$idx] = "/* $val */";
    }

}

$ts1[1] = number_format(round($t11 - $t10, 6), 6);
$ts1[2] = number_format(round($t12 - $t11, 6), 6);
$ts1[3] = number_format(round($t13 - $t12, 6), 6);
$ts1[4] = number_format(round($t14 - $t13, 6), 6);

$min_idx = array_keys($ts1, min($ts1))[0];
foreach ($ts1 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts1[$idx] = "   $val   ";
    } else {
        $ts1[$idx] = "/* $val */";
    }

}

$ts2[1] = number_format(round($t21 - $t20, 6), 6);
$ts2[2] = number_format(round($t22 - $t21, 6), 6);
$ts2[3] = number_format(round($t23 - $t22, 6), 6);
$ts2[4] = number_format(round($t24 - $t23, 6), 6);

$min_idx = array_keys($ts2, min($ts2))[0];
foreach ($ts2 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts2[$idx] = "   $val   ";
    } else {
        $ts2[$idx] = "/* $val */";
    }

}

$ts3[1] = number_format(round($t31 - $t30, 6), 6);
$ts3[2] = number_format(round($t32 - $t31, 6), 6);
$ts3[3] = number_format(round($t33 - $t32, 6), 6);
$ts3[4] = number_format(round($t34 - $t33, 6), 6);

$min_idx = array_keys($ts3, min($ts3))[0];
foreach ($ts3 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts3[$idx] = "   $val   ";
    } else {
        $ts3[$idx] = "/* $val */";
    }

}

$ts4[1] = number_format(round($t41 - $t40, 6), 6);
$ts4[2] = number_format(round($t42 - $t41, 6), 6);
$ts4[3] = number_format(round($t43 - $t42, 6), 6);
$ts4[4] = number_format(round($t44 - $t43, 6), 6);

$min_idx = array_keys($ts4, min($ts4))[0];
foreach ($ts4 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts4[$idx] = "   $val   ";
    } else {
        $ts4[$idx] = "/* $val */";
    }

}

$ts5[1] = number_format(round($t51 - $t50, 6), 6);
$ts5[2] = number_format(round($t52 - $t51, 6), 6);
$ts5[3] = number_format(round($t53 - $t52, 6), 6);
$ts5[4] = number_format(round($t54 - $t53, 6), 6);

$min_idx = array_keys($ts5, min($ts5))[0];
foreach ($ts5 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts5[$idx] = "   $val   ";
    } else {
        $ts5[$idx] = "/* $val */";
    }

}

$ts6[1] = number_format(round($t61 - $t60, 6), 6);
$ts6[2] = number_format(round($t62 - $t61, 6), 6);
$ts6[3] = number_format(round($t63 - $t62, 6), 6);
$ts6[4] = number_format(round($t64 - $t63, 6), 6);

$min_idx = array_keys($ts6, min($ts6))[0];
foreach ($ts6 as $idx => $val) {
    if ($idx == $min_idx) {
        $ts6[$idx] = "   $val   ";
    } else {
        $ts6[$idx] = "/* $val */";
    }

}

echo "             |    count     |    empty     |     comp     |     cast     |\n";
echo "-------------|--------------|--------------|--------------|--------------|\n";
echo "       Empty |";
echo $ts0[1] . '|';
echo $ts0[2] . '|';
echo $ts0[3] . '|';
echo $ts0[4] . "|\n";

echo "     Uniform |";
echo $ts1[1] . '|';
echo $ts1[2] . '|';
echo $ts1[3] . '|';
echo $ts1[4] . "|\n";

echo "     Integer |";
echo $ts2[1] . '|';
echo $ts2[2] . '|';
echo $ts2[3] . '|';
echo $ts2[4] . "|\n";

echo "      String |";
echo $ts3[1] . '|';
echo $ts3[2] . '|';
echo $ts3[3] . '|';
echo $ts3[4] . "|\n";

echo "       Mixed |";
echo $ts4[1] . '|';
echo $ts4[2] . '|';
echo $ts4[3] . '|';
echo $ts4[4] . "|\n";

echo " Associative |";
echo $ts5[1] . '|';
echo $ts5[2] . '|';
echo $ts5[3] . '|';
echo $ts5[4] . "|\n";

echo "-------------|--------------|--------------|--------------|--------------|\n";
echo "       Total |";
echo $ts6[1] . '|';
echo $ts6[2] . '|';
echo $ts6[3] . '|';
echo $ts6[4] . "|\n";

How to pass variable as a parameter in Execute SQL Task SSIS?

SELECT, INSERT, UPDATE, and DELETE commands frequently include WHERE clauses to specify filters that define the conditions each row in the source tables must meet to qualify for an SQL command. Parameters provide the filter values in the WHERE clauses.

You can use parameter markers to dynamically provide parameter values. The rules for which parameter markers and parameter names can be used in the SQL statement depend on the type of connection manager that the Execute SQL uses.

The following table lists examples of the SELECT command by connection manager type. The INSERT, UPDATE, and DELETE statements are similar. The examples use SELECT to return products from the Product table in AdventureWorks2012 that have a ProductID greater than and less than the values specified by two parameters.

EXCEL, ODBC, and OLEDB

SELECT* FROM Production.Product WHERE ProductId > ? AND ProductID < ?

ADO

SELECT * FROM Production.Product WHERE ProductId > ? AND ProductID < ?

ADO.NET

SELECT* FROM Production.Product WHERE ProductId > @parmMinProductID 
     AND ProductID < @parmMaxProductID

The examples would require parameters that have the following names: The EXCEL and OLED DB connection managers use the parameter names 0 and 1. The ODBC connection type uses 1 and 2. The ADO connection type could use any two parameter names, such as Param1 and Param2, but the parameters must be mapped by their ordinal position in the parameter list. The ADO.NET connection type uses the parameter names @parmMinProductID and @parmMaxProductID.

Clear input fields on form submit

Still using empty strings you can use:

document.getElementById("name").value = '';
document.getElementById("review").value = '';

How do I dump an object's fields to the console?

Possibly:

puts variable.inspect

Is Java RegEx case-insensitive?

You also can lead your initial string, which you are going to check for pattern matching, to lower case. And use in your pattern lower case symbols respectively.

React-Native: Application has not been registered error

In my case i have got a different solution in case any one need

yarn remove react-native-material-dropdown

Install new packages react-native-material-dropdown-v2

yarn add react-native-material-dropdown-v2

Replace react-native-material-dropdown with react-native-material-dropdown-v2 in your code

e.g. import { Dropdown } from 'react-native-material-dropdown' to import { Dropdown } from 'react-native-material-dropdown-v2'

another thing ==========

  1. Open node_modules and then search for react-native-material-textfield open the file and go to src folder
  2. Under src you will see affix, helper, label folder - under each folder, there is an index.js
  3. open the index.js of the mentioned folders one by one (all 3 folders) and search for the text style: Animated.Text.propTypes.style, and replace it by style: Text.propTypes
  4. And import text form react-native like this import { Animated , Text} from 'react-native';

Read and overwrite a file in Python

The fileinput module has an inplace mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via an object which transparently keeps track of the file name, line number etc if you should want to inspect them inside the loop.

from fileinput import FileInput
for line in FileInput("file", inplace=1):
    line = line.replace("foobar", "bar")
    print(line)

Import regular CSS file in SCSS file?

If I am correct css is compatible with scss so you can change the extension of a css to scss and it should continue to work. Once you change the extension you can import it and it will be included in the file.

If you don't do that sass will use the css @import which is something you don't want.

How to invoke the super constructor in Python?

Just to add an example with parameters:

class B(A):
    def __init__(self, x, y, z):
        A.__init__(self, x, y)

Given a derived class B that requires the variables x, y, z to be defined, and a superclass A that requires x, y to be defined, you can call the static method init of the superclass A with a reference to the current subclass instance (self) and then the list of expected arguments.

Unable to start Service Intent

First, you do not need android:process=":remote", so please remove it, since all it will do is take up extra RAM for no benefit.

Second, since the <service> element contains an action string, use it:

public void onCreate(Bundle savedInstanceState) {    
      super.onCreate(savedInstanceState);  
      Intent intent=new Intent("com.sample.service.serviceClass");  
      this.startService(intent);
}

bypass invalid SSL certificate in .net core

ServicePointManager.ServerCertificateValidationCallback isn't supported in .Net Core.

Current situation is that it will be a a new ServerCertificateCustomValidationCallback method for the upcoming 4.1.* System.Net.Http contract (HttpClient). .NET Core team are finalizing the 4.1 contract now. You can read about this in here on github

You can try out the pre-release version of System.Net.Http 4.1 by using the sources directly here in CoreFx or on the MYGET feed: https://dotnet.myget.org/gallery/dotnet-core

Current WinHttpHandler.ServerCertificateCustomValidationCallback definition on Github

Finding absolute value of a number without using Math.abs()

Yes:

abs_number = (number < 0) ? -number : number;

For integers, this works fine (except for Integer.MIN_VALUE, whose absolute value cannot be represented as an int).

For floating-point numbers, things are more subtle. For example, this method -- and all other methods posted thus far -- won't handle the negative zero correctly.

To avoid having to deal with such subtleties yourself, my advice would be to stick to Math.abs().

Check if a string is not NULL or EMPTY

You don't necessarily have to use the [string]:: prefix. This works in the same way:

if ($version)
{
    $request += "/" + $version
}

A variable that is null or empty string evaluates to false.

Can Flask have optional URL parameters?

I know this post is really old but I worked on a package that does this called flask_optional_routes. The code is located at: https://github.com/sudouser2010/flask_optional_routes.

from flask import Flask

from flask_optional_routes import OptionalRoutes


app = Flask(__name__)
optional = OptionalRoutes(app)

@optional.routes('/<user_id>/<user_name>?/')
def foobar(user_id, user_name=None):
    return 'it worked!'

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

How to show/hide if variable is null

In this case, myvar should be a boolean value. If this variable is true, it will show the div, if it's false.. It will hide.

Check this out.

Get div height with plain JavaScript

var clientHeight = document.getElementById('myDiv').clientHeight;

or

var offsetHeight = document.getElementById('myDiv').offsetHeight;

clientHeight includes padding.

offsetHeight includes padding, scrollBar and borders.

When should I use Lazy<T>?

You should try to avoid using Singletons, but if you ever do need to, Lazy<T> makes implementing lazy, thread-safe singletons easy:

public sealed class Singleton
{
    // Because Singleton's constructor is private, we must explicitly
    // give the Lazy<Singleton> a delegate for creating the Singleton.
    static readonly Lazy<Singleton> instanceHolder =
        new Lazy<Singleton>(() => new Singleton());

    Singleton()
    {
        // Explicit private constructor to prevent default public constructor.
        ...
    }

    public static Singleton Instance => instanceHolder.Value;
}

How to run certain task every day at a particular time using ScheduledExecutorService?

Have you considered using something like Quartz Scheduler? This library has a mechanism for scheduling tasks to run at a set period of time every day using a cron like expression (take a look at CronScheduleBuilder).

Some example code (not tested):

public class GetDatabaseJob implements InterruptableJob
{
    public void execute(JobExecutionContext arg0) throws JobExecutionException
    {
        getFromDatabase();
    }
}

public class Example
{
    public static void main(String[] args)
    {
        JobDetails job = JobBuilder.newJob(GetDatabaseJob.class);

        // Schedule to run at 5 AM every day
        ScheduleBuilder scheduleBuilder = 
                CronScheduleBuilder.cronSchedule("0 0 5 * * ?");
        Trigger trigger = TriggerBuilder.newTrigger().
                withSchedule(scheduleBuilder).build();

        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.scheduleJob(job, trigger);

        scheduler.start();
    }
}

There's a bit more work upfront, and you may need to rewrite your job execution code, but it should give you more control over how you want you job to run. Also it would be easier to change the schedule should you need to.

Entity Framework select distinct name

Try this:

var results = (from ta in context.TestAddresses
               select ta.Name).Distinct();

This will give you an IEnumerable<string> - you can call .ToList() on it to get a List<string>.

Determine which element the mouse pointer is on top of in JavaScript

Although the following may not actually answering the question, since this is the first result of googling (the googler may not asking exactly the same question:), hope it will provide some extra input.

There are actually two different approaches to get a list of all elements the mouse is currently over (for newer browsers, perhaps):

The "structural" approach - Ascending DOM tree

As in dherman's answer, one can call

var elements = document.querySelectorAll(':hover');

However, this assumes that only children will overlay their ancestors, which is usually the case, but not true in general, especially when dealing with SVG where element in different branches of the DOM tree may overlap each other.

The "visual" approach - Based on "visual" overlapping

This method uses document.elementFromPoint(x, y) to find the topmost element, temporarily hide it (since we recover it immediately in the same context, the browser will not actually renders this), then go on to find the second topmost element... Looks a little hacky, but it returns what you expect when there are, e.g., siblings elements in a tree occluding each other. Please find this post for more details,

function allElementsFromPoint(x, y) {
    var element, elements = [];
    var old_visibility = [];
    while (true) {
        element = document.elementFromPoint(x, y);
        if (!element || element === document.documentElement) {
            break;
        }
        elements.push(element);
        old_visibility.push(element.style.visibility);
        element.style.visibility = 'hidden'; // Temporarily hide the element (without changing the layout)
    }
    for (var k = 0; k < elements.length; k++) {
        elements[k].style.visibility = old_visibility[k];
    }
    elements.reverse();
    return elements;
}

Try both, and check their different returns.

how to install multiple versions of IE on the same system?

To answer your question: no, it's not possible to have multiple versions of IE (if that is what you meant) installed in a 'normal' way (i.e. not a hack, a sandbox or a VM etc). It's perfectly ok to have multiple browsers of different types installed on the same machine, such as IE8, Firefox 3 and Chrome all at once.

SandboxIE should allow you to install multiple versions of IE side-by-side (as well as other software), and this is less hassle than going down the virtual machine route.

However, from a QA point of view I'd strongly recommend installing different versions on different machines as the best option from a testing point of view. This will give you the most realistic testing environment. If you don't have the hardware for that, then virtual machines are the next best option as mentioned in some of the other answers.

What's the best way to share data between activities?

You could extend the Application class and tag on any objects you want there, they are then available anywhere in your application

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This error is usually observed when your machine is low on disk space. Steps to be followed to avoid this error message

  1. Resetting the read-only index block on the index:

    $ curl -X PUT -H "Content-Type: application/json" http://127.0.0.1:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
    
    Response
    ${"acknowledged":true}
    
  2. Updating the low watermark to at least 50 gigabytes free, a high watermark of at least 20 gigabytes free, and a flood stage watermark of 10 gigabytes free, and updating the information about the cluster every minute

     Request
     $curl -X PUT "http://127.0.0.1:9200/_cluster/settings?pretty" -H 'Content-Type: application/json' -d' { "transient": { "cluster.routing.allocation.disk.watermark.low": "50gb", "cluster.routing.allocation.disk.watermark.high": "20gb", "cluster.routing.allocation.disk.watermark.flood_stage": "10gb", "cluster.info.update.interval": "1m"}}'
    
      Response
      ${
       "acknowledged" : true,
       "persistent" : { },
       "transient" : {
       "cluster" : {
       "routing" : {
       "allocation" : {
       "disk" : {
         "watermark" : {
           "low" : "50gb",
           "flood_stage" : "10gb",
           "high" : "20gb"
         }
       }
     }
    }, 
    "info" : {"update" : {"interval" : "1m"}}}}}
    

After running these two commands, you must run the first command again so that the index does not go again into read-only mode

Add a pipe separator after items in an unordered list unless that item is the last on a line

Slightly modified SCSS version which gives you control of the pipe | size and will eliminate padding from first and last list items while respects borders.


$pipe-list-height: 20px;
$pipe-list-padding: 15px;

.pipe-list {
    position: relative;
    overflow: hidden;
    height: $pipe-list-height;

    > ul {
        display: flex;
        flex-direction: row;

        > li {
            position: relative;
            padding: 0 $pipe-list-padding;

            &:after {
                content: " ";
                position: absolute;
                border-right: 1px solid gray;
                top: 10%;
                right: 0;
                height: 75%;
                margin-top: auto;
                margin-bottom: auto;
            }

            &:first-child {
                padding-left: 0;
            }

            &:last-child {
                padding-right: 0;

                &:after {
                    border-right: none;
                }
            }
        }
    }
}
<div class="pipe-list">
  <ul>
    <li>Link</li>
    <li>Link</li>
    <li>Link</li>
  </ul>
</div>

Polling the keyboard (detect a keypress) in python

From the comments:

import msvcrt # built-in module

def kbfunc():
    return ord(msvcrt.getch()) if msvcrt.kbhit() else 0

Thanks for the help. I ended up writing a C DLL called PyKeyboardAccess.dll and accessing the crt conio functions, exporting this routine:

#include <conio.h>

int kb_inkey () {
   int rc;
   int key;

   key = _kbhit();

   if (key == 0) {
      rc = 0;
   } else {
      rc = _getch();
   }

   return rc;
}

And I access it in python using the ctypes module (built into python 2.5):

import ctypes
import time

#
# first, load the DLL
#


try:
    kblib = ctypes.CDLL("PyKeyboardAccess.dll")
except:
    raise ("Error Loading PyKeyboardAccess.dll")


#
# now, find our function
#

try:
    kbfunc = kblib.kb_inkey
except:
    raise ("Could not find the kb_inkey function in the dll!")


#
# Ok, now let's demo the capability
#

while 1:
    x = kbfunc()

    if x != 0:
        print "Got key: %d" % x
    else:
        time.sleep(.01)

How do I execute a *.dll file

It should be mentioned that since it is entirely possible to run DLL's just as any other executable, it has long been considered a security issue. As such, there have been a number of security improvements and registry hacks (sorry no longer have ref-links) that prevents running DLL's from regular user space without extra privileges.

As a good example. I recall making these hacks, but since I no longer remember what exactly I did. I can no longer run any DLLs from normal user shell environment, even though starting various Win apps from GUI works just fine.

That said, one should definitely read "Dynamic-Link Library Security" and "Best Practices to Prevent DLL Hijacking".

Search for "does-not-contain" on a DataFrame in pandas

I hope the answers are already posted

I am adding the framework to find multiple words and negate those from dataFrame.

Here 'word1','word2','word3','word4' = list of patterns to search

df = DataFrame

column_a = A column name from from DataFrame df

Search_for_These_values = ['word1','word2','word3','word4'] 

pattern = '|'.join(Search_for_These_values)

result = df.loc[~(df['column_a'].str.contains(pattern, case=False)]

How can I delete all cookies with JavaScript?

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

How to convert string to integer in C#

Do something like:

var result = Int32.Parse(str);

HTML input file selection event not firing upon selecting the same file

<form enctype='multipart/form-data'>
    <input onchange="alert(this.value); this.value=null; return false;" type='file'>
    <br>
    <input type='submit' value='Upload'>
</form>

this.value=null; is only necessary for Chrome, Firefox will work fine just with return false;

Here is a FIDDLE

Writing Python lists to columns in csv

I just wanted to add to this one- because quite frankly, I banged my head against it for a while - and while very new to python - perhaps it will help someone else out.

 writer.writerow(("ColName1", "ColName2", "ColName"))
                 for i in range(len(first_col_list)):
                     writer.writerow((first_col_list[i], second_col_list[i], third_col_list[i]))

Convert a String representation of a Dictionary to a dictionary?

https://docs.python.org/3.8/library/json.html

JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...

import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}

NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.

More about json single quote: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Set session variable in laravel

In Laravel 5.6, you will need to set it as

  session(['variableName'=>$value]);

To retrieve it is as simple as

$variableName = session('variableName')

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

The solution to this was just to change the USB cable, having enabled ADB Integration via

Tools > Android > Enable ADB Integration.

Graph visualization library in JavaScript

JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.

prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.

What's the difference between Git Revert, Checkout and Reset?

These three commands have entirely different purposes. They are not even remotely similar.

git revert

This command creates a new commit that undoes the changes from a previous commit. This command adds new history to the project (it doesn't modify existing history).

git checkout

This command checks-out content from the repository and puts it in your work tree. It can also have other effects, depending on how the command was invoked. For instance, it can also change which branch you are currently working on. This command doesn't make any changes to the history.

git reset

This command is a little more complicated. It actually does a couple of different things depending on how it is invoked. It modifies the index (the so-called "staging area"). Or it changes which commit a branch head is currently pointing at. This command may alter existing history (by changing the commit that a branch references).

Using these commands

If a commit has been made somewhere in the project's history, and you later decide that the commit is wrong and should not have been done, then git revert is the tool for the job. It will undo the changes introduced by the bad commit, recording the "undo" in the history.

If you have modified a file in your working tree, but haven't committed the change, then you can use git checkout to checkout a fresh-from-repository copy of the file.

If you have made a commit, but haven't shared it with anyone else and you decide you don't want it, then you can use git reset to rewrite the history so that it looks as though you never made that commit.

These are just some of the possible usage scenarios. There are other commands that can be useful in some situations, and the above three commands have other uses as well.

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

I needed to connect to remote Amazon server

ssh -i ~/.ssh/test.pem -fN -L 5555:localhost:5678 [email protected]

I was getting the following error.

ssh: Could not resolve hostname <hostname.com>: nodename nor servname provided, or not known

Solution For Mac OSX

Pinging the host resolved the issue. I am using Mac OSX Seirra.

ping hostname.com

Now problem resolved. Able to connect to the server.

Note: I tried this solution also. But it didn't work out. Then ping resolved the issue.

How can you make a custom keyboard in Android?

Use KeyboardView:

KeyboardView kbd = new KeyboardView(context);
kbd.setKeyboard(new Keyboard(this, R.xml.custom));

kbd.setOnKeyboardActionListener(new OnKeyboardActionListener() {
    ....
}

now you have kbd which is a normal view.

The nice thing about this is that R.xml.custom refers to /res/xml/custom.xml, which defines in xml the layout of the keyboard. For more information on this file, look here: Keyboard, Keyboard.Row, Keyboard.Key.

Remove Item from ArrayList

How about this? Just give it a thought-

import java.util.ArrayList;

class Solution
{
        public static void main (String[] args){

             ArrayList<String> List_Of_Array = new ArrayList<String>();
             List_Of_Array.add("A");
             List_Of_Array.add("B");
             List_Of_Array.add("C");
             List_Of_Array.add("D");
             List_Of_Array.add("E");
             List_Of_Array.add("F");
             List_Of_Array.add("G");
             List_Of_Array.add("H");

             int i[] = {1,3,5};

             for (int j = 0; j < i.length; j++) {
                 List_Of_Array.remove(i[j]-j);
             }

             System.out.println(List_Of_Array);

        }


}

And the output was-

[A, C, E, G, H]

Getting the last n elements of a vector. Is there a better way than using the length() function?

I just add here something related. I was wanted to access a vector with backend indices, ie writting something like tail(x, i) but to return x[length(x) - i + 1] and not the whole tail.

Following commentaries I benchmarked two solutions:

accessRevTail <- function(x, n) {
    tail(x,n)[1]
}

accessRevLen <- function(x, n) {
  x[length(x) - n + 1]
}

microbenchmark::microbenchmark(accessRevLen(1:100, 87), accessRevTail(1:100, 87))
Unit: microseconds
                     expr    min      lq     mean median      uq     max neval
  accessRevLen(1:100, 87)  1.860  2.3775  2.84976  2.803  3.2740   6.755   100
 accessRevTail(1:100, 87) 22.214 23.5295 28.54027 25.112 28.4705 110.833   100

So it appears in this case that even for small vectors, tail is very slow comparing to direct access

How should I set the default proxy to use default credentials?

For those who, unlike Brian Genisio, are able to set the contents of their application's config file:- don't do anything in code. Instead add this to your app.config / web.config.

<system.net>
  <defaultProxy useDefaultCredentials="true" />
</system.net>

Really and truly the default for using the default credentials should be "true"; I've seen this issue confuse so many people - developers, users, IT guys.

For more info see here:- http://sticklebackplastic.com/post/2007/01/26/Poxy-proxies.aspx

UPDATE: I've created this issue/idea for Microsoft to change the default of useDefaultCredentials from false to true so that this whole problem goes away and .NET apps "just work"; please vote it up if you agree:
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2397357-fix-it-so-that-net-apps-can-access-http-thru-auth

A Space between Inline-Block List Items

I have seen this and answered on it before:

After further research I have discovered that inline-block is a whitespace dependent method and is dependent on the font setting. In this case 4px is rendered.

To avoid this you could run all your lis together in one line, or block the end tags and begin tags together like this:

<ul>
        <li>
            <div>first</div>
        </li><li>
            <div>first</div>
        </li><li>
            <div>first</div>
        </li><li>
            <div>first</div>
        </li>
</ul>

Example here.


As mentioned by other answers and comments, the best practice for solving this is to add font-size: 0; to the parent element:

ul {
    font-size: 0;
}

ul li {
    font-size: 14px;
    display: inline-block;
}

This is better for HTML readability (avoiding running the tags together etc). The spacing effect is because of the font's spacing setting, so you must reset it for the inlined elements and set it again for the content within.

Why do you create a View in a database?

One curious thing about views are that they are seen by Microsoft Access as tables: when you attach a Microsoft Access front-end to an SQL database using ODBC, you see the tables and views in the list of available tables. So if you are preparing complicated reports in MS Access, you can let the SQL server do the joining and querying, and greatly simplify your life. Ditto for preparing a query in MS Excel.

hide/show a image in jquery

I had to do something like this just now. I ended up doing:

function newWaitImg(id) {
    var img = {
       "id" : id,
       "state" : "on",
       "hide" : function () {
           $(this.id).hide();
           this.state = "off";
       },
       "show" : function () {
           $(this.id).show();
           this.state = "on";
       },
       "toggle" : function () {
           if (this.state == "on") {
               this.hide();
           } else {
               this.show();
           }
       }
    };
};

.
.
.

var waitImg = newWaitImg("#myImg");
.
.
.
waitImg.hide(); / waitImg.show(); / waitImg.toggle();

What is the difference between Sublime text and Github's Atom

Atom is still in beta (v0.123 as I'm writing this) but it's moving fast. Way faster than Sublime. New builds are released on a weekly basis, sometimes even few of them in the same week. In its short life span, it had more releases than Sublime which takes months to release a new feature or a bug fix. Here's an updated take on things looking back on the path Atom has taken since the launch of the beta:

  1. Sublime has better performance than Atom. Simply because it's written in C++. Atom on the other hand is a web based desktop app built on top of Chromium, and while they take performance close to heart, it will be really hard or even impossible to reach the same speed and responsiveness. Last July Atom began using React and it gave it a nice performance boost but you can still feel the difference. Apart from that, if Atom’s performance issues will not push users away - Sublime better speed up the release cycle, brush up its small UX tweaks, and consider letting in more contributors because this is where Atom is winning.

  2. Atom's package ecosystem is also growing really fast, it might not be as big as Sublime's at the moment but I have a feeling that with GitHub at it's back it will keep growing even faster. It probably has the majority of IDE like plug-ins you can think of. A major difference right now is that it can't handle files bigger than 2MB so it's something to keep in mind.

  3. The one thing you'll notice first is that the Sublime minimap is gone! Other than that, the first impression is that Atom looks almost the same as Sublime. I wrote a more in depth comparison about it in this blog post.

  4. No easy straightforward way to port your Sublime configurations, packages and such as far as I know.

How to overwrite styling in Twitter Bootstrap

You can just make sure your css file parses AFTER boostrap.css , like so:

<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/myFile.css" rel="stylesheet">

how to find my angular version in my project?

you can use ng --version for angular version 7

Getting next element while cycling through a list

while running:
    for elem,next_elem in zip(li, li[1:]+[li[0]]):
        ...

Why is processing a sorted array faster than processing an unsorted array?

That's for sure!...

Branch prediction makes the logic run slower, because of the switching which happens in your code! It's like you are going a straight street or a street with a lot of turnings, for sure the straight one is going to be done quicker!...

If the array is sorted, your condition is false at the first step: data[c] >= 128, then becomes a true value for the whole way to the end of the street. That's how you get to the end of the logic faster. On the other hand, using an unsorted array, you need a lot of turning and processing which make your code run slower for sure...

Look at the image I created for you below. Which street is going to be finished faster?

Branch Prediction

So programmatically, branch prediction causes the process to be slower...

Also at the end, it's good to know we have two kinds of branch predictions that each is going to affect your code differently:

1. Static

2. Dynamic

Branch Prediction

Static branch prediction is used by the microprocessor the first time a conditional branch is encountered, and dynamic branch prediction is used for succeeding executions of the conditional branch code.

In order to effectively write your code to take advantage of these rules, when writing if-else or switch statements, check the most common cases first and work progressively down to the least common. Loops do not necessarily require any special ordering of code for static branch prediction, as only the condition of the loop iterator is normally used.

How to add MVC5 to Visual Studio 2013?

Go File -> New Project.

Select Web under Visual C#.

Select ASP.NET Web Application

select mvc

when solution is created, you will find resources getting added in solution in status bar of vs 2013.

Check property of Dll file --> system.web.mvc, it shows latest version (5.2.2.0)

but depending on your OS runtime version will be decided.

Highcharts - redraw() vs. new Highcharts.chart

var newData = [1,2,3,4,5,6,7];
var chart = $('#chartjs').highcharts();
chart.series[0].setData(newData, true);

Explanation:
Variable newData contains value that want to update in chart. Variable chart is an object of a chart. setData is a method provided by highchart to update data.

Method setData contains two parameters, in first parameter we need to pass new value as array and second param is Boolean value. If true then chart updates itself and if false then we have to use redraw() method to update chart (i.e chart.redraw();)

http://jsfiddle.net/NxEnH/8/

How to detect READ_COMMITTED_SNAPSHOT is enabled?

  1. As per https://msdn.microsoft.com/en-us/library/ms180065.aspx, "DBCC USEROPTIONS reports an isolation level of 'read committed snapshot' when the database option READ_COMMITTED_SNAPSHOT is set to ON and the transaction isolation level is set to 'read committed'. The actual isolation level is read committed."

  2. Also in SQL Server Management Studio, in database properties under Options->Miscellaneous there is "Is Read Committed Snapshot On" option status

Python - Passing a function into another function

Just pass it in like any other parameter:

def a(x):
    return "a(%s)" % (x,)

def b(f,x):
    return f(x)

print b(a,10)

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

MySQL Cannot drop index needed in a foreign key constraint

A foreign key always requires an index. Without an index enforcing the constraint would require a full table scan on the referenced table for every inserted or updated key in the referencing table. And that would have an unacceptable performance impact. This has the following 2 consequences:

  • When creating a foreign key, the database checks if an index exists. If not an index will be created. By default, it will have the same name as the constraint.
  • When there is only one index that can be used for the foreign key, it can't be dropped. If you really wan't to drop it, you either have to drop the foreign key constraint or to create another index for it first.

Check if element is visible in DOM

According to this MDN documentation, an element's offsetParent property will return null whenever it, or any of its parents, is hidden via the display style property. Just make sure that the element isn't fixed. A script to check this, if you have no position: fixed; elements on your page, might look like:

// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    return (el.offsetParent === null)
}

On the other hand, if you do have position fixed elements that might get caught in this search, you will sadly (and slowly) have to use window.getComputedStyle(). The function in that case might be:

// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    var style = window.getComputedStyle(el);
    return (style.display === 'none')
}

Option #2 is probably a little more straightforward since it accounts for more edge cases, but I bet its a good deal slower, too, so if you have to repeat this operation many times, best to probably avoid it.

Binding List<T> to DataGridView in WinForm

After adding new item to persons add:

myGrid.DataSource = null;
myGrid.DataSource = persons;

How do I get extra data from intent on Android?

Kotlin

First Activity

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)

Second Activity

val value = getIntent().getStringExtra("key")

Suggestion

Always put keys in constant file for more managed way.

companion object {
    val PUT_EXTRA_USER = "PUT_EXTRA_USER"
}