Programs & Examples On #Avrdude

AVRDUDE is used in development for Atmel AVR microcontrollers to access the contents of the ROM/EEPROM memories on the target platforms.

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

My issue was due to what physical USB female port I plugged the Arduino cable into on my D-Link DUB-H7 (USB hub) on Windows 10. I had my Arduino plugged into one of the two ports way on the right (in the image below). The USB cable fit, and it powers the Arduino fine, but the Arduino wasn't seeing the port for some reason.

enter image description here

Windows does not recognize these two ports. Any of the other ports are fair game. In my case, the Tools > Port menu was grayed out. In this scenario, the "Ports" section in the object explorer was hidden. So to show the hidden devices, I chose View > show hidden. COM1 was what showed up originally. When I changed it to COM3, it didn't work.

There are many places where the COM port can be configured.

Windows > Control Panel > Device Manager > Ports > right click Arduino > Properties > Port Settings > Advanced > COM Port Number: [choose port]

Windows > Start Menu > Arduino > Tools > Ports > [choose port]

Windows > Start Menu > Arduino > File > Preferences > @ very bottom, there is a label named "More preferences can be edited directly in the file".

C:\Users{user name}\AppData\Local\Arduino15\preferences.txt

target_package = arduino
target_platform = avr
board = uno
software=ARDUINO
# Warn when data segment uses greater than this percentage
build.warn_data_percentage = 75

programmer = arduino:avrispmkii

upload.using = bootloader
upload.verify = true

serial.port=COM3
serial.databits=8
serial.stopbits=1
serial.parity=N
serial.debug_rate=9600

# I18 Preferences

# default chosen language (none for none)
editor.languages.current = 

The user preferences.txt overrides this one:

C:\Users{user name}\Desktop\avrdude.conf

... search for "com" ... "com1" is the default

avrdude: stk500v2_ReceiveMessage(): timeout

I was running this code from Arduino setup , got same error resolve after changing
serial port to COM13
GO TO Option
tool>> serial port>> COM132

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

For me the following work-around worked:

  • split the array up into smaller sub arrays
  • resize the sub arrays
  • merge the sub arrays again

Here the code:

def split_up_resize(arr, res):
    """
    function which resizes large array (direct resize yields error (addedtypo))
    """

    # compute destination resolution for subarrays
    res_1 = (res[0], res[1]/2)
    res_2 = (res[0], res[1] - res[1]/2)

    # get sub-arrays
    arr_1 = arr[0 : len(arr)/2]
    arr_2 = arr[len(arr)/2 :]

    # resize sub arrays
    arr_1 = cv2.resize(arr_1, res_1, interpolation = cv2.INTER_LINEAR)
    arr_2 = cv2.resize(arr_2, res_2, interpolation = cv2.INTER_LINEAR)

    # init resized array
    arr = np.zeros((res[1], res[0]))

    # merge resized sub arrays
    arr[0 : len(arr)/2] = arr_1
    arr[len(arr)/2 :] = arr_2

    return arr

Default string initialization: NULL or Empty?

I either set it to "" or null - I always check by using String.IsNullOrEmpty, so either is fine.

But the inner geek in me says I should set it to null before I have a proper value for it...

Convert list of ASCII codes to string (byte array) in Python

This is reviving an old question, but in Python 3, you can just use bytes directly:

>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'

Read connection string from web.config

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;  

C#

string constring = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constring))

BELOW WEB.CONFIG FILE CODE

<connectionStrings>
    <add name="ABCD" connectionString="Data Source=DESKTOP-SU3NKUU\MSSQLSERVER2016;Initial Catalog=TESTKISWRMIP;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

In the above Code ABCD is the Connection Name

Vertical align in bootstrap table

Based on what you have provided your CSS selector is not specific enough to override the CSS rules defined by Bootstrap.

Try this:

.table > tbody > tr > td {
     vertical-align: middle;
}

In Boostrap 4, this can be achieved with the .align-middle Vertical Alignment utility class.

<td class="align-middle">Text</td>

Where does MAMP keep its php.ini?

It depends on which version of PHP your MAMP is using. You can find it out on: /Applications/MAMP/conf/apache/httpd.conf looking for the configured php5_module.

After that, as someone said before, you have to go to the bin folder. There you'll find a conf folder with a php.ini inside.

example: /Applications/MAMP/bin/php/php5.4.10/conf

Leo

NotificationCompat.Builder deprecated in Android O

Call the 2-arg constructor: For compatibility with Android O, call support-v4 NotificationCompat.Builder(Context context, String channelId). When running on Android N or earlier, the channelId will be ignored. When running on Android O, also create a NotificationChannel with the same channelId.

Out of date sample code: The sample code on several JavaDoc pages such as Notification.Builder calling new Notification.Builder(mContext) is out of date.

Deprecated constructors: Notification.Builder(Context context) and v4 NotificationCompat.Builder(Context context) are deprecated in favor of Notification[Compat].Builder(Context context, String channelId). (See Notification.Builder(android.content.Context) and v4 NotificationCompat.Builder(Context context).)

Deprecated class: The entire class v7 NotificationCompat.Builder is deprecated. (See v7 NotificationCompat.Builder.) Previously, v7 NotificationCompat.Builder was needed to support NotificationCompat.MediaStyle. In Android O, there's a v4 NotificationCompat.MediaStyle in the media-compat library's android.support.v4.media package. Use that one if you need MediaStyle.

API 14+: In Support Library from 26.0.0 and higher, the support-v4 and support-v7 packages both support a minimum API level of 14. The v# names are historical.

See Recent Support Library Revisions.

How do I make Git ignore file mode (chmod) changes?

Adding to Greg Hewgill answer (of using core.fileMode config variable):

You can use --chmod=(-|+)x option of git update-index (low-level version of "git add") to change execute permissions in the index, from where it would be picked up if you use "git commit" (and not "git commit -a").

Post-increment and Pre-increment concept?

All four answers so far are incorrect, in that they assert a specific order of events.

Believing that "urban legend" has led many a novice (and professional) astray, to wit, the endless stream of questions about Undefined Behavior in expressions.

So.

For the built-in C++ prefix operator,

++x

increments x and produces (as the expression's result) x as an lvalue, while

x++

increments x and produces (as the expression's result) the original value of x.

In particular, for x++ there is no no time ordering implied for the increment and production of original value of x. The compiler is free to emit machine code that produces the original value of x, e.g. it might be present in some register, and that delays the increment until the end of the expression (next sequence point).

Folks who incorrectly believe the increment must come first, and they are many, often conclude from that certain expressions must have well defined effect, when they actually have Undefined Behavior.

Why use Gradle instead of Ant or Maven?

This may be a bit controversial, but Gradle doesn't hide the fact that it's a fully-fledged programming language.

Ant + ant-contrib is essentially a turing complete programming language that no one really wants to program in.

Maven tries to take the opposite approach of trying to be completely declarative and forcing you to write and compile a plugin if you need logic. It also imposes a project model that is completely inflexible. Gradle combines the best of all these tools:

  • It follows convention-over-configuration (ala Maven) but only to the extent you want it
  • It lets you write flexible custom tasks like in Ant
  • It provides multi-module project support that is superior to both Ant and Maven
  • It has a DSL that makes the 80% things easy and the 20% things possible (unlike other build tools that make the 80% easy, 10% possible and 10% effectively impossible).

Gradle is the most configurable and flexible build tool I have yet to use. It requires some investment up front to learn the DSL and concepts like configurations but if you need a no-nonsense and completely configurable JVM build tool it's hard to beat.

Center image horizontally within a div

I just found this solution below on the W3 CSS page and it answered my problem.

img {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

Source: http://www.w3.org/Style/Examples/007/center.en.html

What is the best way to parse html in C#?

The Html Agility Pack has been mentioned before - if you are going for speed, you might also want to check out the Majestic-12 HTML parser. Its handling is rather clunky, but it delivers a really fast parsing experience.

Loading a properties file from Java package

public class ReadPropertyDemo {
    public static void main(String[] args) {
        Properties properties = new Properties();

        try {
            properties.load(new FileInputStream(
                    "com/technicalkeeda/demo/application.properties"));
            System.out.println("Domain :- " + properties.getProperty("domain"));
            System.out.println("Website Age :- "
                    + properties.getProperty("website_age"));
            System.out.println("Founder :- " + properties.getProperty("founder"));

            // Display all the values in the form of key value
            for (String key : properties.stringPropertyNames()) {
                String value = properties.getProperty(key);
                System.out.println("Key:- " + key + "Value:- " + value);
            }

        } catch (IOException e) {
            System.out.println("Exception Occurred" + e.getMessage());
        }

    }
}

Mean filter for smoothing images in Matlab

h = fspecial('average', n);
filter2(h, img);

See doc fspecial: h = fspecial('average', n) returns an averaging filter. n is a 1-by-2 vector specifying the number of rows and columns in h.

Exit single-user mode

Today I faced the same issue where my database was changed from Multi User to Single User mode and this was eventually stopping me to publish database.

In order to fix this issue, I had to close all Visual Studio instances and run the below command in Sql Server query window -

USE [Your_Database_Name]; ALTER DATABASE [Your_Database_Name] SET MULTI_USER GO

This command has changed the DB from Single user to Multi User and afterwards, I was successfully able to publish.

Vim clear last search highlighting

This will clear the search highlight after updatetime milliseconds of inactivity.

updatetime defaults to 4000ms or 4s but I set mine to 10s. It is important to note that updatetime does more than just this so read the docs before you change it.

function! SearchHlClear()
    let @/ = ''
endfunction
augroup searchhighlight
    autocmd!
    autocmd CursorHold,CursorHoldI * call SearchHlClear()
augroup END

How may I reference the script tag that loaded the currently-executing script?

Script are executed sequentially only if they do not have either a "defer" or an "async" attribute. Knowing one of the possible ID/SRC/TITLE attributes of the script tag could work also in those cases. So both Greg and Justin suggestions are correct.

There is already a proposal for a document.currentScript on the WHATWG lists.

EDIT: Firefox > 4 already implement this very useful property but it is not available in IE11 last I checked and only available in Chrome 29 and Safari 8.

EDIT: Nobody mentioned the "document.scripts" collection but I believe that the following may be a good cross browser alternative to get the currently running script:

var me = document.scripts[document.scripts.length -1];

Get record counts for all tables in MySQL database

 SELECT TABLE_NAME,SUM(TABLE_ROWS) 
 FROM INFORMATION_SCHEMA.TABLES 
 WHERE TABLE_SCHEMA = 'your_db' 
 GROUP BY TABLE_NAME;

That's all you need.

Reading e-mails from Outlook with Python through MAPI

I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

There are 2 possible problems are:

  • Firstly, you have not used the using System which should be before writing code that uses "System class", as Console.WriteLine()
  • Secondly, you have not coded what happens after the Console displays "Test"

The possible solution will be:

using System;

namespace Test
{
    public static Main()
    {
        //Print to the console
        Console.WriteLine("Test");

        //Allow user to read output
        Console.ReadKey();
    }
}

It is also strategic to code Console.Write("Press any key to exit..."); on the line that precedes the Console.ReadKey(); to make the user aware that the program is ending, he/she must press any key to exit.

Set default heap size in Windows

Setup JAVA_OPTS as a system variable with the following content:

JAVA_OPTS="-Xms256m -Xmx512m"

After that in a command prompt run the following commands:

SET JAVA_OPTS="-Xms256m -Xmx512m"

This can be explained as follows:

  • allocate at minimum 256MBs of heap
  • allocate at maximum 512MBs of heap

These values should be changed according to application requirements.

EDIT:

You can also try adding it through the Environment Properties menu which can be found at:

  1. From the Desktop, right-click My Computer and click Properties.
  2. Click Advanced System Settings link in the left column.
  3. In the System Properties window click the Environment Variables button.
  4. Click New to add a new variable name and value.
  5. For variable name enter JAVA_OPTS for variable value enter -Xms256m -Xmx512m
  6. Click ok and close the System Properties Tab.
  7. Restart any java applications.

EDIT 2:

JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.

To setup a system variable you have to complete the steps listed above from 1 to 4.

how to get bounding box for div element in jquery

As this is specifically tagged for jQuery -

$("#myElement")[0].getBoundingClientRect();

or

$("#myElement").get(0).getBoundingClientRect();

(These are functionally identical, in some older browsers .get() was slightly faster)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect() calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

Python pandas insert list into a cell

As mentionned in this post pandas: how to store a list in a dataframe?; the dtypes in the dataframe may influence the results, as well as calling a dataframe or not to be assigned to.

Remove a modified file from pull request

A pull request is just that: a request to merge one branch into another.

Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".

The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.

In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p should sort you out.

Maven: best way of linking custom external JAR to my project?

Change your systemPath.

<dependency>
  <groupId>stuff</groupId>
  <artifactId>library</artifactId>
  <version>1.0</version>
  <systemPath>${project.basedir}/MyLibrary.jar</systemPath>
  <scope>system</scope>
</dependency>

creating Hashmap from a JSON String

You could use Jackson to do this. I have yet to find a simple Gson solution.

Where data_map.json is a JSON (object) resource file
and data_list.json is a JSON (array) resource file.

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Based on:
 * 
 * http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
 */
public class JsonLoader {
    private static final ObjectMapper OBJ_MAPPER;
    private static final TypeReference<Map<String,Object>> OBJ_MAP;
    private static final TypeReference<List<Map<String,Object>>> OBJ_LIST;

    static {
        OBJ_MAPPER = new ObjectMapper();
        OBJ_MAP = new TypeReference<Map<String,Object>>(){};
        OBJ_LIST = new TypeReference<List<Map<String,Object>>>(){};
    }

    public static void main(String[] args) {
        try {
            System.out.println(jsonToString(parseJsonString(read("data_map.json", true))));
            System.out.println(jsonToString(parseJsonString(read("data_array.json", true))));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static final Object parseJsonString(String jsonString) {
        try {
            if (jsonString.startsWith("{")) {
                return readJsonObject(jsonString);
            } else if (jsonString.startsWith("[")) {
                return readJsonArray(jsonString);
            }
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String jsonToString(Object json) throws JsonProcessingException {
        return OBJ_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(json);
    }

    private static final Map<String,Object> readJsonObject(String jsonObjectString) throws JsonParseException, JsonMappingException, IOException {
        return OBJ_MAPPER.readValue(jsonObjectString, OBJ_MAP);
    }

    private static final List<Map<String,Object>> readJsonArray(String jsonArrayString) throws JsonParseException, JsonMappingException, IOException {
        return OBJ_MAPPER.readValue(jsonArrayString, OBJ_LIST);
    }

    public static final Map<String,Object> loadJsonObject(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
        return OBJ_MAPPER.readValue(load(path, isResource), OBJ_MAP);
    }

    public static final List<Map<String,Object>> loadJsonArray(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
        return OBJ_MAPPER.readValue(load(path, isResource), OBJ_LIST);
    }

    private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
        if (isResource) {
            return JsonLoader.class.getClassLoader().getResource(path);
        }

        return new URL("file:/" + path);
    }

    protected static File load(String path, boolean isResource) throws MalformedURLException {
        return load(pathToUrl(path, isResource));
    }

    protected static File load(URL url) {
        try {
            return new File(url.toURI());
        } catch (URISyntaxException e) {
            return new File(url.getPath());
        }
    }

    public static String read(String path, boolean isResource) throws IOException {
        return read(path, "UTF-8", isResource);
    }

    public static String read(String path, String charset, boolean isResource) throws IOException {
        return read(pathToUrl(path, isResource), charset);
    }

    @SuppressWarnings("resource")
    public static String read(URL url, String charset) throws IOException {
        return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
    }
}

Extra

Here is the complete code for Dheeraj Sachan's example.

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

public class JsonHandler {
    private static ObjectMapper propertyMapper;

    static {
        final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        propertyMapper = new ObjectMapper();
        propertyMapper.setDateFormat(df);
        propertyMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        propertyMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        propertyMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    }

    private static class MyHashMap extends HashMap<String, List<Video>>{
        private static final long serialVersionUID = 7023107716981734468L;
    }

    private static class Video implements Serializable {
        private static final long serialVersionUID = -446275421030765463L;

        private String dashUrl;
        private String videoBitrate;
        private String audioBitrate;
        private int videoWidth;
        private int videoHeight;
        private long fileSize;

        @Override
        public String toString() {
            return "Video [url=" + dashUrl + ", video=" + videoBitrate + ", audio=" + audioBitrate
                    + ", width=" + videoWidth + ", height=" + videoHeight + ", size=" + fileSize + "]";
        }
    }

    public static void main(String[] args) {
        try {
            HashMap<String, List<Video>> map = loadJson("sample.json", true);
            Iterator<Entry<String, List<Video>>> lectures = map.entrySet().iterator();

            while (lectures.hasNext()) {
                Entry<String, List<Video>> lecture = lectures.next();

                System.out.printf("Lecture #%s%n", lecture.getKey());

                for (Video video : lecture.getValue()) {
                    System.out.println(video);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> T parseUnderScoredResponse(String json, Class<T> classOfT) {
        try {
            if (json == null) {
                return null;
            }
            return propertyMapper.readValue(json, classOfT);

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
        if (isResource) {
            return JsonHandler.class.getClassLoader().getResource(path);
        }

        return new URL("file:/" + path);
    }

    public static File load(String path, boolean isResource) throws MalformedURLException {
        return load(pathToUrl(path, isResource));
    }

    public static File load(URL url) {
        try {
            return new File(url.toURI());
        } catch (URISyntaxException e) {
            return new File(url.getPath());
        }
    }

    @SuppressWarnings("resource")
    public static String readFile(URL url, String charset) throws IOException {
        return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
    }

    public static String loadJsonString(String path, boolean isResource) throws IOException {
        return readFile(path, isResource, "UTF-8");
    }

    public static String readFile(String path, boolean isResource, String charset) throws IOException {
        return readFile(pathToUrl(path, isResource), charset);
    }

    public static HashMap<String, List<Video>> loadJson(String jsonString) throws IOException {
        return JsonHandler.parseUnderScoredResponse(jsonString, MyHashMap.class);
    }

    public static HashMap<String, List<Video>> loadJson(String path, boolean isResource) throws IOException {
        return loadJson(loadJsonString(path, isResource));
    }
}

Move an item inside a list?

I profiled a few methods to move an item within the same list with timeit. Here are the ones to use if j>i:

+---------------------------------+
¦ 14.4usec ¦ x[i:i]=x.pop(j),     ¦
¦ 14.5usec ¦ x[i:i]=[x.pop(j)]    ¦
¦ 15.2usec ¦ x.insert(i,x.pop(j)) ¦
+---------------------------------+

and here the ones to use if j<=i:

+--------------------------------------+
¦ 14.4usec ¦ x[i:i]=x[j],;del x[j]     ¦
¦ 14.4usec ¦ x[i:i]=[x[j]];del x[j]    ¦
¦ 15.4usec ¦ x.insert(i,x[j]);del x[j] ¦
+--------------------------------------+

Not a huge difference if you only use it a few times, but if you do heavy stuff like manual sorting, it's important to take the fastest one. Otherwise, I'd recommend just taking the one that you think is most readable.

Can jQuery read/write cookies to a browser?

To answer your question, yes. The other have answered that part, but it also seems like you're asking if that's the best way to do it.

It would probably depend on what you are doing. Typically you would have a user click what items they want to buy (ordering for example). Then they would hit a buy or checkout button. Then the form would send off to a page and process the result. You could do all of that with a cookie but I would find it to be more difficult.

You may want to consider posting your second question in another topic.

Replace missing values with column mean

With the data.table package you could use the set() function and loop over the columns and replace the NAs or whatever you like with an aggregate or value of your choice (here: mean):

require(data.table)

# data
dt = copy(iris[ ,-5])
setDT(dt)
dt[1:4, Sepal.Length := NA] # introduce NAs

# replace NAs with mean (or whatever function you like)
for (j in seq_along(names(dt))) {
  set(dt,
      i = which(is.na(dt[[j]])),
      j = j, 
      value = mean(dt[[j]], na.rm = TRUE))
}

how to add the missing RANDR extension

First off, Xvfb doesn't read configuration from xorg.conf. Xvfb is a variant of the KDrive X servers and like all members of that family gets its configuration from the command line.

It is true that XRandR and Xinerama are mutually exclusive, but in the case of Xvfb there's no Xinerama in the first place. You can enable the XRandR extension by starting Xvfb using at least the following command line options

Xvfb +extension RANDR [further options]

How to read HDF5 files in Python

What you need to do is create a dataset. If you take a look at the quickstart guide, it shows you that you need to use the file object in order to create a dataset. So, f.create_dataset and then you can read the data. This is explained in the docs.

Getting user input

In python 3.x, use input() instead of raw_input()

How to find MAC address of an Android device programmatically

Here the Kotlin version of Arth Tilvas answer:

fun getMacAddr(): String {
    try {
        val all = Collections.list(NetworkInterface.getNetworkInterfaces())
        for (nif in all) {
            if (!nif.getName().equals("wlan0", ignoreCase=true)) continue

            val macBytes = nif.getHardwareAddress() ?: return ""

            val res1 = StringBuilder()
            for (b in macBytes) {
                //res1.append(Integer.toHexString(b & 0xFF) + ":");
                res1.append(String.format("%02X:", b))
            }

            if (res1.length > 0) {
                res1.deleteCharAt(res1.length - 1)
            }
            return res1.toString()
        }
    } catch (ex: Exception) {
    }

    return "02:00:00:00:00:00"
}

How do I POST with multipart form data using fetch?

You're setting the Content-Type to be multipart/form-data, but then using JSON.stringify on the body data, which returns application/json. You have a content type mismatch.

You will need to encode your data as multipart/form-data instead of json. Usually multipart/form-data is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded (which is the default for HTML forms).

The specification for multipart/form-data can be found in RFC 1867.

For a guide on how to submit that kind of data via javascript, see here.

The basic idea is to use the FormData object (not supported in IE < 10):

async function sendData(url, data) {
  const formData  = new FormData();

  for(const name in data) {
    formData.append(name, data[name]);
  }

  const response = await fetch(url, {
    method: 'POST',
    body: formData
  });

  // ...
}

Per this article make sure not to set the Content-Type header. The browser will set it for you, including the boundary parameter.

check if a file is open in Python

If all you care about is the current process, an easy way is to use the file object attribute "closed"

f = open('file.py')
if f.closed:
  print 'file is closed'

This will not detect if the file is open by other processes!

source: http://docs.python.org/2.4/lib/bltin-file-objects.html

Convert floating point number to a certain precision, and then copy to string

With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.

# Option one
older_method_string = "%.9f" % numvar

# Option two
newer_method_string = "{:.9f}".format(numvar)

But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.

For more information on option two, I suggest this link on string formatting from the Python documentation.

And for more information on option one, this link will suffice and has info on the various flags.

Python 3.6 (officially released in December of 2016), added the f string literal, see more information here, which extends the str.format method (use of curly braces such that f"{numvar:.9f}" solves the original problem), that is,

# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"

solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.

How to import a new font into a project - Angular 5

the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face

@font-face {
  font-family: 'Name You Font';
  src: url('assets/font/xxyourfontxxx.eot');
  src: local('Cera Pro Medium'), local('CeraPro-Medium'),
  url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
  url('assets/font/xxyourfontxxx.woff') format('woff'),
  url('assets/font/xxyourfontxxx.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}

So you can just indicate your fontfamily name that you already choosed

NOTE: the font-weight and font-style depend on your .woff .ttf ... files

How to hide the border for specified rows of a table?

I use this with good results:

border-style:hidden;

It also works for:

border-right-style:hidden; /*if you want to hide just a border on a cell*/

Example:

_x000D_
_x000D_
<style type="text/css">_x000D_
      table, th, td {_x000D_
       border: 2px solid green;_x000D_
      }_x000D_
      tr.hide_right > td, td.hide_right{_x000D_
        border-right-style:hidden;_x000D_
      }_x000D_
      tr.hide_all > td, td.hide_all{_x000D_
        border-style:hidden;_x000D_
      }_x000D_
  }_x000D_
</style>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="hide_right">11</td>_x000D_
    <td>12</td>_x000D_
    <td class="hide_all">13</td>_x000D_
  </tr>_x000D_
  <tr class="hide_right">_x000D_
    <td>21</td>_x000D_
    <td>22</td>_x000D_
    <td>23</td>_x000D_
  </tr>_x000D_
  <tr class="hide_all">_x000D_
    <td>31</td>_x000D_
    <td>32</td>_x000D_
    <td>33</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here is the result: enter image description here

remove attribute display:none; so the item will be visible

If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.

$("span").toggle();

Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
_x000D_
_x000D_

How do I use extern to share variables between source files?

extern keyword is used with the variable for its identification as a global variable.

It also represents that you can use the variable declared using extern keyword in any file though it is declared/defined in other file.

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

This is fairly straightforward. In your JS, all you would do is this or something similar:

var array = ["thing1", "thing2", "thing3"];

var parameters = {
  "array1[]": array,
  ...
};

$.post(
  'your/page.php',
  parameters
)
.done(function(data, statusText) {
    // This block is optional, fires when the ajax call is complete
});

In your php page, the values in array form will be available via $_POST['array1'].

references

Allow click on twitter bootstrap dropdown toggle link?

Since there is not really an answer that works (selected answer disables dropdown), or overrides using javascript, here goes.

This is all html and css fix (uses two <a> tags):

<ul class="nav">
 <li class="dropdown dropdown-li">
    <a class="dropdown-link" href="http://google.com">Dropdown</a>
    <a class="dropdown-caret dropdown-toggle"><b class="caret"></b></a>
    <ul class="dropdown-menu">
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
    </ul>
 </li>
</ul>

Now here's the CSS you need.

.dropdown-li {
    display:inline-block !important;
}
.dropdown-link {
    display:inline-block !important; 
    padding-right:4px !important;
}
.dropdown-caret {
    display:inline-block !important; 
    padding-left:4px !important;
}

Assuming you will want the both <a> tags to highlight on hover of either one, you will also need to override bootstrap, you might play around with the following:

.nav > li:hover {
    background-color: #f67a47; /*hover background color*/
}
.nav > li:hover > a {
    color: white; /*hover text color*/
}
.nav > li:hover > ul > a {
    color: black; /*dropdown item text color*/
}

Sorting using Comparator- Descending order (User defined classes)

I would create a comparator for the person class that can be parametrized with a certain sorting behaviour. Here I can set the sorting order but it can be modified to allow sorting for other person attributes as well.

public class PersonComparator implements Comparator<Person> {

  public enum SortOrder {ASCENDING, DESCENDING}

  private SortOrder sortOrder;

  public PersonComparator(SortOrder sortOrder) {
    this.sortOrder = sortOrder;
  }

  @Override
  public int compare(Person person1, Person person2) {
    Integer age1 = person1.getAge();
    Integer age2 = person2.getAge();
    int compare = Math.signum(age1.compareTo(age2));

    if (sortOrder == ASCENDING) {
      return compare;
    } else {
      return compare * (-1);
    }
  }
}

(hope it compiles now, I have no IDE or JDK at hand, coded 'blind')

Edit

Thanks to Thomas, edited the code. I wouldn't say that the usage of Math.signum is good, performant, effective, but I'd like to keep it as a reminder, that the compareTo method can return any integer and multiplying by (-1) will fail if the implementation returns Integer.MIN_INTEGER... And I removed the setter because it's cheap enough to construct a new PersonComparator just when it's needed.

But I keep the boxing because it shows that I rely on an existing Comparable implementation. Could have done something like Comparable<Integer> age1 = new Integer(person1.getAge()); but that looked too ugly. The idea was to show a pattern which could easily be adapted to other Person attributes, like name, birthday as Date and so on.

Why is json_encode adding backslashes?

json_encode will always add slashes.

Check some examples on the manual HERE

This is because if there are some characters which needs to escaped then they will create problem.

To use the json please Parse your json to ensure that the slashes are removed

Well whether or not you remove slashesthe json will be parsed without any problem by eval.

<?php
$array = array('url'=>'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg','id'=>54);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var x = jQuery.parseJSON('<?php echo json_encode($array);?>');
alert(x);
</script>

This is my code and i m able to parse the JSON.

Check your code May be you are missing something while parsing the JSON

jQuery animate margin top

use 'marginTop' instead of MarginTop

$(this).find('.info').animate({ 'marginTop': '-50px', opacity: 0.5 }, 1000);

Jackson - best way writes a java list to a json array

This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:

public void writeListToJsonArray() throws IOException {  
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();

    mapper.writeValue(out, list);

    final byte[] data = out.toByteArray();
    System.out.println(new String(data));
}

How to right-align form input boxes?

Try this:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
    p {
        text-align: right;
    }
    input {
        width: 100px;
    }
    </style>
</head>

<body>
    <form>
        <p>
            <input name="declared_first" value="above" />
        </p>
        <p>
            <input name="declared_second" value="below" />
        </p>
    </form>
</body>
</html>

Read a variable in bash with a default value

#Script for calculating various values in MB
echo "Please enter some input: "
read input_variable
echo $input_variable | awk '{ foo = $1 / 1024 / 1024 ; print foo "MB" }'

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

You need to add JQuery js before adding bootstrap js file, because BootStrap use jqueries function. So make sure to load first jquery js and then bootstap js file.

<!-- JQuery Core JavaScript -->
<script src="app/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="app/js/bootstrap.min.js"></script>

Fix height of a table row in HTML Table

my css

TR.gray-t {background:#949494;}
h3{
    padding-top:3px;
    font:bold 12px/2px Arial;
}

my html

<TR class='gray-t'>
<TD colspan='3'><h3>KAJANG</h3>

I decrease the 2nd size in font.

padding-top is used to fix the size in IE7.

How to use a variable for the database name in T-SQL?

Put the entire script into a template string, with {SERVERNAME} placeholders. Then edit the string using:

SET @SQL_SCRIPT = REPLACE(@TEMPLATE, '{SERVERNAME}', @DBNAME)

and then run it with

EXECUTE (@SQL_SCRIPT)

It's hard to believe that, in the course of three years, nobody noticed that my code doesn't work!

You can't EXEC multiple batches. GO is a batch separator, not a T-SQL statement. It's necessary to build three separate strings, and then to EXEC each one after substitution.

I suppose one could do something "clever" by breaking the single template string into multiple rows by splitting on GO; I've done that in ADO.NET code.

And where did I get the word "SERVERNAME" from?

Here's some code that I just tested (and which works):

DECLARE @DBNAME VARCHAR(255)
SET @DBNAME = 'TestDB'

DECLARE @CREATE_TEMPLATE VARCHAR(MAX)
DECLARE @COMPAT_TEMPLATE VARCHAR(MAX)
DECLARE @RECOVERY_TEMPLATE VARCHAR(MAX)

SET @CREATE_TEMPLATE = 'CREATE DATABASE {DBNAME}'
SET @COMPAT_TEMPLATE='ALTER DATABASE {DBNAME} SET COMPATIBILITY_LEVEL = 90'
SET @RECOVERY_TEMPLATE='ALTER DATABASE {DBNAME} SET RECOVERY SIMPLE'

DECLARE @SQL_SCRIPT VARCHAR(MAX)

SET @SQL_SCRIPT = REPLACE(@CREATE_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

SET @SQL_SCRIPT = REPLACE(@COMPAT_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

SET @SQL_SCRIPT = REPLACE(@RECOVERY_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

Select the first row by group

now, for dplyr, adding a distinct counter.

df %>%
    group_by(aa, bb) %>%
    summarise(first=head(value,1), count=n_distinct(value))

You create groups, them summarise within groups.

If data is numeric, you can use:
first(value) [there is also last(value)] in place of head(value, 1)

see: http://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html

Full:

> df
Source: local data frame [16 x 3]

   aa bb value
1   1  1   GUT
2   1  1   PER
3   1  2   SUT
4   1  2   GUT
5   1  3   SUT
6   1  3   GUT
7   1  3   PER
8   2  1   221
9   2  1   224
10  2  1   239
11  2  2   217
12  2  2   221
13  2  2   224
14  3  1   GUT
15  3  1   HUL
16  3  1   GUT

> library(dplyr)
> df %>%
>   group_by(aa, bb) %>%
>   summarise(first=head(value,1), count=n_distinct(value))

Source: local data frame [6 x 4]
Groups: aa

  aa bb first count
1  1  1   GUT     2
2  1  2   SUT     2
3  1  3   SUT     3
4  2  1   221     3
5  2  2   217     3
6  3  1   GUT     2

HTML "overlay" which allows clicks to fall through to elements behind it

Generally, this isn't a great idea. Taking your scenario, if you had evil intentions, you could hide everything underneath your "overlay". Then, when a user clicks on a link they think should take them to bankofamerica.com, instead it triggers the hidden link which takes them to myevilsite.com.

That said, event bubbling works, and if it's within an application, it's not a big deal. The following code is an example. Clicking the blue area pops up an alert, even though the alert is set on the red area. Note that the orange area does NOT work, because the event will propagate through the PARENT elements, so your overlay needs to be inside whatever element you're observing the clicks on. In your scenario, you may be out of luck.

<html>
<head>
</head>
<body>
    <div id="outer" style="position:absolute;height:50px;width:60px;z-index:1;background-color:red;top:5px;left:5px;" onclick="alert('outer')"> 
        <div id="nested" style="position:absolute;height:50px;width:60px;z-index:2;background-color:blue;top:15px;left:15px;">
        </div>
    </div>
    <div id="separate" style="position:absolute;height:50px;width:60px;z-index:3;background-color:orange;top:25px;left:25px;">
    </div>
</body>
</html>

How can I get the count of milliseconds since midnight for the current?

In Java 8 you can simply do

ZonedDateTime.now().toInstant().toEpochMilli()

returns : the number of milliseconds since the epoch of 1970-01-01T00:00:00Z

How to set max width of an image in CSS

I see this hasn't been answered as final.

I see you have max-width as 100% and width as 600. Flip those.

A simple way also is:

     <img src="image.png" style="max-width:600px;width:100%">

I use this often, and then you can control individual images as well, and not have it on all img tags. You could CSS it also like below.

 .image600{
     width:100%;
     max-width:600px;
 }

     <img src="image.png" class="image600">

Jquery: how to trigger click event on pressing enter key

Just include preventDefault() function in the code,

$("#txtSearchProdAssign").keydown(function (e) 
{
   if (e.keyCode == 13) 
   {
       e.preventDefault();
       $('input[name = butAssignProd]').click();
   }
});

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Install Genymotion 2.10 or above, now there is a dedicated button to install Google Play Services name "Open GApps". Link for more info

3 Steps process for Genymotion 2.9 or below:-

4.4 Kitkat
5.0 Lollipop
5.1 Lollipop
6.0 Marshmallow
7.0 Nougat
7.1 Nougat (webview patch)
8.0 Oreo
8.1 Oreo
9.0 Pie

  1. Download from above link
  2. Just drag & drop downloaded zip file to genymotion and restart
  3. Add google account and download "Google Play Music" and Run.


import an array in python

Have a look at SciPy cookbook. It should give you an idea of some basic methods to import /export data.

If you save/load the files from your own Python programs, you may also want to consider the Pickle module, or cPickle.

Read response headers from API response - Angular 5 + TypeScript

Have you exposed the X-Token from server side using access-control-expose-headers? because not all headers are allowed to be accessed from the client side, you need to expose them from the server side

Also in your frontend, you can use new HTTP module to get a full response using {observe: 'response'} like

http
  .get<any>('url', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Token'));
  });

Warning: Failed propType: Invalid prop `component` supplied to `Route`

[email protected] also fixed this bug, just update it:

npm i --save react-router@latest

Android device chooser - My device seems offline

On the Galaxy Note 3 in debugging mode with Windows 7 I had problems with the device "offline" in the Android ADT (Eclipse) DDMS "Devices" window. By selecting USB 3.0 as USB connection in the Note 3 pull down control panel the device came online. Obviously applicable for a computer with USB3 ports.

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

Can I check if Bootstrap Modal Shown / Hidden?

its an old question but anyway heres something i used incase someone was looking for the same thing

if (!$('#myModal').is(':visible')) {
    // if modal is not shown/visible then do something
}

How to automatically import data from uploaded CSV or XLS file into Google Sheets

You can programmatically import data from a csv file in your Drive into an existing Google Sheet using Google Apps Script, replacing/appending data as needed.

Below is some sample code. It assumes that: a) you have a designated folder in your Drive where the CSV file is saved/uploaded to; b) the CSV file is named "report.csv" and the data in it comma-delimited; and c) the CSV data is imported into a designated spreadsheet. See comments in code for further details.

function importData() {
  var fSource = DriveApp.getFolderById(reports_folder_id); // reports_folder_id = id of folder where csv reports are saved
  var fi = fSource.getFilesByName('report.csv'); // latest report file
  var ss = SpreadsheetApp.openById(data_sheet_id); // data_sheet_id = id of spreadsheet that holds the data to be updated with new report data

  if ( fi.hasNext() ) { // proceed if "report.csv" file exists in the reports folder
    var file = fi.next();
    var csv = file.getBlob().getDataAsString();
    var csvData = CSVToArray(csv); // see below for CSVToArray function
    var newsheet = ss.insertSheet('NEWDATA'); // create a 'NEWDATA' sheet to store imported data
    // loop through csv data array and insert (append) as rows into 'NEWDATA' sheet
    for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ) {
      newsheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    }
    /*
    ** report data is now in 'NEWDATA' sheet in the spreadsheet - process it as needed,
    ** then delete 'NEWDATA' sheet using ss.deleteSheet(newsheet)
    */
    // rename the report.csv file so it is not processed on next scheduled run
    file.setName("report-"+(new Date().toString())+".csv");
  }
};


// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.

function CSVToArray( strData, strDelimiter ) {
  // Check to see if the delimiter is defined. If not,
  // then default to COMMA.
  strDelimiter = (strDelimiter || ",");

  // Create a regular expression to parse the CSV values.
  var objPattern = new RegExp(
    (
      // Delimiters.
      "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

      // Quoted fields.
      "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

      // Standard fields.
      "([^\"\\" + strDelimiter + "\\r\\n]*))"
    ),
    "gi"
  );

  // Create an array to hold our data. Give the array
  // a default empty first row.
  var arrData = [[]];

  // Create an array to hold our individual pattern
  // matching groups.
  var arrMatches = null;

  // Keep looping over the regular expression matches
  // until we can no longer find a match.
  while (arrMatches = objPattern.exec( strData )){

    // Get the delimiter that was found.
    var strMatchedDelimiter = arrMatches[ 1 ];

    // Check to see if the given delimiter has a length
    // (is not the start of string) and if it matches
    // field delimiter. If id does not, then we know
    // that this delimiter is a row delimiter.
    if (
      strMatchedDelimiter.length &&
      (strMatchedDelimiter != strDelimiter)
    ){

      // Since we have reached a new row of data,
      // add an empty row to our data array.
      arrData.push( [] );

    }

    // Now that we have our delimiter out of the way,
    // let's check to see which kind of value we
    // captured (quoted or unquoted).
    if (arrMatches[ 2 ]){

      // We found a quoted value. When we capture
      // this value, unescape any double quotes.
      var strMatchedValue = arrMatches[ 2 ].replace(
        new RegExp( "\"\"", "g" ),
        "\""
      );

    } else {

      // We found a non-quoted value.
      var strMatchedValue = arrMatches[ 3 ];

    }

    // Now that we have our value string, let's add
    // it to the data array.
    arrData[ arrData.length - 1 ].push( strMatchedValue );
  }

  // Return the parsed data.
  return( arrData );
};

You can then create time-driven trigger in your script project to run importData() function on a regular basis (e.g. every night at 1AM), so all you have to do is put new report.csv file into the designated Drive folder, and it will be automatically processed on next scheduled run.

If you absolutely MUST work with Excel files instead of CSV, then you can use this code below. For it to work you must enable Drive API in Advanced Google Services in your script and in Developers Console (see How to Enable Advanced Services for details).

/**
 * Convert Excel file to Sheets
 * @param {Blob} excelFile The Excel file blob data; Required
 * @param {String} filename File name on uploading drive; Required
 * @param {Array} arrParents Array of folder ids to put converted file in; Optional, will default to Drive root folder
 * @return {Spreadsheet} Converted Google Spreadsheet instance
 **/
function convertExcel2Sheets(excelFile, filename, arrParents) {

  var parents  = arrParents || []; // check if optional arrParents argument was provided, default to empty array if not
  if ( !parents.isArray ) parents = []; // make sure parents is an array, reset to empty array if not

  // Parameters for Drive API Simple Upload request (see https://developers.google.com/drive/web/manage-uploads#simple)
  var uploadParams = {
    method:'post',
    contentType: 'application/vnd.ms-excel', // works for both .xls and .xlsx files
    contentLength: excelFile.getBytes().length,
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    payload: excelFile.getBytes()
  };

  // Upload file to Drive root folder and convert to Sheets
  var uploadResponse = UrlFetchApp.fetch('https://www.googleapis.com/upload/drive/v2/files/?uploadType=media&convert=true', uploadParams);

  // Parse upload&convert response data (need this to be able to get id of converted sheet)
  var fileDataResponse = JSON.parse(uploadResponse.getContentText());

  // Create payload (body) data for updating converted file's name and parent folder(s)
  var payloadData = {
    title: filename, 
    parents: []
  };
  if ( parents.length ) { // Add provided parent folder(s) id(s) to payloadData, if any
    for ( var i=0; i<parents.length; i++ ) {
      try {
        var folder = DriveApp.getFolderById(parents[i]); // check that this folder id exists in drive and user can write to it
        payloadData.parents.push({id: parents[i]});
      }
      catch(e){} // fail silently if no such folder id exists in Drive
    }
  }
  // Parameters for Drive API File Update request (see https://developers.google.com/drive/v2/reference/files/update)
  var updateParams = {
    method:'put',
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    contentType: 'application/json',
    payload: JSON.stringify(payloadData)
  };

  // Update metadata (filename and parent folder(s)) of converted sheet
  UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files/'+fileDataResponse.id, updateParams);

  return SpreadsheetApp.openById(fileDataResponse.id);
}

/**
 * Sample use of convertExcel2Sheets() for testing
 **/
 function testConvertExcel2Sheets() {
  var xlsId = "0B9**************OFE"; // ID of Excel file to convert
  var xlsFile = DriveApp.getFileById(xlsId); // File instance of Excel file
  var xlsBlob = xlsFile.getBlob(); // Blob source of Excel file for conversion
  var xlsFilename = xlsFile.getName(); // File name to give to converted file; defaults to same as source file
  var destFolders = []; // array of IDs of Drive folders to put converted file in; empty array = root folder
  var ss = convertExcel2Sheets(xlsBlob, xlsFilename, destFolders);
  Logger.log(ss.getId());
}

The above code is also available as a gist here.

Proxy Basic Authentication in C#: HTTP 407 error

here is the correct way of using proxy along with creds..

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

IWebProxy proxy = request.Proxy;                    
if (proxy != null)
{
    Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
}
else
{
    Console.WriteLine("Proxy is null; no proxy will be used");
}

WebProxy myProxy = new WebProxy();
Uri newUri = new Uri("http://20.154.23.100:8888");
// Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
myProxy.Address = newUri;
// Create a NetworkCredential object and associate it with the 
// Proxy property of request object.
myProxy.Credentials = new NetworkCredential("userName", "password");
request.Proxy = myProxy;

Thanks everyone for help... :)

How do you subtract Dates in Java?

You can use the following approach:

SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd");

long d1=formater.parse("2001-1-1").getTime();
long d2=formater.parse("2001-1-2").getTime();

System.out.println(Math.abs((d1-d2)/(1000*60*60*24)));

How to split a data frame?

If you want to split a dataframe according to values of some variable, I'd suggest using daply() from the plyr package.

library(plyr)
x <- daply(df, .(splitting_variable), function(x)return(x))

Now, x is an array of dataframes. To access one of the dataframes, you can index it with the name of the level of the splitting variable.

x$Level1
#or
x[["Level1"]]

I'd be sure that there aren't other more clever ways to deal with your data before splitting it up into many dataframes though.

make a phone call click on a button

add "tel:" along with your number to be dialed in your intent and then start your activity.

Intent myIntent = new Intent(Intent.ACTION_CALL);
 String phNum = "tel:" + "1234567890";
 myIntent.setData(Uri.parse(phNum));
  startActivity( myIntent ) ;

Left Join With Where Clause

You might find it easier to understand by using a simple subquery

SELECT `settings`.*, (
    SELECT `value` FROM `character_settings`
    WHERE `character_settings`.`setting_id` = `settings`.`id`
      AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`

The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.

Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.

SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'

How to remove responsive features in Twitter Bootstrap 3?

To inactivate the non-desktop styles you just have to change 4 lines of code in the variables.less file. Set the screen width breakpoints in the variables.less file like this:

// Media queries breakpoints
// --------------------------------------------------

// Extra small screen / phone
// Note: Deprecated @screen-xs and @screen-phone as of v3.0.1
@screen-xs:                  1px;
@screen-xs-min:              @screen-xs;
@screen-phone:               @screen-xs-min;

// Small screen / tablet
// Note: Deprecated @screen-sm and @screen-tablet as of v3.0.1
@screen-sm:                  2px;
@screen-sm-min:              @screen-sm;
@screen-tablet:              @screen-sm-min;

// Medium screen / desktop
// Note: Deprecated @screen-md and @screen-desktop as of v3.0.1
@screen-md:                  3px;
@screen-md-min:              @screen-md;
@screen-desktop:             @screen-md-min;

// Large screen / wide desktop
// Note: Deprecated @screen-lg and @screen-lg-desktop as of v3.0.1
@screen-lg:                  9999px;
@screen-lg-min:              @screen-lg;
@screen-lg-desktop:          @screen-lg-min;

This sets the min-width on the desktop style media query lower so that it applies to all screen widths. Thanks to 2calledchaos for the improvement! Some base styles are defined in the mobile styles, so we need to be sure to include them.

Edit: chris notes that you can set these variables in the online less compiler on the bootstrap site

How to fix UITableView separator on iOS 7?

This is default by iOS7 design. try to do the below:

[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

You can set the 'Separator Inset' from the storyboard:

enter image description here

enter image description here

How to convert a String to Bytearray

The best solution I've come up with at on the spot (though most likely crude) would be:

String.prototype.getBytes = function() {
    var bytes = [];
    for (var i = 0; i < this.length; i++) {
        var charCode = this.charCodeAt(i);
        var cLen = Math.ceil(Math.log(charCode)/Math.log(256));
        for (var j = 0; j < cLen; j++) {
            bytes.push((charCode << (j*8)) & 0xFF);
        }
    }
    return bytes;
}

Though I notice this question has been here for over a year.

POST request via RestTemplate in JSON

I'm doing in this way and it works .

HttpHeaders headers = createHttpHeaders(map);
public HttpHeaders createHttpHeaders(Map<String, String> map)
{   
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    for (Entry<String, String> entry : map.entrySet()) {
        headers.add(entry.getKey(),entry.getValue());
    }
    return headers;
}

// Pass headers here

 String requestJson = "{ // Construct your JSON here }";
logger.info("Request JSON ="+requestJson);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
logger.info("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
logger.info("Response ="+response.getBody());

Hope this helps

Spaces in URLs?

The information there is I think partially correct:

That's not true. An URL can use spaces. Nothing defines that a space is replaced with a + sign.

As you noted, an URL can NOT use spaces. The HTTP request would get screwed over. I'm not sure where the + is defined, though %20 is standard.

How do I mount a host directory as a volume in docker compose

Checkout their documentation

From the looks of it you could do the following on your docker-compose.yml

volumes:
    - ./:/app

Where ./ is the host directory, and /app is the target directory for the containers.


EDIT:
Previous documentation source now leads to version history, you'll have to select the version of compose you're using and look for the reference.

For the lazy – v3 / v2 / v1

Side note: Syntax remains the same for all versions as of this edit

What is the proper declaration of main in C++?

The two valid mains are int main() and int main(int, char*[]). Any thing else may or may not compile. If main doesn't explicitly return a value, 0 is implicitly returned.

Symbol for any number of any characters in regex?

Do you mean

.*

. any character, except newline character, with dotall mode it includes also the newline characters

* any amount of the preceding expression, including 0 times

python requests file upload

If upload_file is meant to be the file, use:

files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.

The filename will be included in the mime header for the specific field:

>>> import requests
>>> open('file.txt', 'wb')  # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"


--c226ce13d09842658ffbd31e0563c6bd--

Note the filename="file.txt" parameter.

You can use a tuple for the files mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:

files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}

This sets an alternative filename and content type, leaving out the optional headers.

If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files parameter, just post the file directly as data. You then may want to set a Content-Type header too, as none will be set otherwise. See Python requests - POST data from a file.

Can you delete data from influxdb?

I'm surprised that nobody has mentioned InfluxDB retention policies for automatic data removal. You can set a default retention policy and also set them on a per-database level.

From the docs:

CREATE RETENTION POLICY <retention_policy_name> ON <database_name> DURATION <duration> REPLICATION <n> [DEFAULT]

How to label each equation in align environment?

Within the environment align from the package amsmath it is possible to combine the use of \label and \tag for each equation or line. For example, the code:

\documentclass{article}
\usepackage{amsmath}

\begin{document}
Write
\begin{align}
x+y\label{eq:eq1}\tag{Aa}\\
x+z\label{eq:eq2}\tag{Bb}\\
y-z\label{eq:eq3}\tag{Cc}\\
y-2z\nonumber
\end{align}
then cite \eqref{eq:eq1} and \eqref{eq:eq2} or \eqref{eq:eq3} separately.
\end{document}

produces:

screenshot of output

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

As @Izabela Orlowska pointed out: In my case the problem occurred due to some files that could not be found inside the gradle cache folder. (Windows OS)

The default gradle path was inside my user folder. the path contained umlauts and a space. I moved the gradle folder by setting GRADLE_HOME and GRADLE_USER_HOME environment variable to some newly created folder without umlauts or spaces in path. This fixed the problem for me.

How to do error logging in CodeIgniter (PHP)

In config.php add or edit the following lines to this:
------------------------------------------------------
$config['log_threshold'] = 4; // (1/2/3)
$config['log_path'] = '/home/path/to/application/logs/';

Run this command in the terminal:
----------------------------------
sudo chmod -R 777 /home/path/to/application/logs/

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

Creating CSS Global Variables : Stylesheet theme management

It's not possible using CSS, but using a CSS preprocessor like less or SASS.

How do I delete a local repository in git?

To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:

$ rm -rf .git

Or to delete .gitignore and .gitmodules if any (via @aragaer):

$ rm -rf .git*

Then from the same ex-repository folder, to see if hidden folder .git is still there:

$ ls -lah

If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).

To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:

defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder

Source: http://lifehacker.com/188892/show-hidden-files-in-finder.

Display encoded html with razor

Try this:

<div class='content'>    
   @Html.Raw(HttpUtility.HtmlDecode(Model.Content))
</div>

How can I configure my makefile for debug and release builds?

You can use Target-specific Variable Values. Example:

CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2

all: executable

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

Remember to use $(CXX) or $(CC) in all your compile commands.

Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.

On a side note, you can make your Makefile a lot more concise like other posts had suggested.

Sort Pandas Dataframe by Date

sort method has been deprecated and replaced with sort_values. After converting to datetime object using df['Date']=pd.to_datetime(df['Date'])

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

Note: to sort in-place and/or in a descending order (the most recent first):

df.sort_values(by=['Date'], inplace=True, ascending=False)

Jenkins CI: How to trigger builds on SVN commit

I made a tool using Python with some bash to trigger a Jenkins build. Basically you have to collect these two values from post-commit when a commit hits the SVN server:

REPOS="$1"
REV="$2"

Then you use "svnlook dirs-changed $1 -r $2" to get the path which is has just committed. Then from that you can check which repository you want to build. Imagine you have hundred of thousand of projects. You can't check the whole repository, right?

You can check out my script from GitHub.

How to compare DateTime without time via LINQ?

Try

var q = db.Games.Where(t => t.StartDate.Date >= DateTime.Now.Date).OrderBy(d => d.StartDate);

Cygwin Make bash command not found

I faced the same problem too. Look up to the left side, and select (full). (Make), (gcc) and many others will appear. You will be able to chose the search bar to find them easily.

How can I remove a style added with .css() function?

You can use:

 $("#eslimi").removeAttr("style").hide();

What is the right way to treat argparse.Namespace() as a dictionary?

You can access the namespace's dictionary with vars():

>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}

You can modify the dictionary directly if you wish:

>>> d['baz'] = 'store me'
>>> args.baz
'store me'

Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.

Show and hide divs at a specific time interval using jQuery

here is a jQuery plugin I came up with:

$.fn.cycle = function(timeout){
    var $all_elem = $(this)

    show_cycle_elem = function(index){
        if(index == $all_elem.length) return; //you can make it start-over, if you want
        $all_elem.hide().eq(index).fadeIn()
        setTimeout(function(){show_cycle_elem(++index)}, timeout);
    }
    show_cycle_elem(0);
}

You need to have a common classname for all the divs you wan to cycle, use it like this:

$("div.cycleme").cycle(5000)

Python AttributeError: 'module' object has no attribute 'Serial'

This problem is beacouse your proyect is named serial.py and the library imported is name serial too , change the name and thats all.

iPhone X / 8 / 8 Plus CSS media queries

Here are some of the following media queries for iPhones. Here is the ref link https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions

        /* iphone 3 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 1) { }
        
        /* iphone 4 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 2) { }
        
        /* iphone 5 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (-webkit-device-pixel-ratio: 2) { }
        
        /* iphone 6, 6s, 7, 8 */
        @media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (-webkit-device-pixel-ratio: 2) { }
            
        /* iphone 6+, 6s+, 7+, 8+ */
        @media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (-webkit-device-pixel-ratio: 3) { }
        
        /* iphone X , XS, 11 Pro, 12 Mini */
        @media only screen and (min-device-width: 375px) and (max-device-height: 812px) and (-webkit-device-pixel-ratio: 3) { }

        /* iphone 12, 12 Pro */
        @media only screen and (min-device-width: 390px) and (max-device-height: 844px) and (-webkit-device-pixel-ratio: 3) { }
       
        /* iphone XR, 11 */
        @media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 2) { }
            
        /* iphone XS Max, 11 Pro Max */
        @media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 3) { }

        /* iphone 12 Pro Max */
        @media only screen and (min-device-width : 428px) and (max-device-height : 926px) and (-webkit-device-pixel-ratio : 3) { }

Object not found! The requested URL was not found on this server. localhost

I also had same error but with codeigniter application. I changed

  • my base URL in config.php to my localhost path

  • in htaccess I changed RewriteBase /"my folder name in htdocs"

    and I able to login to my application.

Hope it might help.

IIS7 Permissions Overview - ApplicationPoolIdentity

Giving access to the IIS AppPool\YourAppPoolName user may be not enough with IIS default configurations.

In my case, I still had the error HTTP Error 401.3 - Unauthorized after adding the AppPool user and it was fixed only after adding permissions to the IUSR user.

This is necessary because, by default, Anonymous access is done using the IUSR. You can set another specific user, the Application Pool or continue using the IUSR, but don't forget to set the appropriate permissions.

authentication tab

Credits to this answer: HTTP Error 401.3 - Unauthorized

Bootstrap trying to load map file. How to disable it? Do I need to do it?

.map files allow a browser to download a full version of the minified JS. It is really for debugging purposes.

In effect, the .map missing isn't a problem. You only know it is missing, as the browser has had its Developer tools opened, detected a minified file and is just informing you that the JS debugging won't be as good as it could be.

This is why libraries like jQuery have the full, the minified and the map file too.

See this article for a full explanation of .map files:

How to extract public key using OpenSSL?

For AWS importing an existing public key,

  1. Export from the .pem doing this... (on linux)

    openssl rsa -in ./AWSGeneratedKey.pem -pubout -out PublicKey.pub
    

This will produce a file which if you open in a text editor looking something like this...

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn/8y3uYCQxSXZ58OYceG
A4uPdGHZXDYOQR11xcHTrH13jJEzdkYZG8irtyG+m3Jb6f9F8WkmTZxl+4YtkJdN
9WyrKhxq4Vbt42BthadX3Ty/pKkJ81Qn8KjxWoL+SMaCGFzRlfWsFju9Q5C7+aTj
eEKyFujH5bUTGX87nULRfg67tmtxBlT8WWWtFe2O/wedBTGGQxXMpwh4ObjLl3Qh
bfwxlBbh2N4471TyrErv04lbNecGaQqYxGrY8Ot3l2V2fXCzghAQg26Hc4dR2wyA
PPgWq78db+gU3QsePeo2Ki5sonkcyQQQlCkL35Asbv8khvk90gist4kijPnVBCuv
cwIDAQAB
-----END PUBLIC KEY-----
  1. However AWS will NOT accept this file.

    You have to strip off the -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- from the file. Save it and import and it should work in AWS.

Is it possible to center text in select box?

You can't really customise <select> or <option> much. The only way (cross-browser) would be to manually create a drop down with divs and css/js to create something similar.

CreateProcess error=206, The filename or extension is too long when running main() method

Valid answer from this thread was the right answer for my special case. Specify the ORM folder path for datanucleus certainly reduce the java path compile.

https://stackoverflow.com/a/1219427/1469481

In Java, should I escape a single quotation mark (') in String (double quoted)?

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').

How can I switch word wrap on and off in Visual Studio Code?

Word wrap settings redesign

Here are the new word wrap options:

editor.wordWrap: "off" - Lines will never wrap.
editor.wordWrap: "on" - Lines will wrap at viewport width.
editor.wordWrap: "wordWrapColumn" - Lines will wrap at the value of editor.wordWrapColumn.
editor.wordWrap: "bounded" 

Lines will wrap at the minimum of viewport width and the value of editor.wordWrapColumn.

php hide ALL errors

Use PHP error handling functions to handle errors. How you do it depends on your needs. This system will intercept all errors and forward it however you want it Or supress it if you ask it to do so

http://php.net/manual/en/book.errorfunc.php

Count unique values using pandas groupby

I think you can use SeriesGroupBy.nunique:

print (df.groupby('param')['group'].nunique())
param
a    2
b    1
Name: group, dtype: int64

Another solution with unique, then create new df by DataFrame.from_records, reshape to Series by stack and last value_counts:

a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a    2
b    1
dtype: int64

How to install bcmath module?

To enable bcmath in Arch Linux or Manjaro

Edit php.ini

nano /etc/php/php.ini

Uncomment bcmath (remove semicolon)

extension=bcmath

If you are using Apache server reload the server by

sudo systemctl reload apache.server

Or

sudo systemctl realod httpd

If you don't use Apache

sudo systemctl reload php-fpm.service

To see the activated modules

php -m

To make sure the php-fpm is installed and activated, search for it

php -m | grep bcmath

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Parse usable Street Address, City, State, Zip from a string

Since there is chance of error in word, think about using SOUNDEX combined with LCS algorithm to compare strings, this will help a lot !

I want to calculate the distance between two points in Java

This may be OLD, but here is the best answer:

    float dist = (float) Math.sqrt(
            Math.pow(x1 - x2, 2) +
            Math.pow(y1 - y2, 2) );

random.seed(): What does it do?

A random number is generated by some operation on previous value.

If there is no previous value then the current time is taken as previous value automatically. We can provide this previous value by own using random.seed(x) where x could be any number or string etc.

Hence random.random() is not actually perfect random number, it could be predicted via random.seed(x).

import random 
random.seed(45)            #seed=45  
random.random()            #1st rand value=0.2718754143840908
0.2718754143840908  
random.random()            #2nd rand value=0.48802820785090784
0.48802820785090784  
random.seed(45)            # again reasign seed=45  
random.random()
0.2718754143840908         #matching with 1st rand value  
random.random()
0.48802820785090784        #matching with 2nd rand value

Hence, generating a random number is not actually random, because it runs on algorithms. Algorithms always give the same output based on the same input. This means, it depends on the value of the seed. So, in order to make it more random, time is automatically assigned to seed().

What does "request for member '*******' in something not a structure or union" mean?

It also happens if you're trying to access an instance when you have a pointer, and vice versa:

struct foo
{
  int x, y, z;
};

struct foo a, *b = &a;

b.x = 12;  /* This will generate the error, should be b->x or (*b).x */

As pointed out in a comment, this can be made excruciating if someone goes and typedefs a pointer, i.e. includes the * in a typedef, like so:

typedef struct foo* Foo;

Because then you get code that looks like it's dealing with instances, when in fact it's dealing with pointers:

Foo a_foo = get_a_brand_new_foo();
a_foo->field = FANTASTIC_VALUE;

Note how the above looks as if it should be written a_foo.field, but that would fail since Foo is a pointer to struct. I strongly recommend against typedef:ed pointers in C. Pointers are important, don't hide your asterisks. Let them shine.

How do I send email with JavaScript without opening the mail client?

You need to do it directly on a server. But a better way is using PHP. I have heard that PHP has a special code that can send e-mail directly without opening the mail client.

Amazon Linux: apt-get: command not found

I faced the same issue regarding apt-get: command not found here are the steps how I resolved it on ubuntu xenial

  • Search the appropriate version of apt from here (apt_1.4_amd64.deb for ubuntu xenial)

  • Download the apt.deb

    wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.4_amd64.deb

  • Install the apt.deb package

    sudo dpkg -i apt_1.4_amd64.deb

Now we can easily run

sudo apt-get install htop

How can I put an icon inside a TextInput in React Native?

Basically you can’t put an icon inside of a textInput but you can fake it by wrapping it inside a view and setting up some simple styling rules.

Here's how it works:

  • put both Icon and TextInput inside a parent View
  • set flexDirection of the parent to ‘row’ which will align the children next to each other
  • give TextInput flex 1 so it takes the full width of the parent View
  • give parent View a borderBottomWidth and push this border down with paddingBottom (this will make it appear like a regular textInput with a borderBottom)
    • (or you can add any other style depending on how you want it to look)

Code:

<View style={styles.passwordContainer}>
  <TextInput
    style={styles.inputStyle}
      autoCorrect={false}
      secureTextEntry
      placeholder="Password"
      value={this.state.password}
      onChangeText={this.onPasswordEntry}
    />
  <Icon
    name='what_ever_icon_you_want'
    color='#000'
    size={14}
  />
</View>

Style:

passwordContainer: {
  flexDirection: 'row',
  borderBottomWidth: 1,
  borderColor: '#000',
  paddingBottom: 10,
},
inputStyle: {
  flex: 1,
},

(Note: the icon is underneath the TextInput so it appears on the far right, if it was above TextInput it would appear on the left.)

How to create an empty array in PHP with predefined size?

 $array = new SplFixedArray(5);
   echo $array->getSize()."\n";

You can use PHP documentation more info check this link https://www.php.net/manual/en/splfixedarray.setsize.php

Why is my element value not getting changed? Am I using the wrong function?

Sounds like we need to assume that your textbox name and ID are both set to "Tue." If that's the case, try using a lower-case V on .value.

Adding a column to a data.frame

Easily: Your data frame is A

b <- A[,1]
b <- b==1
b <- cumsum(b)

Then you get the column b.

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

There was conflict in java version. Resolved after using 1.8 for maven.

How can I solve a connection pool problem between ASP.NET and SQL Server?

If you are working on complex legacy code where a simple using(..) {..} isn't possible - as I was - you may want to check out the code snippet I posted in this SO question for a way to determine the call stack of the connection creation when a connection is potentially leaked (not closed after a set timeout). This makes it fairly easy to spot the cause of the leaks.

Foreign key constraints: When to use ON UPDATE and ON DELETE

You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).

Consider how your application should respond to various cases.

The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.

Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.

How to concatenate text from multiple rows into a single text string in SQL server?

@User1460901 You can try something like this:

WITH cte_base AS (
    SELECT CustomerCode, CustomerName,
    CASE WHEN Typez = 'Breakfast' THEN Items ELSE NULL END AS 'BREAKFAST'
    , CASE WHEN Typez = 'Lunch' THEN Items ELSE NULL END AS 'LUNCH'
    FROM #Customer
    )
    SELECT distinct CustomerCode, CustomerName,
    SUBSTRING(
    (   
        SELECT ','+BREAKFAST AS [text()]
        FROM cte_base b1
        WHERE b1.CustomerCode = b2.CustomerCode AND b1.CustomerName = b2.CustomerName
        ORDER BY b1.BREAKFAST
        FOR XML PATH('')
        ), 2, 1000
    ) [BREAKFAST], 
    SUBSTRING(
    (   
        SELECT ','+LUNCH AS [text()]
        FROM cte_base b1
        WHERE b1.CustomerCode = b2.CustomerCode AND b1.CustomerName = b2.CustomerName
        ORDER BY b1.LUNCH
        FOR XML PATH('')
        ), 2, 1000
    ) [LUNCH]
    FROM cte_base b2

How do I show my global Git configuration?

Since Git 2.26.0, you can use --show-scope option:

git config --list --show-scope

Example output:

system  rebase.autosquash=true
system  credential.helper=helper-selector
global  core.editor='code.cmd' --wait -n
global  merge.tool=kdiff3
local   core.symlinks=false
local   core.ignorecase=true

It can be combined with

  • --local for project config, --global for user config, --system for all users' config
  • --show-origin to show the exact config file location

How to pick an image from gallery (SD Card) for my app?

public class BrowsePictureActivity extends Activity {
private static final int SELECT_PICTURE = 1;

private String selectedImagePath;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById(R.id.Button01))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {

                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,
                            "Select Picture"), SELECT_PICTURE);
                }
            });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
        }
    }
}

public String getPath(Uri uri) {

        if( uri == null ) {
            return null;
        }

        // this will only work for images selected from gallery
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if( cursor != null ){
            int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }

        return uri.getPath();
}

}

Mockito How to mock and assert a thrown exception?

To answer your second question first. If you're using JUnit 4, you can annotate your test with

@Test(expected=MyException.class)

to assert that an exception has occured. And to "mock" an exception with mockito, use

when(myMock.doSomething()).thenThrow(new MyException());

How to reset a timer in C#?

For clarity since some other comments are incorrect, when using System.Timers setting Enabled to true will reset the elapsed time. I just tested the behavior with the below:

Timer countDown= new Timer(3000);

Main()
{
    TextBox.TextDidChange += TextBox_TextDidChange;
    countdown.Elapsed += CountDown_Elapsed;
}

void TextBox_TextDidChange(Object sender, EventArgs e)
{
    countdown.Enabled = true;
}

void CountDown_Elapsed(object sender, EventArgs e)
{
    System.Console.WriteLine("Elapsed");
}

I would input text to the text box repeatedly and the timer would only run 3 seconds after the last keystroke. It's hinted at in the docs as well, as you'll see: calling Timers.Start() simply sets Enabled to true.

And to be sure, which I should've just went straight to from the beginning, you'll see in the .NET reference source that if enabling an already Enabled timer it calls the private UpdateTimer() method, which internally calls Change().

How can I make a multipart/form-data POST request using Java?

httpcomponents-client-4.0.1 worked for me. However, I had to add the external jar apache-mime4j-0.6.jar (org.apache.james.mime4j) otherwise reqEntity.addPart("bin", bin); would not compile. Now it's working like charm.

AngularJS sorting by property

Armin's answer + a strict check for object types and non-angular keys such as $resolve

app.filter('orderObjectBy', function(){
 return function(input, attribute) {
    if (!angular.isObject(input)) return input;

    var array = [];
    for(var objectKey in input) {
      if (typeof(input[objectKey])  === "object" && objectKey.charAt(0) !== "$")
        array.push(input[objectKey]);
    }

    array.sort(function(a, b){
        a = parseInt(a[attribute]);
        b = parseInt(b[attribute]);
        return a - b;
    });

    return array;
 }
})

How to retrieve the first word of the output of a command in bash?

Using shell parameter expansion %% *

Here is another solution using shell parameter expansion. It takes care of multiple spaces after the first word. Handling spaces in front of the first word requires one additional expansion.

string='word1    word2'
echo ${string%% *}
word1

string='word1    word2      '
echo ${string%% *}
word1

Explanation

The %% signifies deleting the longest possible match of * (a space followed by any number of whatever other characters) in the trailing part of string.

Setting up and using Meld as your git difftool and mergetool

For Windows 10 I had to put this in my .gitconfig:

[merge]
  tool = meld
[mergetool "meld"]
  cmd = 'C:/Program Files (x86)/Meld/Meld.exe' $LOCAL $BASE $REMOTE --output=$MERGED
[mergetool]
  prompt = false

Everything else you need to know is written in this super answer by mattst further above.

PS: For some reason, this only worked with Meld 3.18.x, Meld 3.20.x gives me an error.

"ssl module in Python is not available" when installing package with pip3

I encountered the same problem on windows 10. My very specific issue is due to my installation of Anaconda. I installed Anaconda and under the path Path/to/Anaconda3/, there comes the python.exe. Thus, I didn't install python at all because Anaconda includes python. When using pip to install packages, I found the same error report, pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available..

The solution was the following:

1) you can download python again on the official website;

2) Navigate to the directory where "Python 3.7 (64-bit).lnk"is located

3) import ssl and exit()

4) type in cmd, "Python 3.7 (64-bit).lnk" -m pip install tensorflow for instance.

Here, you're all set.

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

If the property does not change for the widget it may be better to use like android:imeOptions="actionDone" in the layout xml file.

How to prevent a click on a '#' link from jumping to top of page?

Solution #1: (plain)

<a href="#!" class="someclass">Text</a>

Solution #2: (needed javascript)

<a href="javascript:void(0);" class="someclass">Text</a>

Solution #3: (needed jQuery)

<a href="#" class="someclass">Text</a>
<script>
$('a.someclass').click(function(e) {
    e.preventDefault();
});
</script>

'tuple' object does not support item assignment

Tuples, in python can't have their values changed. If you'd like to change the contained values though I suggest using a list:

[1,2,3] not (1,2,3)

How to multiply a BigDecimal by an integer in Java

If I were you, I would set the scale of the BigDecimal so that I dont end up on lengthy numbers. The integer 2 in the BigDecimal initialization below sets the scale.

Since you have lots of mismatch of data type, I have changed it accordingly to adjust.

class Payment   
{
      BigDecimal itemCost=new BigDecimal(BigInteger.ZERO,  2);
      BigDecimal totalCost=new BigDecimal(BigInteger.ZERO,  2);

     public BigDecimal calculateCost(int itemQuantity,BigDecimal itemPrice)
       { 
           BigDecimal   itemCost = itemPrice.multiply(new BigDecimal(itemQuantity)); 
             return totalCost.add(itemCost); 
       }
  }

BigDecimals are Object , not primitives, so make sure you initialize itemCost and totalCost , otherwise it can give you nullpointer while you try to add on totalCost or itemCost

Correct way of looping through C++ arrays

Add a stopping value to the array:

#include <iostream>
using namespace std;

int main ()
{
   string texts[] = {"Apple", "Banana", "Orange", ""};
   for( unsigned int a = 0; texts[a].length(); a = a + 1 )
   {
       cout << "value of a: " << texts[a] << endl;
   }

   return 0;
}

Running Command Line in Java

Have you tried the exec command within the Runtime class?

Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")

Runtime - Java Documentation

XML string to XML document

This code sample is taken from csharp-examples.net, written by Jan Slama:

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.

XML:

<Names>
    <Name>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
    </Name>
    <Name>
        <FirstName>James</FirstName>
        <LastName>White</LastName>
    </Name>
</Names>

CODE:

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
  string firstName = xn["FirstName"].InnerText;
  string lastName = xn["LastName"].InnerText;
  Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

Python: fastest way to create a list of n lists

The probably only way which is marginally faster than

d = [[] for x in xrange(n)]

is

from itertools import repeat
d = [[] for i in repeat(None, n)]

It does not have to create a new int object in every iteration and is about 15 % faster on my machine.

Edit: Using NumPy, you can avoid the Python loop using

d = numpy.empty((n, 0)).tolist()

but this is actually 2.5 times slower than the list comprehension.

Change column type in pandas

I thought I had the same problem but actually I have a slight difference that makes the problem easier to solve. For others looking at this question it's worth checking the format of your input list. In my case the numbers are initially floats not strings as in the question:

a = [['a', 1.2, 4.2], ['b', 70, 0.03], ['x', 5, 0]]

but by processing the list too much before creating the dataframe I lose the types and everything becomes a string.

Creating the data frame via a numpy array

df = pd.DataFrame(np.array(a))

df
Out[5]: 
   0    1     2
0  a  1.2   4.2
1  b   70  0.03
2  x    5     0

df[1].dtype
Out[7]: dtype('O')

gives the same data frame as in the question, where the entries in columns 1 and 2 are considered as strings. However doing

df = pd.DataFrame(a)

df
Out[10]: 
   0     1     2
0  a   1.2  4.20
1  b  70.0  0.03
2  x   5.0  0.00

df[1].dtype
Out[11]: dtype('float64')

does actually give a data frame with the columns in the correct format

How to fill 100% of remaining height?

To get a div to 100% height on a page, you will need to set each object on the hierarchy above the div to 100% as well. for instance:

html { height:100%; }
body { height:100%; }
#full { height: 100%; }
#someid { height: 100%; }

Although I cannot fully understand your question, I'm assuming this is what you mean.

This is the example I am working from:

<html style="height:100%">
    <body style="height:100%">
        <div style="height:100%; width: 300px;">
            <div style="height:100%; background:blue;">

            </div>
        </div>
    </body>
</html>

Style is just a replacement for the CSS which I haven't externalised.

Convert JSON String to Pretty Print JSON output using Jackson

The new way using Jackson 1.9+ is the following:

Object json = OBJECT_MAPPER.readValue(diffResponseJson, Object.class);
String indented = OBJECT_MAPPER.writerWithDefaultPrettyPrinter()
                               .writeValueAsString(json);

The output will be correctly formatted!

Checking for Undefined In React

What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like

componentWillReceiveProps(nextProps) {

    if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
       console.log("new title is", nextProps.blog.title);
       console.log("new body content is", nextProps.blog.content["body"]);
       this.setState({
           title: nextProps.blog.title,
           body: nextProps.blog.content["body"]
       })
    }
}

You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value

In order to check for undefined, you can also use the typeof operator like

typeof nextProps.blog.content != "undefined"

Simple argparse example wanted: 1 argument, 3 results

Since you have not clarified wheather the arguments 'A' and 'B' are positional or optional, I'll make a mix of both.

Positional arguments are required by default. If not giving one will throw 'Few arguments given' which is not the case for the optional arguments going by their name. This program will take a number and return its square by default, if the cube option is used it shall return its cube.

import argparse
parser = argparse.ArgumentParser('number-game')
parser.add_argument(
    "number",
    type=int,
    help="enter a number"
   )
parser.add_argument(
   "-c", "--choice",
   choices=['square','cube'],
   help="choose what you need to do with the number"
)

# all the results will be parsed by the parser and stored in args
args = parser.parse_args()

# if square is selected return the square, same for cube 
if args.c == 'square':
    print("{} is the result".format(args.number**2))
elif args.c == 'cube':
    print("{} is the result".format(args.number**3))
else:
    print("{} is not changed".format(args.number))

usage

$python3 script.py 4 -c square
16

Here the optional arguments are taking value, if you just wanted to use it like a flag you can too. So by using -s for square and -c for cube we change the behaviour, by adding action = "store_true". It is changed to true only when used.

parser.add_argument(
    "-s", "--square",
    help="returns the square of number",
    action="store_true"
    )
parser.add_argument(
    "-c", "--cube",
    help="returns the cube of number",
    action="store_true"
    )

so the conditional block can be changed to,

if args.s:
    print("{} is the result".format(args.number**2))
elif args.c:
    print("{} is the result".format(args.number**3))
else:
    print("{} is not changed".format(args.number))

usage

$python3 script.py 4 -c
64

In python, what is the difference between random.uniform() and random.random()?

random.random() gives you a random floating point number in the range [0.0, 1.0) (so including 0.0, but not including 1.0 which is also known as a semi-open range). random.uniform(a, b) gives you a random floating point number in the range [a, b], (where rounding may end up giving you b).

The implementation of random.uniform() uses random.random() directly:

def uniform(self, a, b):
    "Get a random number in the range [a, b) or [a, b] depending on rounding."
    return a + (b-a) * self.random()

random.uniform(0, 1) is basically the same thing as random.random() (as 1.0 times float value closest to 1.0 still will give you float value closest to 1.0 there is no possibility of a rounding error there).

How to resolve the C:\fakepath?

Hy there , in my case i am using asp.net development environment, so i was want to upload those data in asynchronus ajax request , in [webMethod] you can not catch the file uploader since it is not static element , so i had to make a turnover for such solution by fixing the path , than convert the wanted image into bytes to save it in DB .

Here is my javascript function , hope it helps you:

function FixPath(Path)
         {
             var HiddenPath = Path.toString();
             alert(HiddenPath.indexOf("FakePath"));

             if (HiddenPath.indexOf("FakePath") > 1)
             {
                 var UnwantedLength = HiddenPath.indexOf("FakePath") + 7;
                 MainStringLength = HiddenPath.length - UnwantedLength;
                 var thisArray =[];
                 var i = 0;
                 var FinalString= "";
                 while (i < MainStringLength)
                 {
                     thisArray[i] = HiddenPath[UnwantedLength + i + 1];
                     i++;
                 }
                 var j = 0;
                 while (j < MainStringLength-1)
                 {
                     if (thisArray[j] != ",")
                     {
                         FinalString += thisArray[j];
                     }
                     j++;
                 }
                 FinalString = "~" + FinalString;
                 alert(FinalString);
                 return FinalString;
             }
             else
             {
                 return HiddenPath;
             }
         }

here only for testing :

 $(document).ready(function () {
             FixPath("hakounaMatata:/7ekmaTa3mahaLaziz/FakePath/EnsaLmadiLiYghiz");
         });
// this will give you : ~/EnsaLmadiLiYghiz

How to handle ETIMEDOUT error?

In case if you are using node js, then this could be the possible solution

const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;

https://medium.com/hk01-tech/running-eks-in-production-for-2-years-the-kubernetes-journey-at-hk01-68130e603d76

Pagination on a list using ng-repeat

Check out this directive: https://github.com/samu/angular-table

It automates sorting and pagination a lot and gives you enough freedom to customize your table/list however you want.

recursively use scp but excluding some folders

Assuming the simplest option (installing rsync on the remote host) isn't feasible, you can use sshfs to mount the remote locally, and rsync from the mount directory. That way you can use all the options rsync offers, for example --exclude.

Something like this should do:

sshfs user@server: sshfsdir
rsync --recursive --exclude=whatever sshfsdir/path/on/server /where/to/store

Note that the effectiveness of rsync (only transferring changes, not everything) doesn't apply here. This is because for that to work, rsync must read every file's contents to see what has changed. However, as rsync runs only on one host, the whole file must be transferred there (by sshfs). Excluded files should not be transferred, however.

How to position a DIV in a specific coordinates?

You don't have to use Javascript to do this. Using plain-old css:

div.blah {
  position:absolute;
  top: 0; /*[wherever you want it]*/
  left:0; /*[wherever you want it]*/
}

If you feel you must use javascript, or are trying to do this dynamically Using JQuery, this affects all divs of class "blah":

var blahclass =  $('.blah'); 
blahclass.css('position', 'absolute');
blahclass.css('top', 0); //or wherever you want it
blahclass.css('left', 0); //or wherever you want it

Alternatively, if you must use regular old-javascript you can grab by id

var domElement = document.getElementById('myElement');// don't go to to DOM every time you need it. Instead store in a variable and manipulate.
domElement.style.position = "absolute";
domElement.style.top = 0; //or whatever 
domElement.style.left = 0; // or whatever

Pass object to javascript function

function myFunction(arg) {
    alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}

myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });

How do check if a PHP session is empty?

you are looking for PHP’s empty() function

SQL query to find Nth highest salary from a salary table

if wanna specified nth highest,could use rank method.

To get the third highest, use

SELECT * FROM
(SELECT @rank := @rank + 1 AS rank, salary
FROM   tbl,(SELECT @rank := 0) r 
order by salary desc ) m
WHERE rank=3

How do I remove the "extended attributes" on a file in Mac OS X?

Another recursive approach:

# change directory to target folder:
cd /Volumes/path/to/folder

# find all things of type "f" (file), 
# then pipe "|" each result as an argument (xargs -0) 
# to the "xattr -c" command:
find . -type f -print0 | xargs -0 xattr -c

# Sometimes you may have to use a star * instead of the dot.
# The dot just means "here" (whereever your cd'd to
find * -type f -print0 | xargs -0 xattr -c

What is the best way to create a string array in python?

def _remove_regex(input_text, regex_pattern):
    findregs = re.finditer(regex_pattern, input_text) 
    for i in findregs: 
        input_text = re.sub(i.group().strip(), '', input_text)
    return input_text

regex_pattern = r"\buntil\b|\bcan\b|\bboat\b"
_remove_regex("row and row and row your boat until you can row no more", regex_pattern)

\w means that it matches word characters, a|b means match either a or b, \b represents a word boundary

Instance member cannot be used on type

It is saying you have an instance variable (the var is only visible/accessible when you have an instance of that class) and you are trying to use it in the context of a static scope (class method).

You can make your instance variable a class variable by adding static/class attribute.

You instantiate an instance of your class and call the instance method on that variable.

How to change visibility of layout programmatically

this is a programatical approach:

 view.setVisibility(View.GONE); //For GONE
 view.setVisibility(View.INVISIBLE); //For INVISIBLE
 view.setVisibility(View.VISIBLE); //For VISIBLE

SQL Server: Examples of PIVOTing String data

With pivot_data as
(
select 
action, -- grouping column
view_edit -- spreading column
from tbl
)
select action, [view], [edit]
from   pivot_data
pivot  ( max(view_edit) for view_edit in ([view], [edit]) ) as p;

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Simply difference between Forward(ServletRequest request, ServletResponse response) and sendRedirect(String url) is

forward():

  1. The forward() method is executed in the server side.
  2. The request is transfer to other resource within same server.
  3. It does not depend on the client’s request protocol since the forward () method is provided by the servlet container.
  4. The request is shared by the target resource.
  5. Only one call is consumed in this method.
  6. It can be used within server.
  7. We cannot see forwarded message, it is transparent.
  8. The forward() method is faster than sendRedirect() method.
  9. It is declared in RequestDispatcher interface.

sendRedirect():

  1. The sendRedirect() method is executed in the client side.
  2. The request is transfer to other resource to different server.
  3. The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.
  4. New request is created for the destination resource.
  5. Two request and response calls are consumed.
  6. It can be used within and outside the server.
  7. We can see redirected address, it is not transparent.
  8. The sendRedirect() method is slower because when new request is created old request object is lost.
  9. It is declared in HttpServletResponse.

Why should text files end with a newline?

This originates from the very early days when simple terminals were used. The newline char was used to trigger a 'flush' of the transferred data.

Today, the newline char isn't required anymore. Sure, many apps still have problems if the newline isn't there, but I'd consider that a bug in those apps.

If however you have a text file format where you require the newline, you get simple data verification very cheap: if the file ends with a line that has no newline at the end, you know the file is broken. With only one extra byte for each line, you can detect broken files with high accuracy and almost no CPU time.

phpMyAdmin on MySQL 8.0

in my case, to fix it I preferred to create a new user to use with PhpMyAdmin because modifying the root user has caused native login problems with other applications such as MySQL WorkBench.

This is what I did:

  • Log in to MySQL console with root user: mysql -u root -p, enter your password.
  • Let’s create a new user within the MySQL shell:
CREATE USER 'newMySqlUsername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysqlNewUsernamePassword';
  • At this point the newMysqlUsername has no permissions to do anything with the databases. So is needed to provide the user with access to the information they will need.
GRANT ALL PRIVILEGES ON * . * TO ' newMySqlUsername'@'localhost';
  • Once you have finalized the permissions that you want to set up for your new users, always be sure to reload all the privileges.
FLUSH PRIVILEGES;
  • Log out by typing quit or \q, and your changes will now be in effect, we can log in into PhpMyAdmin with the new user and it will have access to the databases.

  • Also you can log back in with this command in terminal:

mysql -u newMySqlUsername -p

Create a temporary table in MySQL with an index from a select

I wrestled quite a while with the proper syntax for CREATE TEMPORARY TABLE SELECT. Having figured out a few things, I wanted to share the answers with the rest of the community.

Basic information about the statement is available at the following MySQL links:

CREATE TABLE SELECT and CREATE TABLE.

At times it can be daunting to interpret the spec. Since most people learn best from examples, I will share how I have created a working statement, and how you can modify it to work for you.

  1. Add multiple indexes

    This statement shows how to add multiple indexes (note that index names - in lower case - are optional):

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (INDEX my_index_name (tag, time), UNIQUE my_unique_index_name (order_number))
    SELECT * FROM core.my_big_table
    WHERE my_val = 1
    
  2. Add a new primary key:

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (PRIMARY KEY my_pkey (order_number),
    INDEX cmpd_key (user_id, time))
    SELECT * FROM core.my_big_table
    
  3. Create additional columns

    You can create a new table with more columns than are specified in the SELECT statement. Specify the additional column in the table definition. Columns specified in the table definition and not found in select will be first columns in the new table, followed by the columns inserted by the SELECT statement.

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (my_new_id BIGINT NOT NULL AUTO_INCREMENT,  
    PRIMARY KEY my_pkey (my_new_id), INDEX my_unique_index_name (invoice_number))
    SELECT * FROM core.my_big_table
    
  4. Redefining data types for the columns from SELECT

    You can redefine the data type of a column being SELECTed. In the example below, column tag is a MEDIUMINT in core.my_big_table and I am redefining it to a BIGINT in core.my_tmp_table.

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (tag BIGINT,
    my_time DATETIME,  
    INDEX my_unique_index_name (tag) )
    SELECT * FROM core.my_big_table
    
  5. Advanced field definitions during create

    All the usual column definitions are available as when you create a normal table. Example:

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    value BIGINT UNSIGNED NOT NULL DEFAULT 0 UNIQUE,
    location VARCHAR(20) DEFAULT "NEEDS TO BE SET",
    country CHAR(2) DEFAULT "XX" COMMENT "Two-letter country code",  
    INDEX my_index_name (location))
    ENGINE=MyISAM 
    SELECT * FROM core.my_big_table
    

How to post data to specific URL using WebClient in C#

I just found the solution and yea it was easier than I thought :)

so here is the solution:

string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";

using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(URI, myParameters);
}

it works like charm :)

Convert Long into Integer

The best simple way of doing so is:

public static int safeLongToInt( long longNumber ) 
    {
        if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE ) 
        {
            throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
        }
        return (int) longNumber;
    }

How to add images in select list?

You already have several answers that suggest using JavaScript/jQuery. I am going to add an alternative that only uses HTML and CSS without any JS.

The basic idea is to use a set of radio buttons and labels (that will activate/deactivate the radio buttons), and with CSS control that only the label associated to the selected radio button will be displayed. If you want to allow selecting multiple values, you could achieve it by using checkboxes instead of radio buttons.

Here is an example. The code may be a bit messier (specially compared to the other solutions):

_x000D_
_x000D_
.select-sim {_x000D_
  width:200px;_x000D_
  height:22px;_x000D_
  line-height:22px;_x000D_
  vertical-align:middle;_x000D_
  position:relative;_x000D_
  background:white;_x000D_
  border:1px solid #ccc;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
.select-sim::after {_x000D_
  content:"?";_x000D_
  font-size:0.5em;_x000D_
  font-family:arial;_x000D_
  position:absolute;_x000D_
  top:50%;_x000D_
  right:5px;_x000D_
  transform:translate(0, -50%);_x000D_
}_x000D_
_x000D_
.select-sim:hover::after {_x000D_
  content:"";_x000D_
}_x000D_
_x000D_
.select-sim:hover {_x000D_
  overflow:visible;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option label {_x000D_
  display:inline-block;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options {_x000D_
  background:white;_x000D_
  border:1px solid #ccc;_x000D_
  position:absolute;_x000D_
  top:-1px;_x000D_
  left:-1px;_x000D_
  width:100%;_x000D_
  height:88px;_x000D_
  overflow-y:scroll;_x000D_
}_x000D_
_x000D_
.select-sim .options .option {_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option {_x000D_
  height:22px;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
.select-sim .options .option img {_x000D_
  vertical-align:middle;_x000D_
}_x000D_
_x000D_
.select-sim .options .option label {_x000D_
  display:none;_x000D_
}_x000D_
_x000D_
.select-sim .options .option input {_x000D_
  width:0;_x000D_
  height:0;_x000D_
  overflow:hidden;_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  float:left;_x000D_
  display:inline-block;_x000D_
  /* fix specific for Firefox */_x000D_
  position: absolute;_x000D_
  left: -10000px;_x000D_
}_x000D_
_x000D_
.select-sim .options .option input:checked + label {_x000D_
  display:block;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option input + label {_x000D_
  display:block;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option input:checked + label {_x000D_
  background:#fffff0;_x000D_
}
_x000D_
<div class="select-sim" id="select-color">_x000D_
  <div class="options">_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="" id="color-" checked />_x000D_
      <label for="color-">_x000D_
        <img src="http://placehold.it/22/ffffff/ffffff" alt="" /> Select an option_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="red" id="color-red" />_x000D_
      <label for="color-red">_x000D_
        <img src="http://placehold.it/22/ff0000/ffffff" alt="" /> Red_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="green" id="color-green" />_x000D_
      <label for="color-green">_x000D_
        <img src="http://placehold.it/22/00ff00/ffffff" alt="" /> Green_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="blue" id="color-blue" />_x000D_
      <label for="color-blue">_x000D_
        <img src="http://placehold.it/22/0000ff/ffffff" alt="" /> Blue_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="yellow" id="color-yellow" />_x000D_
      <label for="color-yellow">_x000D_
        <img src="http://placehold.it/22/ffff00/ffffff" alt="" /> Yellow_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="pink" id="color-pink" />_x000D_
      <label for="color-pink">_x000D_
        <img src="http://placehold.it/22/ff00ff/ffffff" alt="" /> Pink_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="turquoise" id="color-turquoise" />_x000D_
      <label for="color-turquoise">_x000D_
        <img src="http://placehold.it/22/00ffff/ffffff" alt="" /> Turquoise_x000D_
      </label>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SQL RANK() versus ROW_NUMBER()

Look this example.

CREATE TABLE [dbo].#TestTable(
    [id] [int] NOT NULL,
    [create_date] [date] NOT NULL,
    [info1] [varchar](50) NOT NULL,
    [info2] [varchar](50) NOT NULL,
)

Insert some data

INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/1/09', 'Blue', 'Green')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/2/09', 'Red', 'Yellow')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/3/09', 'Orange', 'Purple')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (2, '1/1/09', 'Yellow', 'Blue')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (2, '1/5/09', 'Blue', 'Orange')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (3, '1/2/09', 'Green', 'Purple')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (3, '1/8/09', 'Red', 'Blue')

Repeat same Values for 1

INSERT INTO dbo.#TestTable (id, create_date, info1, info2) VALUES (1, '1/1/09', 'Blue', 'Green')

Look All

SELECT * FROM #TestTable

Look your results

SELECT Id,
    create_date,
    info1,
    info2,
    ROW_NUMBER() OVER (PARTITION BY Id ORDER BY create_date DESC) AS RowId,
    RANK() OVER(PARTITION BY Id ORDER BY create_date DESC)    AS [RANK]
FROM #TestTable

Need to understand the different

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

Just put ojdbc6.jar in class path, so that we can fix CallbaleStatement exception:

oracle.jdbc.driver.T4CPreparedStatement.setBinaryStream(ILjava/io/InputStream;J)V)

in Oracle.

How to check if the user can go back in browser history or not

the browser has back and forward button. I come up a solution on this question. but It will affect browser forward action and cause bug with some browsers.

It works like that: If the browser open a new url, that has never opened, the history.length will be grow.

so you can change hash like

  location.href = '#__transfer__' + new Date().getTime() 

to get a never shown url, then history.length will get the true length.

  var realHistoryLength = history.length - 1

but, It not always work well, and I don't known why ,especially the when url auto jump quickly.

Creating object with dynamic keys

In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.

The syntax is:

var obj = {
  [myKey]: value,
}

If applied to the OP's scenario, it would turn into:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    return {
      [this.attr('name')]: this.attr('value'),
    };
  }) 

  callback(null, inputs);
}

Note: A transpiler is still required for browser compatiblity.

Using Babel or Google's traceur, it is possible to use this syntax today.


In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.

To use a "dynamic" key, you have to use bracket notation:

var obj = {};
obj[myKey] = value;

In your case:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    var key   = this.attr('name')
     ,  value = this.attr('value')
     ,  ret   = {};

     ret[key] = value;
     return ret;
  }) 

  callback(null, inputs);
}

Matplotlib scatterplot; colour as a function of a third variable

There's no need to manually set the colors. Instead, specify a grayscale colormap...

import numpy as np
import matplotlib.pyplot as plt

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()

plt.show()

enter image description here

Or, if you'd prefer a wider range of colormaps, you can also specify the cmap kwarg to scatter. To use the reversed version of any of these, just specify the "_r" version of any of them. E.g. gray_r instead of gray. There are several different grayscale colormaps pre-made (e.g. gray, gist_yarg, binary, etc).

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()

Multiple IF statements between number ranges

Shorter than accepted A, easily extensible and addresses 0 and below:

=if(or(A2<=0,A2>2000),"?",if(A2<500,"Less than 500","Between "&500*int(A2/500)&" and "&500*(int(A2/500)+1))) 

How to get current time and date in Android

You should use Calender class according to new API. Date class is deprecated now.

Calendar cal = Calendar.getInstance();

String date = ""+cal.get(Calendar.DATE)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.YEAR);

String time = ""+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);

How do I get information about an index and table owner in Oracle?

The following may help give you want you need:

SELECT
    index_owner, index_name, table_name, column_name, column_position
FROM DBA_IND_COLUMNS
ORDER BY
    index_owner, 
    table_name,
    index_name,
    column_position
    ;

For my use case, I wanted the column_names and order that they are in the indices (so that I could recreate them in a different database engine after migrating to AWS). The following was what I used, in case it is of use to anyone else:

SELECT
    index_name, table_name, column_name, column_position
FROM DBA_IND_COLUMNS
WHERE
    INDEX_OWNER = 'FOO'
    AND TABLE_NAME NOT LIKE '%$%'
ORDER BY
    table_name,
    index_name,
    column_position
    ;

How to add a browser tab icon (favicon) for a website?

There are a lot of complicated solutions above. For me? I used GIMP to save a copy of the original PNG file after changing the image size to 32 x 32 pixels.

Just be sure to save it as a *.ico file and use the

<link rel="shortcut icon" href="http://sstatic.net/stackoverflow/img/favicon.ico">

listed above

Passing data between controllers in Angular JS?

FYI The $scope Object has the $emit, $broadcast, $on AND The $rootScope Object has the identical $emit, $broadcast, $on

read more about publish/subscribe design pattern in angular here

Force browser to clear cache

For static resources right caching would be to use query parameters with value of each deployment or file version. This will have effect of clearing cache after each deployment.

/Content/css/Site.css?version={FileVersionNumber}

Here is ASP.NET MVC example.

<link href="@Url.Content("~/Content/Css/Reset.css")[email protected]().Assembly.GetName().Version" rel="stylesheet" type="text/css" />

Don't forget to update assembly version.

CodeIgniter: How to get Controller, Action, URL information

Update

The answer was added was in 2015 and the following methods are deprecated now

$this->router->fetch_class();  in favour of  $this->router->class; 
$this->router->fetch_method(); in favour of  $this->router->method;

Hi you should use the following approach

$this->router->fetch_class(); // class = controller
$this->router->fetch_method(); // action

for this purpose but for using this you need to extend your hook from the CI_Controller and it works like a charm, you should not use uri segments

Ruby objects and JSON serialization (without Rails)

What version of Ruby are you using? ruby -v will tell you.

If it's 1.9.2, JSON is included in the standard library.

If you're on 1.8.something then do gem install json and it'll install. Then, in your code do:

require 'rubygems'
require 'json'

Then append to_json to an object and you're good to go:

asdf = {'a' => 'b'} #=> {"a"=>"b"}
asdf.to_json #=> "{"a":"b"}"

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

How do I use the conditional operator (? :) in Ruby?

A simple example where the operator checks if player's id is 1 and sets enemy id depending on the result

player_id=1
....
player_id==1? enemy_id=2 : enemy_id=1
# => enemy=2

And I found a post about to the topic which seems pretty helpful.

How to set UITextField height?

You can use frame property of textfield to change frame Like-Textfield.frame=CGRECTMake(x axis,y axis,width,height)

Count how many files in directory PHP

Working Demo

<?php

$directory = "../images/team/harry/"; // dir location
if (glob($directory . "*.*") != false)
{
 $filecount = count(glob($directory . "*.*"));
 echo $filecount;
}
else
{
 echo 0;
}

?>

How do I make an HTML button not reload the page

You can use a form that includes a submit button. Then use jQuery to prevent the default behavior of a form:

_x000D_
_x000D_
$(document).ready(function($) {_x000D_
  $(document).on('submit', '#submit-form', function(event) {_x000D_
    event.preventDefault();_x000D_
  _x000D_
    alert('page did not reload');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<form id='submit-form'>_x000D_
  <button type='submit'>submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Convert string with commas to array

You can use javascript Spread Syntax to convert string to an array. In the solution below, I remove the comma then convert the string to an array.

var string = "0,1"
var array = [...string.replace(',', '')]
console.log(array[0])

How to get back Lost phpMyAdmin Password, XAMPP

You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"

change this line:

$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command in the Shell:

mysqladmin.exe -u root password WhateverPassword

where 'WhateverPassword' is your new password.

What are some examples of commonly used practices for naming git branches?

My personal preference is to delete the branch name after I’m done with a topic branch.

Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.

The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.

That makes the output of git branch more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.

How do I activate a specific workbook and a specific sheet?

Dim Wb As Excel.Workbook
Set Wb = Workbooks.Open(file_path)
Wb.Sheets("Sheet1").Cells(2,24).Value = 24
Wb.Close

To know the sheets name to refer in Wb.Sheets("sheetname") you can use the following :

Dim sht as Worksheet    
For Each sht In tempWB.Sheets
    Debug.Print sht.Name
Next sht

How to get input field value using PHP

Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.

For Example, change the method in your form and then echo out the value by the name of the input:

Using $_GET method:

<form name="form" action="" method="get">
  <input type="text" name="subject" id="subject" value="Car Loan">
</form>

To show the value:

<?php echo $_GET['subject']; ?>

Using $_POST method:

<form name="form" action="" method="post">
  <input type="text" name="subject" id="subject" value="Car Loan">
</form>

To show the value:

<?php echo $_POST['subject']; ?>

Exit while loop by user hitting ENTER key

I ran into this page while (no pun) looking for something else. Here is what I use:

while True:
    i = input("Enter text (or Enter to quit): ")
    if not i:
        break
    print("Your input:", i)
print("While loop has exited")

How to check if memcache or memcached is installed for PHP?

You have several options ;)

$memcache_enabled = class_exists('Memcache');
$memcache_enabled = extension_loaded('memcache');
$memcache_enabled = function_exists('memcache_connect');

How can I stop float left?

Just add overflow:hidden in the first div style. That should be enough.

When should I write the keyword 'inline' for a function/method?

Unless you are writing a library or have special reasons, you can forget about inline and use link-time optimization instead. It removes the requirement that a function definition must be in a header for it to be considered for inlining across compilation units, which is precisely what inline allows.

(But see Is there any reason why not to use link time optimization?)

Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1440
https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1080
etc...

Options are:

Code for 1440: vq=hd1440
Code for 1080: vq=hd1080
Code for 720: vq=hd720
Code for 480p: vq=large
Code for 360p: vq=medium
Code for 240p: vq=small

UPDATE
As of 10 of April 2018, this code still works.
Some users reported "not working", if it doesn't work for you, please read below:

From what I've learned, the problem is related with network speed and or screen size.
When YT player starts, it collects the network speed, screen and player sizes, among other information, if the connection is slow or the screen/player size smaller than the quality requested(vq=), a lower quality video is displayed despite the option selected on vq=.

Also make sure you read the comments below.

Call javascript from MVC controller action

For those that just used a standard form submit (non-AJAX), there's another way to fire some Javascript/JQuery code upon completion of your action.

First, create a string property on your Model.

public class MyModel 
{
    public string JavascriptToRun { get; set;}
}

Now, bind to your new model property in the Javascript of your view:

<script type="text/javascript">
     @Model.JavascriptToRun
</script>

Now, also in your view, create a Javascript function that does whatever you need to do:

<script type="text/javascript">
     @Model.JavascriptToRun

     function ShowErrorPopup() {
          alert('Sorry, we could not process your order.');
     }

</script>

Finally, in your controller action, you need to call this new Javascript function:

[HttpPost]
public ActionResult PurchaseCart(MyModel model)
{
    // Do something useful
    ...

    if (success == false)
    {
        model.JavascriptToRun= "ShowErrorPopup()";
        return View(model);
    }
    else
        return RedirectToAction("Success");
}

How do I get the path of the current executed file in Python?

this solution is robust even in executables

import inspect, os.path

filename = inspect.getframeinfo(inspect.currentframe()).filename
path     = os.path.dirname(os.path.abspath(filename))

Reactjs setState() with a dynamic key name?

this.setState({ [`${event.target.id}`]: event.target.value}, () => {
      console.log("State updated: ", JSON.stringify(this.state[event.target.id]));
    });

Please mind the quote character.

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

Being au fait with patterns as defined by (say) the GOF book, and naming objects after these gets me a long way in naming classes, organising them and communicating intent. Most people will understand this nomenclature (or at least a major part of it).

Use ffmpeg to add text subtitles

I will provide a simple and general answer that works with any number of audios and srt subtitles and respects the metadata that may include the mkv container. So it will even add the images the matroska may include as attachments (though not another types AFAIK) and convert them to tracks; you will not be able to watch but they will be there (you can demux them). Ah, and if the mkv has chapters the mp4 too.

ffmpeg -i <mkv-input> -c copy -map 0 -c:s mov_text <mp4-output>

As you can see, it's all about the -map 0, that tells FFmpeg to add all the tracks, which includes metadata, chapters, attachments, etc. If there is an unrecognized "track" (mkv allows to attach any type of file), it will end with an error.

You can create a simple batch mkv2mp4.bat, if you usually do this, to create an mp4 with the same name as the mkv. It would be better with error control, a different output name, etc., but you get the point.

@ffmpeg -i %1 -c copy -map 0 -c:s mov_text "%~n1.mp4"

Now you can simply run

mkv2mp4 "Video with subtitles etc.mkv"

And it will create "Video with subtitles etc.mp4" with the maximum of information included.

error 1265. Data truncated for column when trying to load data from txt file

I have seen the same warning when my data has extra space, tabs, newlines or other characters in my column which is decimal(10,2) to solve that, I had to remove those characters from value.

here is how I handled it.

LOAD DATA LOCAL INFILE 'c:/Users/Hitesh/Downloads/InventoryMasterReportHitesh.csv' 
INTO TABLE stores_inventory_tmp 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(@col1, @col2, @col3, @col4, @col5)
SET sku = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col1,'\t',''), '$',''), '\r', ''), '\n', ''))
, product_name = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col2,'\t',''), '$',''), '\r', ''), '\n', ''))
, department_number = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col3,'\t',''), '$',''), '\r', ''), '\n', ''))
, department_name = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col4,'\t',''), '$',''), '\r', ''), '\n', ''))
, price = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col5,'\t',''), '$',''), '\r', ''), '\n', ''))
;

I've got that hint from this answer