Programs & Examples On #Info.plist

Info.plist (information property list) is a structured text file (XML) used in Apple's developer environment and operating systems that contains essential configuration information for a bundled executable.

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

You need to paste these two in your info.plist, The only way that worked in iOS 11 for me.

    <key>NSPhotoLibraryUsageDescription</key>
    <string>This app requires access to the photo library.</string>

    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>This app requires access to the photo library.</string>

Xcode 10 Error: Multiple commands produce

In Xcode 10, it will work on previous version too

  1. Double click on project
  2. You will see image like below
  3. select TARGET from left
  4. Expand Copy Bundle Resources (0 items)
  5. Remove corresponding file which produces the error

enter image description here

Find difference between timestamps in seconds in PostgreSQL

SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;

In case if someone is having an issue using extract.

Git update submodules recursively

The way I use is:

git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master

OWIN Startup Class Missing

I tried most of the recommended fixes here, and still couldn't avoid the error message. I finally performed a combination of a few recommended solutions:

  1. Added this entry to the top of the AppSettings section of my web.config:

    <add key="owin:AutomaticAppStartup" value="false"/>

  2. Expanded the References node of my project and deleted everything that contained the string OWIN. (I felt safe doing so since my organization is not (and won't be) an active OWIN provider in the future)

I then clicked Run and my homepage loaded right up.

How to create nested directories using Mkdir in Golang?

If the issue is to create all the necessary parent directories, you could consider using os.MkDirAll()

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.

The path_test.go is a good illustration on how to use it:

func TestMkdirAll(t *testing.T) {
    tmpDir := TempDir()
    path := tmpDir + "/_TestMkdirAll_/dir/./dir2"
    err := MkdirAll(path, 0777)
    if err != nil {
    t.Fatalf("MkdirAll %q: %s", path, err)
    }
    defer RemoveAll(tmpDir + "/_TestMkdirAll_")
...
}

(Make sure to specify a sensible permission value, as mentioned in this answer)

The 'json' native gem requires installed build tools

I have found that the error is sometimes caused by a missing library.

so If you install RDOC first by running

gem install rdoc

then install rails with:

gem install rails

then go back and install the devtools as mentioned before with:

1) Extract DevKit to path C:\Ruby193\DevKit
2) cd C:\Ruby192\DevKit
3) ruby dk.rb init
4) ruby dk.rb review
5) ruby dk.rb install

then try installing json

which culminate with you finally being able to run

rails new project_name - without errors.

good luck

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

I believe python arrays just admit values. So convert it to list:

kOUT = np.zeros(N+1)
kOUT = kOUT.tolist()

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Updating a JSON object using Javascript

JSON is the JavaScript Object Notation. There is no such thing as a JSON object. JSON is just a way of representing a JavaScript object in text.

So what you're after is a way of updating a in in-memory JavaScript object. qiao's answer shows how to do that simply enough.

Why doesn't logcat show anything in my Android?

If you are using a device, the simplest check is to restart eclipse.

** you don't have to shutdown eclipse **

use File > Restart

in a quick second or two you should see your LogCat return

how to create a logfile in php?

You could use built-in function trigger_error() to trigger user errors/warnings/notices and set_error_handler() to handle them. Inside your error handler you might want to use error_log() or file_put_contents() to store all records on files. To have a single file for every day just use something like sprintf('%s.log', date('Y-m-d')) as filename. And now you should know where to start... :)

How to copy a directory structure but only include certain files (using windows batch files)

With find and cp only:

mkdir /tmp/targetdir
cd sourcedir
find . -type f -name '*.zip' -exec cp -p --parents {} /tmp/targetdir ";"
find . -type f -name '*.txt' -exec cp -p --parents {} /tmp/targetdir ";"

Find out which remote branch a local branch is tracking

git-status porcelain (machine-readable) v2 output looks like this:

$ git status -b --porcelain=v2
# branch.oid d0de00da833720abb1cefe7356493d773140b460
# branch.head the-branch-name
# branch.upstream gitlab/the-branch-name
# branch.ab +2 -2

And to get the branch upstream only:

$ git status -b --porcelain=v2 | grep -m 1 "^# branch.upstream " | cut -d " " -f 3-
gitlab/the-branch-name

If the branch has no upstream, the above command will produce an empty output (or fail with set -o pipefail).

How to install latest version of Node using Brew

if the node is not installed then

brew install node

If you have an older version of node install then remove it and install freshly that's the only suitable way.

Make sure to add the path in the environment file.

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

I also found jQuery Debugger in the chrome store. You can click on a dom item and it will show all events bound to it along with the callback function. I was debugging an application where events weren't being removed properly and this helped me track it down in minutes. Obviously this is for chrome though, not firefox.

Placeholder in IE9

HTML5 Placeholder jQuery Plugin
- by Mathias Bynens (a collaborator on HTML5 Boilerplate and jsPerf)

https://github.com/mathiasbynens/jquery-placeholder

Demo & Examples

http://mathiasbynens.be/demo/placeholder

p.s
I have used this plugin many times and it works a treat. Also it doesn't submit the placeholder text as a value when you submit your form (... a real pain I found with other plugins).

PHP Echo a large block of text

Check out heredoc. Example:

echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

echo <<<"FOOBAR"
Hello World!
FOOBAR;

The is also nowdoc but no parsing is done inside the block.

echo <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

How to find out if a Python object is a string?

Python 2

To check if an object o is a string type of a subclass of a string type:

isinstance(o, basestring)

because both str and unicode are subclasses of basestring.

To check if the type of o is exactly str:

type(o) is str

To check if o is an instance of str or any subclass of str:

isinstance(o, str)

The above also work for Unicode strings if you replace str with unicode.

However, you may not need to do explicit type checking at all. "Duck typing" may fit your needs. See http://docs.python.org/glossary.html#term-duck-typing.

See also What’s the canonical way to check for type in python?

asp.net validation to make sure textbox has integer values

simpally add this code:

<asp:FilteredTextBoxExtender ID="txtAltitudeMin_FilteredTextBoxExtender" runat="server" Enabled="True" TargetControlID="txtAltitudeMin" FilterType="Numbers"></asp:FilteredTextBoxExtender>

Difference between binary semaphore and mutex

At a theoretical level, they are no different semantically. You can implement a mutex using semaphores or vice versa (see here for an example). In practice, the implementations are different and they offer slightly different services.

The practical difference (in terms of the system services surrounding them) is that the implementation of a mutex is aimed at being a more lightweight synchronisation mechanism. In oracle-speak, mutexes are known as latches and semaphores are known as waits.

At the lowest level, they use some sort of atomic test and set mechanism. This reads the current value of a memory location, computes some sort of conditional and writes out a value at that location in a single instruction that cannot be interrupted. This means that you can acquire a mutex and test to see if anyone else had it before you.

A typical mutex implementation has a process or thread executing the test-and-set instruction and evaluating whether anything else had set the mutex. A key point here is that there is no interaction with the scheduler, so we have no idea (and don't care) who has set the lock. Then we either give up our time slice and attempt it again when the task is re-scheduled or execute a spin-lock. A spin lock is an algorithm like:

Count down from 5000:
     i. Execute the test-and-set instruction
    ii. If the mutex is clear, we have acquired it in the previous instruction 
        so we can exit the loop
   iii. When we get to zero, give up our time slice.

When we have finished executing our protected code (known as a critical section) we just set the mutex value to zero or whatever means 'clear.' If multiple tasks are attempting to acquire the mutex then the next task that happens to be scheduled after the mutex is released will get access to the resource. Typically you would use mutexes to control a synchronised resource where exclusive access is only needed for very short periods of time, normally to make an update to a shared data structure.

A semaphore is a synchronised data structure (typically using a mutex) that has a count and some system call wrappers that interact with the scheduler in a bit more depth than the mutex libraries would. Semaphores are incremented and decremented and used to block tasks until something else is ready. See Producer/Consumer Problem for a simple example of this. Semaphores are initialised to some value - a binary semaphore is just a special case where the semaphore is initialised to 1. Posting to a semaphore has the effect of waking up a waiting process.

A basic semaphore algorithm looks like:

(somewhere in the program startup)
Initialise the semaphore to its start-up value.

Acquiring a semaphore
   i. (synchronised) Attempt to decrement the semaphore value
  ii. If the value would be less than zero, put the task on the tail of the list of tasks waiting on the semaphore and give up the time slice.

Posting a semaphore
   i. (synchronised) Increment the semaphore value
  ii. If the value is greater or equal to the amount requested in the post at the front of the queue, take that task off the queue and make it runnable.  
 iii. Repeat (ii) for all tasks until the posted value is exhausted or there are no more tasks waiting.

In the case of a binary semaphore the main practical difference between the two is the nature of the system services surrounding the actual data structure.

EDIT: As evan has rightly pointed out, spinlocks will slow down a single processor machine. You would only use a spinlock on a multi-processor box because on a single processor the process holding the mutex will never reset it while another task is running. Spinlocks are only useful on multi-processor architectures.

How to bring view in front of everything?

You can use BindingAdapter like this:

@BindingAdapter("bringToFront")
public static void bringToFront(View view, Boolean flag) {
    if (flag) {
        view.bringToFront();
    }
}


  <ImageView
        ...
        app:bringToFront="@{true}"/>

How to populate HTML dropdown list with values from database

My guess is that you have a problem since you don't close your select-tag after the loop. Could that do the trick?

<select name="owner">
<?php 
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>

Loop timer in JavaScript

You should try something like this:

 function update(){
    i++;
    document.getElementById('tekst').innerHTML = i;
    setInterval(update(),1000);
    }

This means that you have to create a function in which you do the stuff you need to do, and make sure it will call itself with an interval you like. In your body onload call the function for the first time like this:

<body onload="update()">

How do I copy the contents of one stream to another?

if you want a procdure to copy a stream to other the one that nick posted is fine but it is missing the position reset, it should be

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    long TempPos = input.Position;
    while (true)    
    {
        int read = input.Read (buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write (buffer, 0, read);
    }
    input.Position = TempPos;// or you make Position = 0 to set it at the start
}

but if it is in runtime not using a procedure you shpuld use memory stream

Stream output = new MemoryStream();
byte[] buffer = new byte[32768]; // or you specify the size you want of your buffer
long TempPos = input.Position;
while (true)    
{
    int read = input.Read (buffer, 0, buffer.Length);
    if (read <= 0)
        return;
    output.Write (buffer, 0, read);
 }
    input.Position = TempPos;// or you make Position = 0 to set it at the start

ImportError: cannot import name

The problem is that you have a circular import: in app.py

from mod_login import mod_login

in mod_login.py

from app import app

This is not permitted in Python. See Circular import dependency in Python for more info. In short, the solution are

  • either gather everything in one big file
  • delay one of the import using local import

How should I make my VBA code compatible with 64-bit Windows?

I've already encountered this problem on people using my in-house tools on new 64 bit machines with Office 2010.

all I had to do was change lines of code like this:

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
    (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

To This:

#If VBA7 Then
    Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
        (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
#Else
    Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
        (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
#End If

You will, of course want to make sure that the library you're using is available on both machines, but so far nothing I've used has been a problem.

Note that in the old VB6, PtrSafe isn't even a valid command, so it'll appear in red as though you have a compile error, but it won't actually ever give an error because the compiler will skip the first part of the if block.

code Appearance

Applications using the above code compile and run perfectly on Office 2003, 2007, and 2010 32 and 64 bit.

ASP.NET MVC on IIS 7.5

For me on an Azure Server 2012 R2 IIS 8.5 VM with an Asp.Net MVC 5 app (bin deployed MVC 5) I had to do the following from an elevated cmd prompt even though I had 4.5 already installed:

dism /online /enable-feature /featurename:IIS-ASPNET45

Source: http://support.microsoft.com/kb/2736284

I also brute force installed all IIS features with the following PowerShell:

import-module servermanager
add-windowsfeature web-server -includeallsubfeature

Source: http://www.iis.net/learn/install/installing-iis-85/installing-iis-85-on-windows-server-2012-r2

Now my app is working.

How to add data via $.ajax ( serialize() + extra data ) like this

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.

Because of the adds and removes in arbitrary places on the list, I went with the LinkedList implementation.

/* traverses tree starting with given node */
  private static List<Node> traverse(Node n)
  {
    return traverse(Arrays.asList(n));
  }

  /* traverses tree starting with given nodes */
  private static List<Node> traverse(List<Node> nodes)
  {
    List<Node> open = new LinkedList<Node>(nodes);
    List<Node> visited = new LinkedList<Node>();

    ListIterator<Node> it = open.listIterator();
    while (it.hasNext() || it.hasPrevious())
    {
      Node unvisited;
      if (it.hasNext())
        unvisited = it.next();
      else
        unvisited = it.previous();

      it.remove();

      List<Node> children = getChildren(unvisited);
      for (Node child : children)
        it.add(child);

      visited.add(unvisited);
    }

    return visited;
  }

  private static List<Node> getChildren(Node n)
  {
    List<Node> children = asList(n.getChildNodes());
    Iterator<Node> it = children.iterator();
    while (it.hasNext())
      if (it.next().getNodeType() != Node.ELEMENT_NODE)
        it.remove();
    return children;
  }

  private static List<Node> asList(NodeList nodes)
  {
    List<Node> list = new ArrayList<Node>(nodes.getLength());
    for (int i = 0, l = nodes.getLength(); i < l; i++)
      list.add(nodes.item(i));
    return list;
  }

How to check whether an object has certain method/property?

It is an old question, but I just ran into it. Type.GetMethod(string name) will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case

public static bool HasMethod(this object objectToCheck, string methodName)
{
    try
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    }
    catch(AmbiguousMatchException)
    {
        // ambiguous means there is more than one result,
        // which means: a method with that name does exist
        return true;
    }
} 

How to downgrade python from 3.7 to 3.6

For those who want to add multiple Python version in their system: I easily add multiple interpreters by running the following commands:

  • sudo apt update
  • sudo apt install software-properties-common
  • sudo add-apt-repository ppa:deadsnakes/ppa
  • sudo apt install python 3.x.x
  • then while making your virtual environment choose the interpreter of your choice.

PHP Warning: Division by zero

when my divisor has 0 value

if ($divisor == 0) {
    $divisor = 1;
}

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

Eclipse has got the concept of incremental builds.This is incredibly useful as it saves a lot of time.

How is this Useful

Say you just changed a single .java file. The incremental builders will be able to compile the code without having to recompile everything(which will take more time).

Now what's the problem with Maven Plugins

Most of the maven plugins aren't designed for incremental builds and hence it creates trouble for m2e. m2e doesn't know if the plugin goal is something which is crucial or if it is irrelevant. If it just executes every plugin when a single file changes, it's gonna take lots of time.

This is the reason why m2e relies on metadata information to figure out how the execution should be handled. m2e has come up with different options to provide this metadata information and the order of preference is as below(highest to lowest)

  1. pom.xml file of the project
  2. parent, grand-parent and so on pom.xml files
  3. [m2e 1.2+] workspace preferences
  4. installed m2e extensions
  5. [m2e 1.1+] lifecycle mapping metadata provided by maven plugin
  6. default lifecycle mapping metadata shipped with m2e

1,2 refers to specifying pluginManagement section in the tag of your pom file or any of it's parents. M2E reads this configuration to configure the project.Below snippet instructs m2e to ignore the jslint and compress goals of the yuicompressor-maven-plugin

<pluginManagement>
        <plugins>
            <!--This plugin's configuration is used to store Eclipse m2e settings 
                only. It has no influence on the Maven build itself. -->
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>net.alchim31.maven</groupId>
                                    <artifactId>yuicompressor-maven-plugin</artifactId>
                                    <versionRange>[1.0,)</versionRange>
                                    <goals>
                                        <goal>compress</goal>
                                        <goal>jslint</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore />
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>

3) In case you don't prefer polluting your pom file with this metadata, you can store this in an external XML file(option 3). Below is a sample mapping file which instructs m2e to ignore the jslint and compress goals of the yuicompressor-maven-plugin

<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
    <pluginExecutions>
        <pluginExecution>
            <pluginExecutionFilter>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>yuicompressor-maven-plugin</artifactId>
                <versionRange>[1.0,)</versionRange>
                <goals>
                    <goal>compress</goal>
                    <goal>jslint</goal>
                </goals>
            </pluginExecutionFilter>
            <action>
                <ignore/>
            </action>
        </pluginExecution>
    </pluginExecutions>
</lifecycleMappingMetadata>

4) In case you don't like any of these 3 options, you can use an m2e connector(extension) for the maven plugin.The connector will in turn provide the metadata to m2e. You can see an example of the metadata information within a connector at this link . You might have noticed that the metadata refers to a configurator. This simply means that m2e will delegate the responsibility to that particular java class supplied by the extension author.The configurator can configure the project(like say add additional source folders etc) and decide whether to execute the actual maven plugin during an incremental build(if not properly managed within the configurator, it can lead to endless project builds)

Refer these links for an example of the configuratior(link1,link2). So in case the plugin is something which can be managed via an external connector then you can install it. m2e maintains a list of such connectors contributed by other developers.This is known as the discovery catalog. m2e will prompt you to install a connector if you don't already have any lifecycle mapping metadata for the execution through any of the options(1-6) and the discovery catalog has got some extension which can manage the execution.

The below image shows how m2e prompts you to install the connector for the build-helper-maven-plugin. install connector suggested from the discovery catalog.

5)m2e encourages the plugin authors to support incremental build and supply lifecycle mapping within the maven-plugin itself.This would mean that users won't have to use any additional lifecycle mappings or connectors.Some plugin authors have already implemented this

6) By default m2e holds the lifecycle mapping metadata for most of the commonly used plugins like the maven-compiler-plugin and many others.

Now back to the question :You can probably just provide an ignore life cycle mapping in 1, 2 or 3 for that specific goal which is creating trouble for you.

Reverse a string without using reversed() or [::-1]?

EDIT

Recent activity on this question caused me to look back and change my solution to a quick one-liner using a generator:

rev = ''.join([text[len(text) - count] for count in xrange(1,len(text)+1)])

Although obviously there are some better answers here like a negative step in the range or xrange function. The following is my original solution:


Here is my solution, I'll explain it step by step

def reverse(text):

    lst = []
    count = 1

    for i in range(0,len(text)):

        lst.append(text[len(text)-count])
        count += 1

    lst = ''.join(lst)
    return lst

print reverse('hello')

First, we have to pass a parameter to the function, in this case text.

Next, I set an empty list, named lst to use later. (I actually didn't know I'd need the list until I got to the for loop, you'll see why it's necessary in a second.)

The count variable will make sense once I get into the for loop

So let's take a look at a basic version of what we are trying to accomplish:

It makes sense that appending the last character to the list would start the reverse order. For example:

>>lst = []
>>word = 'foo'
>>lst.append(word[2])
>>print lst
['o']

But in order to continue reversing the order, we need to then append word[1] and then word[0]:

>>lst.append(word[2])
>>lst.append(word[1])
>>lst.append(word[0])
>>print lst
['o','o','f']

This is great, we now have a list that has our original word in reverse order and it can be converted back into a string by using .join(). But there's a problem. This works for the word foo, it even works for any word that has a length of 3 characters. But what about a word with 5 characters? Or 10 characters? Now it won't work. What if there was a way we could dynamically change the index we append so that any word will be returned in reverse order?

Enter for loop.

for i in range(0,len(text)):

    lst.append(text[len(text)-count])
    count += 1

First off, it is necessary to use in range() rather than just in, because we need to iterate through the characters in the word, but we also need to pull the index value of the word so that we change the order.

The first part of the body of our for loop should look familiar. Its very similar to

>>lst.append(word[..index..])

In fact, the base concept of it is exactly the same:

>>lst.append(text[..index..])

So what's all the stuff in the middle doing?

Well, we need to first append the index of the last letter to our list, which is the length of the word, text, -1. From now on we'll refer to it as l(t) -1

>>lst.append(text[len(text)-1])

That alone will always get the last letter of our word, and append it to lst, regardless of the length of the word. But now that we have the last letter, which is l(t) - 1, we need the second to last letter, which is l(t) - 2, and so on, until there are no more characters to append to the list. Remember our count variable from above? That will come in handy. By using a for loop, we can increment the value of count by 1 through each iteration, so that the value we subtract by increases, until the for loop has iterated through the entire word:

>>for i in range(0,len(text)):
..        
..      lst.append(text[len(text)-count])
..      count += 1

Now that we have the heart of our function, let's look at what we have so far:

def reverse(text):

    lst = []
    count = 1

    for i in range(0,len(text)):

        lst.append(text[len(text)-count])
        count += 1

We're almost done! Right now, if we were to call our function with the word 'hello', we would get a list that looks like:

['o','l','l','e','h']

We don't want a list, we want a string. We can use .join for that:

def reverse(text):

    lst = []
    count = 1

    for i in range(0,len(text)):

        lst.append(text[len(text)-count])
        count += 1

    lst = ''.join(lst) # join the letters together without a space
    return lst

And that's it. If we call the word 'hello' on reverse(), we'd get this:

>>print reverse('hello')
olleh

Obviously, this is way more code than is necessary in a real life situation. Using the reversed function or extended slice would be the optimal way to accomplish this task, but maybe there is some instance when it would not work, and you would need this. Either way, I figured I'd share it for anyone who would be interested.

If you guys have any other ideas, I'd love to hear them!

How to use su command over adb shell?

The su command does not execute anything, it just raise your privileges.

Try adb shell su -c YOUR_COMMAND.

Delete files older than 3 months old in a directory using .NET

Here's a 1-liner lambda:

Directory.GetFiles(dirName)
         .Select(f => new FileInfo(f))
         .Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
         .ToList()
         .ForEach(f => f.Delete());

How to clear the canvas for redrawing

Use: context.clearRect(0, 0, canvas.width, canvas.height);

This is the fastest and most descriptive way to clear the entire canvas.

Do not use: canvas.width = canvas.width;

Resetting canvas.width resets all canvas state (e.g. transformations, lineWidth, strokeStyle, etc.), it is very slow (compared to clearRect), it doesn't work in all browsers, and it doesn't describe what you are actually trying to do.

Dealing with transformed coordinates

If you have modified the transformation matrix (e.g. using scale, rotate, or translate) then context.clearRect(0,0,canvas.width,canvas.height) will likely not clear the entire visible portion of the canvas.

The solution? Reset the transformation matrix prior to clearing the canvas:

// Store the current transformation matrix
context.save();

// Use the identity matrix while clearing the canvas
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);

// Restore the transform
context.restore();

Edit: I've just done some profiling and (in Chrome) it is about 10% faster to clear a 300x150 (default size) canvas without resetting the transform. As the size of your canvas increases this difference drops.

That is already relatively insignificant, but in most cases you will be drawing considerably more than you are clearing and I believe this performance difference be irrelevant.

100000 iterations averaged 10 times:
1885ms to clear
2112ms to reset and clear

Javascript format date / time

Yes, you can use the native javascript Date() object and its methods.

For instance you can create a function like:

function formatDate(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + "  " + strTime;
}

var d = new Date();
var e = formatDate(d);

alert(e);

And display also the am / pm and the correct time.

Remember to use getFullYear() method and not getYear() because it has been deprecated.

DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/

Insert a line at specific line number with sed or awk

sed -i "" -e $'4 a\\n''Project_Name=sowstest' start

  • This line works fine in macOS

How do I open a new window using jQuery?

This works:

myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

How to generate .json file with PHP?

Here i have mentioned the simple syntex for create json file and print the array value inside the json file in pretty manner.

$array = array('name' => $name,'id' => $id,'url' => $url);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($array, JSON_PRETTY_PRINT));   // here it will print the array pretty
fclose($fp);

Hope it will works for you....

How to read a file without newlines?

I think this is the best option.

temp = [line.strip() for line in file.readlines()]

How to pass macro definition from "make" command line arguments (-D) to C source code?

Because of low reputation, I cannot comment the accepted answer.

I would like to mention the predefined variable CPPFLAGS. It might represent a better fit than CFLAGS or CXXFLAGS, since it is described by the GNU Make manual as:

Extra flags to give to the C preprocessor and programs that use it (the C and Fortran compilers).

Examples of built-in implicit rules that use CPPFLAGS

  • n.o is made automatically from n.c with a recipe of the form:
    • $(CC) $(CPPFLAGS) $(CFLAGS) -c
  • n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form:
    • $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c

One would use the command make CPPFLAGS=-Dvar=123 to define the desired macro.

More info

How to make borders collapse (on a div)?

You need to use display: table-row instead of float: left; to your column and obviously as @Hushme correct your diaplay: table-cell to display: table-cell;

 .container {
    display: table;
    border-collapse: collapse;
}
.column {
    display: table-row;
    overflow: hidden;
    width: 120px;
}
.cell {
    display: table-cell;
    border: 1px solid red;
    width: 120px;
    height: 20px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

demo

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

These answers were very helpful. Thank you.

My contribution below adds an array where multiple days can return false (we're closed every Tuesday, Wednesday and Thursday). And I bundled the specific dates plus years and the no-weekends functions.

If you want weekends off, add [Saturday], [Sunday] to the closedDays array.

$(document).ready(function(){

    $("#datepicker").datepicker({
        beforeShowDay: nonWorkingDates,
        numberOfMonths: 1,
        minDate: '05/01/09',
        maxDate: '+2M',
        firstDay: 1
    });

    function nonWorkingDates(date){
        var day = date.getDay(), Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6;
        var closedDates = [[7, 29, 2009], [8, 25, 2010]];
        var closedDays = [[Monday], [Tuesday]];
        for (var i = 0; i < closedDays.length; i++) {
            if (day == closedDays[i][0]) {
                return [false];
            }

        }

        for (i = 0; i < closedDates.length; i++) {
            if (date.getMonth() == closedDates[i][0] - 1 &&
            date.getDate() == closedDates[i][1] &&
            date.getFullYear() == closedDates[i][2]) {
                return [false];
            }
        }

        return [true];
    }




});

How to create a popup windows in javafx

Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.

Iterating over and deleting from Hashtable in Java

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if key is null or equals 0.
  if (entry.getKey() == null || entry.getKey() == 0) {
    it.remove();
  }
}

how to set the background image fit to browser using html

Found an easier way to set it. Here's the html and css:

<style>
    #body {
        *background: url(../Images/abcd.jpg) no-repeat center center fixed; /* For IE 6 and 7 */
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }
</style>

<body id="body">
    <nav class="navbar navbar-default" id="navColour">
        <div class="container-fluid">
            <div class="navbar-header">
                <a id="clr" class="navbar-brand" href="#">Summer Haze Festival</a>
            </div>
            <div>
                <ul class="nav navbar-nav" >
                    <li id="clr" class="active"><a href="#">Home</a></li>
                    <li id="clr"><a href="#">Page 1</a></li>
                    <li id="clr"><a href="#">Page 2</a></li>
                    <li id="clr"><a href="#">Page 3</a></li>
                </ul>
            </div>
        </div>
    </nav>
</body>

url(../Images/abcd.jpg) being the image stored in your solution in a folder called Images. Hope it helps. Note: I used the id "body" because the navigation bar was somehow overriding my background image.

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

git checkout master
git merge origin/master --allow-unrelated-histories

Resolve conflict, then

git add -A .
git commit -m "Upload"
git push

How do I get a background location update every n minutes in my iOS application?

Unfortunately, all of your assumptions seem correct, and I don't think there's a way to do this. In order to save battery life, the iPhone's location services are based on movement. If the phone sits in one spot, it's invisible to location services.

The CLLocationManager will only call locationManager:didUpdateToLocation:fromLocation: when the phone receives a location update, which only happens if one of the three location services (cell tower, gps, wifi) perceives a change.

A few other things that might help inform further solutions:

  • Starting & Stopping the services causes the didUpdateToLocation delegate method to be called, but the newLocation might have an old timestamp.

  • Region Monitoring might help

  • When running in the background, be aware that it may be difficult to get "full" LocationServices support approved by Apple. From what I've seen, they've specifically designed startMonitoringSignificantLocationChanges as a low power alternative for apps that need background location support, and strongly encourage developers to use this unless the app absolutely needs it.

Good Luck!

UPDATE: These thoughts may be out of date by now. Looks as though people are having success with @wjans answer, above.

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

document.getelementbyId will return null if element is not defined?

console.log(document.getElementById('xx') ) evaluates to null.

document.getElementById('xx') !=null evaluates to false

You should use document.getElementById('xx') !== null as it is a stronger equality check.

Validate that text field is numeric usiung jQuery

All basic validation by using a class:

$('.IsInteger,.IsDecimal').focus(function (e) {
    if (this.value == "0") {
        this.value = "";
    }
});
$('.IsInteger,.IsDecimal').blur(function (e) {
    if (this.value == "") {
        this.value = "0";
    }
});

$('.IsInteger').keypress(function (e) {
    var charCode = (e.which) ? e.which : e.keyCode;
    if (charCode > 31
    && (charCode < 48 || charCode > 57))
        return false;
});
$('.IsDecimal').keypress(function (e) {
    var charCode = (e.which) ? e.which : e.keyCode;
    if (this.value.indexOf(".") > 0) {
        if (charCode == 46) {
            return false;
        }
    }
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
});
$('.IsSpecialChar').keypress(function (e) {
    if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40)
        return false;
    else
        return true;
});
$('.IsMaxLength').keypress(function (e) {
    var length = $(this).attr("maxlength");
    return (this.value.length <= length);
});

$('.IsPhoneNumber').keyup(function (e) {
    var numbers = this.value.replace(/\D/g, ''),
    char = { 0: '(', 3: ') ', 6: ' - ' };
    this.value = '';
    for (var i = 0; i < numbers.length; i++) {
        this.value += (char[i] || '') + numbers[i];
    }
});
$('.IsEmail').blur(function (e) {
    var flag = false;
    var email = this.value;
    if (email.length > 0) {
        var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        flag = regex.test(email);
    }
    if (!flag)
        this.value = "";
});

Example:

<asp:TextBox 
    runat="server" 
    ID="txtDeliveryFee" 
    TextMode="SingleLine" 
    CssClass="form-control IsInteger" 
    MaxLength="3" 
    Text="0"
></asp:TextBox>

Just put the class name in the input.

Step-by-step debugging with IPython

Looks like the approach in @gaborous's answer is deprecated.

The new approach seems to be:

from IPython.core import debugger
debug = debugger.Pdb().set_trace

def buggy_method():
    debug()

How to list branches that contain a given commit?

From the git-branch manual page:

 git branch --contains <commit>

Only list branches which contain the specified commit (HEAD if not specified). Implies --list.


 git branch -r --contains <commit>

Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".


As noted by Carl Walsh, this applies only to the default refspec

fetch = +refs/heads/*:refs/remotes/origin/*

If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:

git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>

See also this git ready article.

The --contains tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.

$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date:   Wed Apr 1 20:38:59 2009 -0400

    Green all around, finally.

$ git branch --contains d590f2
  tests
* master

Note: if the commit is on a remote tracking branch, add the -a option.
(as MichielB comments below)

git branch -a --contains <commit>

MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry:

Because git cherry compares the changeset rather than the commit id (sha1), you can use git cherry to find out if a commit you made locally has been applied <upstream> under a different commit id.
For example, this will happen if you’re feeding patches <upstream> via email rather than pushing or pulling commits directly.

           __*__*__*__*__> <upstream>
          /
fork-point
          \__+__+__-__+__+__-__+__> <head>

(Here, the commits marked '-' wouldn't show up with git cherry, meaning they are already present in <upstream>.)

How to send a "multipart/form-data" with requests in python?

Since the previous answers were written, requests have changed. Have a look at the bug thread at Github for more detail and this comment for an example.

In short, the files parameter takes a dict with the key being the name of the form field and the value being either a string or a 2, 3 or 4-length tuple, as described in the section POST a Multipart-Encoded File in the requests quickstart:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

In the above, the tuple is composed as follows:

(filename, data, content_type, headers)

If the value is just a string, the filename will be the same as the key, as in the following:

>>> files = {'obvius_session_id': '72c2b6f406cdabd578c5fd7598557c52'}

Content-Disposition: form-data; name="obvius_session_id"; filename="obvius_session_id"
Content-Type: application/octet-stream

72c2b6f406cdabd578c5fd7598557c52

If the value is a tuple and the first entry is None the filename property will not be included:

>>> files = {'obvius_session_id': (None, '72c2b6f406cdabd578c5fd7598557c52')}

Content-Disposition: form-data; name="obvius_session_id"
Content-Type: application/octet-stream

72c2b6f406cdabd578c5fd7598557c52

How to parse a CSV file in Bash?

You need to use IFS instead of -d:

while IFS=, read -r col1 col2
do
    echo "I got:$col1|$col2"
done < myfile.csv

Note that for general purpose CSV parsing you should use a specialized tool which can handle quoted fields with internal commas, among other issues that Bash can't handle by itself. Examples of such tools are cvstool and csvkit.

What is an AssertionError? In which case should I throw it from my own code?

The meaning of an AssertionError is that something happened that the developer thought was impossible to happen.

So if an AssertionError is ever thrown, it is a clear sign of a programming error.

How to install Selenium WebDriver on Mac OS

First up you need to download Selenium jar files from http://www.seleniumhq.org/download/. Then you'd need an IDE, something like IntelliJ or Eclipse. Then you'll have to map your jar files to those IDEs. Then depending on which language/framework you choose, you'll have to download the relevant library files, for example, if you're using JUnit you'll have to download Junit 4.11 jar file. Finally don't forget to download the drivers for Chrome and Safari (firefox driver comes standard with selenium). Once done, you can start coding and testing your code with the browser of your choice.

How to add /usr/local/bin in $PATH on Mac

export PATH=$PATH:/usr/local/git/bin:/usr/local/bin

One note: you don't need quotation marks here because it's on the right hand side of an assignment, but in general, and especially on Macs with their tradition of spacy pathnames, expansions like $PATH should be double-quoted as "$PATH".

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Better and quicker approach without any software to download.

  • Open command prompt and follow steps mentioned below
  • cd path/from/where/file/istobe/copied
  • ftp (serverip or name)
  • It will ask for Server(AIX) User: (username)
  • It will ask for password : (password)
  • cd path/where/file/istobe/copied
  • pwd (to check current path)
  • mput (directory name which is to be copied)

This should work.

Remove all constraints affecting a UIView

This is the way to disable all constraints from a specific view

 NSLayoutConstraint.deactivate(myView.constraints)

Apply CSS rules to a nested class inside a div

If you need to target multiple classes use:

#main_text .title, #main_text .title2 {
  /* Properties */
}

Cannot make a static reference to the non-static method

Since getText() is non-static you cannot call it from a static method.

To understand why, you have to understand the difference between the two.

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

SomeClass myObject = new SomeClass();

To call an instance method, you call it on the instance (myObject):

myObject.getText(...)

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

... = SomeClass.final

And the two cannot work together as they operate on different data spaces (instance data and class data)

Let me try and explain. Consider this class (psuedocode):

class Test {
     string somedata = "99";
     string getText() { return somedata; } 
     static string TTT = "0";
}

Now I have the following use case:

Test item1 = new Test();
 item1.somedata = "200";

 Test item2 = new Test();

 Test.TTT = "1";

What are the values?

Well

in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99

In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say

class Test {
         string somedata = "99";
         string getText() { return somedata; } 
  static string TTT = getText(); // error there is is no somedata at this point 
}

So the question is why is TTT static or why is getText() not static?

Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Importing packages in Java

For the second class file, add "package Dan;" like the first one, so as to make sure they are in the same package; modify "import Dan.Vik.disp;" to be "import Dan.Vik;"

http post - how to send Authorization header?

If you are like me, and starring at your angular/ionic typescript, which looks like..

  getPdf(endpoint: string): Observable<Blob> {
    let url = this.url + '/' + endpoint;
    let token = this.msal.accessToken;
    console.log(token);
    return this.http.post<Blob>(url, {
      headers: new HttpHeaders(
        {
          'Access-Control-Allow-Origin': 'https://localhost:5100',
          'Access-Control-Allow-Methods': 'POST',
          'Content-Type': 'application/pdf',
          'Authorization': 'Bearer ' + token,
          'Accept': '*/*',
        }),
        //responseType: ResponseContentType.Blob,
      });
  }

And while you are setting options but can't seem to figure why they aren't anywhere..

Well.. if you were like me and started this post from a copy/paste of a get, then...

Change to:

  getPdf(endpoint: string): Observable<Blob> {
    let url = this.url + '/' + endpoint;
    let token = this.msal.accessToken;
    console.log(token);
    return this.http.post<Blob>(url, null, { //  <-----  notice the null  *****
      headers: new HttpHeaders(
        {
          'Authorization': 'Bearer ' + token,
          'Accept': '*/*',
        }),
        //responseType: ResponseContentType.Blob,
      });
  }

How to disable an input box using angular.js

I created a directive for this (angular stable 1.0.8)

<input type="text" input-disabled="editableInput" />
<button ng-click="editableInput = !editableInput">enable/disable</button>

app.controller("myController", function(){
  $scope.editableInput = false;
});

app.directive("inputDisabled", function(){
  return function(scope, element, attrs){
    scope.$watch(attrs.inputDisabled, function(val){
      if(val)
        element.removeAttr("disabled");
      else
        element.attr("disabled", "disabled");
    });
  }
});

Which version of C# am I using

While this isn't answering your question directly, I'm putting this here as google brought this page up first in my searches when I was looking for this info.

If you're using Visual Studio, you can right click on your project -> Properties -> Build -> Advanced This should list available versions as well as the one your proj is using.

enter image description here

Create a Path from String in Java7

You can just use the Paths class:

Path path = Paths.get(textPath);

... assuming you want to use the default file system, of course.

How to sort an array of ints using a custom comparator?

Here is some code (it's actually not Timsort as I originally thought, but it does work well) that does the trick without any boxing/unboxing. In my tests, it works 3-4 times faster than using Collections.sort with a List wrapper around the array.

// This code has been contributed by 29AjayKumar 
// from: https://www.geeksforgeeks.org/sort/

static final int sortIntArrayWithComparator_RUN = 32; 

// this function sorts array from left index to  
// to right index which is of size atmost RUN  
static void sortIntArrayWithComparator_insertionSort(int[] arr, IntComparator comparator, int left, int right) { 
    for (int i = left + 1; i <= right; i++)  
    { 
        int temp = arr[i]; 
        int j = i - 1; 
        while (j >= left && comparator.compare(arr[j], temp) > 0)
        { 
            arr[j + 1] = arr[j]; 
            j--; 
        } 
        arr[j + 1] = temp; 
    } 
} 

// merge function merges the sorted runs  
static void sortIntArrayWithComparator_merge(int[] arr, IntComparator comparator, int l, int m, int r) { 
    // original array is broken in two parts  
    // left and right array  
    int len1 = m - l + 1, len2 = r - m; 
    int[] left = new int[len1]; 
    int[] right = new int[len2]; 
    for (int x = 0; x < len1; x++)  
    { 
        left[x] = arr[l + x]; 
    } 
    for (int x = 0; x < len2; x++)  
    { 
        right[x] = arr[m + 1 + x]; 
    } 

    int i = 0; 
    int j = 0; 
    int k = l; 

    // after comparing, we merge those two array  
    // in larger sub array  
    while (i < len1 && j < len2)  
    { 
        if (comparator.compare(left[i], right[j]) <= 0)
        { 
            arr[k] = left[i]; 
            i++; 
        } 
        else 
        { 
            arr[k] = right[j]; 
            j++; 
        } 
        k++; 
    } 

    // copy remaining elements of left, if any  
    while (i < len1) 
    { 
        arr[k] = left[i]; 
        k++; 
        i++; 
    } 

    // copy remaining element of right, if any  
    while (j < len2)  
    { 
        arr[k] = right[j]; 
        k++; 
        j++; 
    } 
} 

// iterative sort function to sort the  
// array[0...n-1] (similar to merge sort)  
static void sortIntArrayWithComparator(int[] arr, IntComparator comparator) { sortIntArrayWithComparator(arr, lIntArray(arr), comparator); }
static void sortIntArrayWithComparator(int[] arr, int n, IntComparator comparator) { 
    // Sort individual subarrays of size RUN  
    for (int i = 0; i < n; i += sortIntArrayWithComparator_RUN)  
    { 
        sortIntArrayWithComparator_insertionSort(arr, comparator, i, Math.min((i + 31), (n - 1))); 
    } 

    // start merging from size RUN (or 32). It will merge  
    // to form size 64, then 128, 256 and so on ....  
    for (int size = sortIntArrayWithComparator_RUN; size < n; size = 2 * size)  
    { 
          
        // pick starting point of left sub array. We  
        // are going to merge arr[left..left+size-1]  
        // and arr[left+size, left+2*size-1]  
        // After every merge, we increase left by 2*size  
        for (int left = 0; left < n; left += 2 * size)  
        { 
              
            // find ending point of left sub array  
            // mid+1 is starting point of right sub array  
            int mid = Math.min(left + size - 1, n - 1);
            int right = Math.min(left + 2 * size - 1, n - 1); 

            // merge sub array arr[left.....mid] &  
            // arr[mid+1....right]  
            sortIntArrayWithComparator_merge(arr, comparator, left, mid, right); 
        } 
    } 
}

static int lIntArray(int[] a) {
  return a == null ? 0 : a.length;
}

static interface IntComparator {
  int compare(int a, int b);
}

How do I parse a YAML file in Ruby?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in some.yml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

gives me

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

JavaScript for handling Tab Key press

try this

 <body>
   <div class="linkCollection">
             <a tabindex=1 href="www.demo1.com">link</a>    
             <a tabindex=2 href="www.demo2.com">link</a>    
             <a tabindex=3 href="www.demo3.com">link</a>    
             <a tabindex=4 href="www.demo4.com">link</a>    
             <a tabindex=5 href="www.demo5.com">link</a>    
             <a tabindex=6 href="www.demo6.com">link</a>    
             <a tabindex=7 href="www.demo7.com">link</a>    
             <a tabindex=8 href="www.demo8.com">link</a>    
             <a tabindex=9 href="www.demo9.com">link</a>    
             <a tabindex=10 href="www.demo10.com">link</a>   
        </div>

</body>

<script>
$(document).ready(function(){
  $(".linkCollection a").focus(function(){
    var href=$(this).attr('href');
    console.log(href);
    // href variable holds the active selected link.
  });
});
</script>

don't forgot to add jQuery library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

Pandas DataFrame to List of Dictionaries

Use df.to_dict('records') -- gives the output without having to transpose externally.

In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

How do I move focus to next input with jQuery?

You can do something like this:

$("input").change(function() {
  var inputs = $(this).closest('form').find(':input');
  inputs.eq( inputs.index(this)+ 1 ).focus();
});

The other answers posted here may not work for you since they depend on the next input being the very next sibling element, which often isn't the case. This approach goes up to the form and searches for the next input type element.

How do you pass a function as a parameter in C?

You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.

Get path from open file in Python

And if you just want to get the directory name and no need for the filename coming with it, then you can do that in the following conventional way using os Python module.

>>> import os
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> os.path.dirname(f.name)
>>> '/Users/Desktop/'

This way you can get hold of the directory structure.

What is the default text size on Android?

Default values in appcompat-v7

<dimen name="abc_text_size_body_1_material">14sp</dimen>
<dimen name="abc_text_size_body_2_material">14sp</dimen>
<dimen name="abc_text_size_button_material">14sp</dimen>
<dimen name="abc_text_size_caption_material">12sp</dimen>
<dimen name="abc_text_size_display_1_material">34sp</dimen>
<dimen name="abc_text_size_display_2_material">45sp</dimen>
<dimen name="abc_text_size_display_3_material">56sp</dimen>
<dimen name="abc_text_size_display_4_material">112sp</dimen>
<dimen name="abc_text_size_headline_material">24sp</dimen>
<dimen name="abc_text_size_large_material">22sp</dimen>
<dimen name="abc_text_size_medium_material">18sp</dimen>
<dimen name="abc_text_size_menu_material">16sp</dimen>
<dimen name="abc_text_size_small_material">14sp</dimen>
<dimen name="abc_text_size_subhead_material">16sp</dimen>
<dimen name="abc_text_size_subtitle_material_toolbar">16dp</dimen>
<dimen name="abc_text_size_title_material">20sp</dimen>
<dimen name="abc_text_size_title_material_toolbar">20dp</dimen>

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

Yes , Jared and Kelly Orr are right. I use the following code like in edit exception.

foreach (var issue in dinner.GetRuleViolations())
{
    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}

in stead of

ModelState.AddRuleViolations(dinner.GetRuleViolations());

How to make a rest post call from ReactJS code?

As of 2018 and beyond, you have a more modern option which is to incorporate async/await in your ReactJS application. A promise-based HTTP client library such as axios can be used. The sample code is given below:

import axios from 'axios';
...
class Login extends Component {
    constructor(props, context) {
        super(props, context);
        this.onLogin = this.onLogin.bind(this);
        ...
    }
    async onLogin() {
        const { email, password } = this.state;
        try {
           const response = await axios.post('/login', { email, password });
           console.log(response);
        } catch (err) {
           ...
        }
    }
    ...
}

EC2 Instance Cloning

There is no explicit Clone button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.

First create an image from an existing EC2 instance.

enter image description here


Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.

enter image description here


Then, you need to create a new instance and use that image as the AMI.

enter image description here

enter image description here

Get program path in VB.NET?

You can also use:

Dim strPath As String = AppDomain.CurrentDomain.BaseDirectory

How do I make a textbox that only accepts numbers?

Just use a NumericUpDown control and set those ugly up down buttons visibility to false.

numericUpDown1.Controls[0].Visible = false;

NumericUpDown is actually a collection of controls containing a 'spin box' (up down buttons), a text box and some code to validate and wange-jangle it all together.

Marking:

YourNumericUpDown.Controls[0].visible = false 

will hide the buttons while keeping the underlying code active.

While not being an obvious solution it is simple and effective. .Controls[1] would hide the text box portion if you wanted to do that instead.

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

This one is good example for Swift 4 about async:

DispatchQueue.global(qos: .background).async {
    // Background Thread
    DispatchQueue.main.async {
        // Run UI Updates or call completion block
    }
}

PHPExcel auto size column width

For Spreedsheet + PHP 7, you must write instead of PHPExcel_Cell::columnIndexFromString, \PhpOffice\PhpSpreadsheet\Cell::columnIndexFromString. And at the loop is a mistake, there you must < not work with <=. Otherwise, he takes a column too much into the loop.

Given an array of numbers, return array of products of all other numbers (no division)

int[] b = new int[] { 1, 2, 3, 4, 5 };            
int j;
for(int i=0;i<b.Length;i++)
{
  int prod = 1;
  int s = b[i];
  for(j=i;j<b.Length-1;j++)
  {
    prod = prod * b[j + 1];
  }
int pos = i;    
while(pos!=-1)
{
  pos--;
  if(pos!=-1)
     prod = prod * b[pos];                    
}
Console.WriteLine("\n Output is {0}",prod);
}

XPath to select Element by attribute value

As a follow on, you could select "all nodes with a particular attribute" like this:

//*[@id='4']

How to use ConcurrentLinkedQueue?

The ConcurentLinkedQueue is a very efficient wait/lock free implementation (see the javadoc for reference), so not only you don't need to synchronize, but the queue will not lock anything, thus being virtually as fast as a non synchronized (not thread safe) one.

I have never set any passwords to my keystore and alias, so how are they created?

Keystore name: "debug.keystore"

Keystore password: "android"

Key alias: "androiddebugkey"

Key password: "android"

I use this information and successfully generate Signed APK.

Android REST client, Sample?

We have open-sourced our lightweight async REST client library for Android, you might find it useful if you have minimal requirements and don't want to handle the multithreading yourself - it is very OK for basic communications but not a full-blown REST client library.

It's called libRESTfulClient and can be found on GitHub.

Getting raw SQL query string from PDO prepared statements

You can use sprintf(str_replace('?', '"%s"', $sql), ...$params);

Here is an example:

function mysqli_prepared_query($link, $sql, $types='', $params=array()) {
    echo sprintf(str_replace('?', '"%s"', $sql), ...$params);
    //prepare, bind, execute
}

$link = new mysqli($server, $dbusername, $dbpassword, $database);
$sql = "SELECT firstname, lastname FROM users WHERE userage >= ? AND favecolor = ?";
$types = "is"; //integer and string
$params = array(20, "Brown");

if(!$qry = mysqli_prepared_query($link, $sql, $types, $params)){
    echo "Failed";
} else {
    echo "Success";
}

Note this only works for PHP >= 5.6

What's the correct way to convert bytes to a hex string in Python 3?

New in python 3.8, you can pass a delimiter argument to the hex function, as in this example

>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'

https://docs.python.org/3/library/stdtypes.html#bytes.hex

How do I create a local database inside of Microsoft SQL Server 2014?

Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link

Youtube video about entire process.
Writeup with pictures about installing SQL Server

How to select a local server:

When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:

1) Make sure you have Server Type: Database

2) Make sure you have Authentication: Windows Authentication (no username & password)

3) For the server name field look to the right and select the drop down arrow, click 'browse for more'

4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14

How do I create a local database inside of Microsoft SQL Server 2014?

1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)

2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

What is the difference between sed and awk?

Both tools are meant to work with text and there are tasks both tools can be used for.

For me the rule to separate them is: Use sed to automate tasks you would do otherwise in a text editor manually. That's why it is called stream editor. (You can use the same commands to edit text in vim). Use awk if you want to analyze text, meaning counting fields, calculate totals, extract and reorganize structures etc.

Also you should not forget about grep. Use grep if you only want to search/extract something in a text (file)

Django: OperationalError No Such Table

I'm using Django CMS 3.4 with Django 1.8. I stepped through the root cause in the Django CMS code. Root cause is the Django CMS is not changing directory to the directory with file containing the SQLite3 database before making database calls. The error message is spurious. The underlying problem is that a SQLite database call is made in the wrong directory.

The workaround is to ensure all your Django applications change directory back to the Django Project root directory when changing to working directories.

Start script missing error when running npm start

This error also happens if you added a second "script" key in the package.json file. If you just leave one "script" key in the package.json the error disappears.

How to strip comma in Python string

Use replace method of strings not strip:

s = s.replace(',','')

An example:

>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo  bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True

How to get current relative directory of your Makefile?

One line in the Makefile should be enough:

DIR := $(notdir $(CURDIR))

Pandas: change data type of Series to String

You can use:

df.loc[:,'id'] = df.loc[:, 'id'].astype(str)

This is why they recommend this solution: Pandas doc

TD;LR

To reflect some of the answers:

df['id'] = df['id'].astype("string")

This will break on the given example because it will try to convert to StringArray which can not handle any number in the 'string'.

df['id']= df['id'].astype(str)

For me this solution throw some warning:

> SettingWithCopyWarning:  
> A value is trying to be set on a copy of a
> slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

There is official fix from microsoft: http://support.microsoft.com/kb/980368

I strongly do NOT recommend to use < modules runAllManagedModulesForAllRequests="true">. This leads all requests (even .jpg, .css, .pdf, etc) will be processed by all registered HTTP modules. There are two negative moments: a) additional load on hardware resources; b) potential errors, as http modules will process new type of content.

How do I access (read, write) Google Sheets spreadsheets with Python?

Take a look at gspread port for api v4 - pygsheets. It should be very easy to use rather than the google client.

Sample example

import pygsheets

gc = pygsheets.authorize()

# Open spreadsheet and then workseet
sh = gc.open('my new ssheet')
wks = sh.sheet1

# Update a cell with value (just to let him know values is updated ;) )
wks.update_cell('A1', "Hey yank this numpy array")

# update the sheet with array
wks.update_cells('A2', my_nparray.to_list())

# share the sheet with your friend
sh.share("[email protected]")

See the docs here.

Author here.

How to check size of a file using Bash?

[ -n file.txt ] doesn't check its size, it checks that the string file.txt is non-zero length, so it will always succeed.

If you want to say "size is non-zero", you need [ -s file.txt ].

To get a file's size, you can use wc -c to get the size (file length) in bytes:

file=file.txt
minimumsize=90000
actualsize=$(wc -c <"$file")
if [ $actualsize -ge $minimumsize ]; then
    echo size is over $minimumsize bytes
else
    echo size is under $minimumsize bytes
fi

In this case, it sounds like that's what you want.

But FYI, if you want to know how much disk space the file is using, you could use du -k to get the size (disk space used) in kilobytes:

file=file.txt
minimumsize=90
actualsize=$(du -k "$file" | cut -f 1)
if [ $actualsize -ge $minimumsize ]; then
    echo size is over $minimumsize kilobytes
else
    echo size is under $minimumsize kilobytes
fi

If you need more control over the output format, you can also look at stat. On Linux, you'd start with something like stat -c '%s' file.txt, and on BSD/Mac OS X, something like stat -f '%z' file.txt.

Changing Fonts Size in Matlab Plots

It's possible to change default fonts, both for the axes and for other text, by adding the following lines to the startup.m file.

% Change default axes fonts.
set(0,'DefaultAxesFontName', 'Times New Roman')
set(0,'DefaultAxesFontSize', 14)

% Change default text fonts.
set(0,'DefaultTextFontname', 'Times New Roman')
set(0,'DefaultTextFontSize', 14)

If you don't know if you have a startup.m file, run

which startup

to find its location. If Matlab says there isn't one, run

userpath

to know where it should be placed.

How to handle button clicks using the XML onClick within Fragments

I'd like to add to Adjorn Linkz's answer.

If you need multiple handlers, you could just use lambda references

void onViewCreated(View view, Bundle savedInstanceState)
{
    view.setOnClickListener(this::handler);
}
void handler(View v)
{
    ...
}

The trick here is that handler method's signature matches View.OnClickListener.onClick signature. This way, you won't need the View.OnClickListener interface.

Also, you won't need any switch statements.

Sadly, this method is only limited to interfaces that require a single method, or a lambda.

Is there a way I can retrieve sa password in sql server 2005

Wait!

There is a way to retrieve the password by using Brute-Force attack, have a look at the following tool from codeproject Retrieve SQL Server Password


How to use the tool to retrieve the password

To Retrieve the password of SQL Server user,run the following query in SQL Query Analyzer

"Select Password from SysxLogins Where Name = 'XXXX'" Where XXXX is the user

name for which you want to retrieve password.Copy the password field (Hashed Code) and

paste here (in Hashed code Field) and click on start button to retrieve

I checked the tool on SQLServer 2000 and it's working fine.

Detect if the app was launched/opened from a push notification

See This code :

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground  )
    {
         //opened from a push notification when the app was on background
    }
}

same as

-(void)application:(UIApplication *)application didReceiveLocalNotification (UILocalNotification *)notification

How to recover corrupted Eclipse workspace?

When workspace is damaged and Eclipse cannot start, even using the -clean option, removing single file workspace/.metadata/.plugins/org.eclipse.core.resources/.snap may help (source: comments to article https://web.archive.org/web/20200517003712/https://letsgetdugg.com/2009/04/19/recovering-a-corrupt-eclipse-workspace/).

Update: when Eclipse 4.X cannot start after crash, try to start with -clearPersistedState option; if it didn't help then remove file workspace/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi (sources: https://www.eclipse.org/forums/index.php/m/1269045/ https://www.eclipse.org/forums/index.php/t/522428/ https://bugs.eclipse.org/bugs/show_bug.cgi?id=404873). Note: you'll lose configuration of your perspective/views/tabs.

Update: Subversive plugin may be responsible for inability to start Eclipse with corrupted metadata. If you have Subversive plugin installed, update it to latest build (at least 0.7.9.I20120210-1700) from update-site. Related bugs 372621 and 370374 were fixed by Subversive developers.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I want to add a few details on top of this very excellent post by Radim.

I took this solution and worked on it for a bit and quickly ran into some limitations. I'll just outline those and then give the solution to that as well.

  • First of all I was unable to render dynamic-detail inside a dynamic-detail (basically nest dynamic UIs inside each other).
  • The next issue was that I wanted to render a dynamic-detail inside one of the parts that was made available in the solution. That was not possible with the initial solution either.
  • Lastly it was not possible to use template URLs on the dynamic parts like string-editor.

I made another question based on this post, on how to achieve these limitations, which can be found here:

recursive dynamic template compilation in angular2

I’ll just outline the answers to these limitations, should you run into the same issue as I, as that make the solution quite more flexible. It would be awesome to have the initial plunker updated with that as well.

To enable nesting dynamic-detail inside each other, You'll need to add DynamicModule.forRoot() in the import statement in the type.builder.ts

protected createComponentModule (componentType: any) {
    @NgModule({
    imports: [
        PartsModule, 
        DynamicModule.forRoot() //this line here
    ],
    declarations: [
        componentType
    ],
    })
    class RuntimeComponentModule
    {
    }
    // a module for just this Type
    return RuntimeComponentModule;
}

Besides that it was not possible to use <dynamic-detail> inside one of the parts being string-editor or text-editor.

To enable that you'll need to change parts.module.ts and dynamic.module.ts

Inside parts.module.ts You'll need to add DynamicDetail in the DYNAMIC_DIRECTIVES

export const DYNAMIC_DIRECTIVES = [
   forwardRef(() => StringEditor),
   forwardRef(() => TextEditor),
   DynamicDetail
];

Also in the dynamic.module.ts you'd have to remove the dynamicDetail as they are now part of the parts

@NgModule({
   imports:      [ PartsModule ],
   exports:      [ PartsModule],
})

A working modified plunker can be found here: http://plnkr.co/edit/UYnQHF?p=preview (I didn’t solve this issue, I’m just the messenger :-D)

Finally it was not possible to use templateurls in the parts created on the dynamic components. A solution (or workaround. I’m not sure whether it’s an angular bug or wrong use of the framework) was to create a compiler in the constructor instead of injecting it.

    private _compiler;

    constructor(protected compiler: RuntimeCompiler) {
        const compilerFactory : CompilerFactory =
        platformBrowserDynamic().injector.get(CompilerFactory);
        this._compiler = compilerFactory.createCompiler([]);
    }

Then use the _compiler to compile, then templateUrls are enabled as well.

return new Promise((resolve) => {
        this._compiler
            .compileModuleAndAllComponentsAsync(module)
            .then((moduleWithFactories) =>
            {
                let _ = window["_"];
                factory = _.find(moduleWithFactories.componentFactories, { componentType: type });

                this._cacheOfFactories[template] = factory;

                resolve(factory);
            });
    });

Hope this helps someone else!

Best regards Morten

XML serialization in Java?

if you want a structured solution (like ORM) then JAXB2 is a good solution.

If you want a serialization like DOT NET then you could use Long Term Persistence of JavaBeans Components

The choice depends on use of serialization.

Regex to check with starts with http://, https:// or ftp://

You need a whole input match here.

System.out.println(test.matches("^(http|https|ftp)://.*$")); 

Edit:(Based on @davidchambers's comment)

System.out.println(test.matches("^(https?|ftp)://.*$")); 

Export a list into a CSV or TXT file in R

I think the most straightforward way to do this is using capture.output, thus;

capture.output(summary(mylist), file = "My New File.txt")

Easy!

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

I have just faced the same problem. First, you need to install the appropriate Oracle client for your OS. In my case, to install it on Ubuntu x64 I have followed this instructions https://help.ubuntu.com/community/Oracle%20Instant%20Client#Install_RPMs

Then, you need to install cx_Oracle, a Python module to connect to the Oracle client. Again, assuming you are running Ubuntu in a 64bit machine, you should type in a shell:

wget -c http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm
sudo alien -i cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm

This will work for Oracle 11g if you have installed Python 2.7.x, but you can download a different cx_Oracle version in http://cx-oracle.sourceforge.net/ To check which Python version do you have, type in a terminal:

python -V

I hope it helps

Tomcat base URL redirection

What i did:

I added the following line inside of ROOT/index.jsp

 <meta http-equiv="refresh" content="0;url=/somethingelse/index.jsp"/>

How to edit Docker container files from the host?

If you think your volume is a "network drive", it will be easier. To edit the file located in this drive, you just need to turn on another machine and connect to this network drive, then edit the file like normal.

How to do that purely with docker (without FTP/SSH ...)?

  1. Run a container that has an editor (VI, Emacs). Search Docker hub for "alpine vim"

Example:

docker run -d --name shared_vim_editor \
 -v <your_volume>:/home/developer/workspace \
jare/vim-bundle:latest
  1. Run the interactive command:

docker exec -it -u root shared_vim_editor /bin/bash

Hope this helps.

How can I debug my JavaScript code?

All modern browsers come with some form of a built-in JavaScript debugging application. The details of these will be covered on the relevant technologies web pages. My personal preference for debugging JavaScript is Firebug in Firefox. I'm not saying Firebug is better than any other; it depends on your personal preference and you should probably test your site in all browsers anyway (my personal first choice is always Firebug).

I'll cover some of the high-level solutions below, using Firebug as an example:

Firefox

Firefox comes with with its own inbuilt JavaScript debugging tool, but I would recommend you install the Firebug add on. This provides several additional features based on the basic version that are handy. I'm going to only talk about Firebug here.

Once Firebug is installed you can access it like below:

Firstly if you right click on any element you can Inspect Element with Firebug:

Inspect Element in Firebug

Clicking this will open up the Firebug pane at the bottom of the browser:

Firebug pane

Firebug provides several features but the one we're interested in is the script tab. Clicking the script tab opens this window:

Script tab

Obviously, to debug you need to click reload:

JavaScript in the sctipt tab

You can now add breakpoints by clicking the line to the left of the piece of JavaScript code you want to add the breakpoint to:

Adding breakpoints

When your breakpoint is hit, it will look like below:

A breakpoint being hit

You can also add watch variables and generally do everything that you would expect in a modern debugging tool.

Watch varibables

For more information on the various options offered in Firebug, check out the Firebug FAQ.

Chrome

Chrome also has its own in built JavaScript debugging option, which works in a very similar way, right click, inspect element, etc.. Have a look at Chrome Developer Tools. I generally find the stack traces in Chrome better than Firebug.

Internet Explorer

If you're developing in .NET and using Visual Studio using the web development environment you can debug JavaScript code directly by placing breakpoints, etc. Your JavaScript code looks exactly the same as if you were debugging your C# or VB.NET code.

If you don't have this, Internet Explorer also provides all of the tools shown above. Annoyingly, instead of having the right click inspect element features of Chrome or Firefox, you access the developer tools by pressing F12. This question covers most of the points.

Django development IDE

There is an actual Python extension for Visual Studio: http://pytools.codeplex.com/. It's absolutely fantastic. It feels the same as if I were coding in any native Visual Studio language. The extension is even compatabile with Django. And best of all: it's totally free. Even for Visual Studio, it only requires the Visual Studio Shell to work, which is completely free.

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

Try browse the WCF in IIS see if it's alive and works normally,

In my case it's because the physical path of the WCF is misdirected.

How do I compile the asm generated by GCC?

You can embed the assembly code in a normal C program. Here's a good introduction. Using the appropriate syntax, you can also tell GCC you want to interact with variables declared in C. The program below instructs gcc that:

  • eax shall be foo
  • ebx shall be bar
  • the value in eax shall be stored in foo after the assembly code executed

\n

int main(void)
{
        int foo = 10, bar = 15;
        __asm__ __volatile__("addl  %%ebx,%%eax"
                             :"=a"(foo)
                             :"a"(foo), "b"(bar)
                             );
        printf("foo+bar=%d\n", foo);
        return 0;
}

Removing Conda environment

My environment name is: test

conda remove -n test --all

Can't push to remote branch, cannot be resolved to branch

I just had this issue as well and my normal branches start with pb-3.1-12345/namebranch but I accidental capitalized the first 2 letters PB-3.1/12345/namebranch. After renaming the branch to use lower case letters I could create the branch.

How can I copy the output of a command directly into my clipboard?

Linux & Windows (WSL)

When using the Windows Subsystem for Linux (e.g. Ubuntu/Debian on WSL) the xclip solution won't work. Instead you need to use clip.exe and powershell.exe to copy into and paste from the Windows clipboard.

.bashrc

This solution works on "real" Linux-based systems (i.e. Ubuntu, Debian) as well as on WSL systems. Just put the following code into your .bashrc:

if grep -q -i microsoft /proc/version; then
    # on WSL
    alias copy="clip.exe"
    alias paste="powershell.exe Get-Clipboard"
else
    # on "normal" linux
    alias copy="xclip -sel clip"
    alias paste="xclip -sel clip -o"
fi

How it works

The file /proc/version contains information about the currently running OS. When the system is running in WSL mode, then this file additionally contains the string Microsoft which is checked by grep.

Usage

To copy:

cat file | copy

And to paste:

paste > new_file

Add up a column of numbers at the Unix shell

Here goes

cat files.txt | xargs ls -l | cut -c 23-30 | 
  awk '{total = total + $1}END{print total}'

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Eloquent: find() and where() usage laravel

To add to craig_h's comment above (I currently don't have enough rep to add this as a comment to his answer, sorry), if your primary key is not an integer, you'll also want to tell your model what data type it is, by setting keyType at the top of the model definition.

public $keyType = 'string'

Eloquent understands any of the types defined in the castAttribute() function, which as of Laravel 5.4 are: int, float, string, bool, object, array, collection, date and timestamp.

This will ensure that your primary key is correctly cast into the equivalent PHP data type.

Count elements with jQuery

The best way would be to use .each()

var num = 0;

$('.className').each(function(){
    num++;
});

Passing arguments to require (when loading module)

Based on your comments in this answer, I do what you're trying to do like this:

module.exports = function (app, db) {
    var module = {};

    module.auth = function (req, res) {
        // This will be available 'outside'.
        // Authy stuff that can be used outside...
    };

    // Other stuff...
    module.pickle = function(cucumber, herbs, vinegar) {
        // This will be available 'outside'.
        // Pickling stuff...
    };

    function jarThemPickles(pickle, jar) {
        // This will be NOT available 'outside'.
        // Pickling stuff...

        return pickleJar;
    };

    return module;
};

I structure pretty much all my modules like that. Seems to work well for me.

jQuery ajax request being block because Cross-Origin

I solved this by changing the file path in the browser:

  • Instead of: c/XAMPP/htdocs/myfile.html
  • I wrote: localhost/myfile.html

Google access token expiration time

Since there is no accepted answer I will try to answer this one:

[s] - seconds

how to add value to a tuple?

In Python, you can't. Tuples are immutable.

On the containing list, you could replace tuple ('1', '2', '3', '4') with a different ('1', '2', '3', '4', '1234') tuple though.

anchor jumping by using javascript

Not enough rep for a comment.

The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).

Something to bare in mind if you don't have control of the document markup (e.g. webextension).

The location based method in the selected answer can also be simplified with location.replace:

function jump(hash) { location.replace("#" + hash) }

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

In Visual Studio Express 2013 for web it's hidden away in View > Other Windows > Toolbox.

Communicating between a fragment and an activity - best practices

There are severals ways to communicate between activities, fragments, services etc. The obvious one is to communicate using interfaces. However, it is not a productive way to communicate. You have to implement the listeners etc.

My suggestion is to use an event bus. Event bus is a publish/subscribe pattern implementation.

You can subscribe to events in your activity and then you can post that events in your fragments etc.

Here on my blog post you can find more detail about this pattern and also an example project to show the usage.

File inside jar is not visible for spring

I was having an issue recursively loading resources in my Spring app, and found that the issue was I should be using resource.getInputStream. Here's an example showing how to recursively read in all files in config/myfiles that are json files.

Example.java

private String myFilesResourceUrl = "config/myfiles/**/";
private String myFilesResourceExtension = "json";

ResourceLoader rl = new ResourceLoader();

// Recursively get resources that match. 
// Big note: If you decide to iterate over these, 
// use resource.GetResourceAsStream to load the contents
// or use the `readFileResource` of the ResourceLoader class.
Resource[] resources = rl.getResourcesInResourceFolder(myFilesResourceUrl, myFilesResourceExtension);

// Recursively get resource and their contents that match. 
// This loads all the files into memory, so maybe use the same approach 
// as this method, if need be.
Map<Resource,String> contents = rl.getResourceContentsInResourceFolder(myFilesResourceUrl, myFilesResourceExtension);

ResourceLoader.java

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StreamUtils;

public class ResourceLoader {
  public Resource[] getResourcesInResourceFolder(String folder, String extension) {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
      String resourceUrl = folder + "/*." + extension;
      Resource[] resources = resolver.getResources(resourceUrl);
      return resources;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public String readResource(Resource resource) throws IOException {
    try (InputStream stream = resource.getInputStream()) {
      return StreamUtils.copyToString(stream, Charset.defaultCharset());
    }
  }

  public Map<Resource, String> getResourceContentsInResourceFolder(
      String folder, String extension) {
    Resource[] resources = getResourcesInResourceFolder(folder, extension);

    HashMap<Resource, String> result = new HashMap<>();
    for (var resource : resources) {
      try {
        String contents = readResource(resource);
        result.put(resource, contents);
      } catch (IOException e) {
        throw new RuntimeException("Could not load resource=" + resource + ", e=" + e);
      }
    }
    return result;
  }
}

Codeigniter : calling a method of one controller from other

You can use the redirect URL to controller:

Class Ctrlr1 extends CI_Controller{
public void my_fct1(){
redirect('Ctrlr2 /my_fct2', 'refresh');
}
}


Class Ctrlr2 extends CI_Controller{
public void my_fct2(){
$this->load->view('view1');
}
}

Python: Select subset from list based on index set

I see 2 options.

  1. Using numpy:

    property_a = numpy.array([545., 656., 5.4, 33.])
    property_b = numpy.array([ 1.2,  1.3, 2.3, 0.3])
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = property_a[good_objects]
    property_bsel = property_b[good_indices]
    
  2. Using a list comprehension and zip it:

    property_a = [545., 656., 5.4, 33.]
    property_b = [ 1.2,  1.3, 2.3, 0.3]
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = [x for x, y in zip(property_a, good_objects) if y]
    property_bsel = [property_b[i] for i in good_indices]
    

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

I've just fixed this for my machine. Maybe it will work for some. Maybe not for others, but here is what worked for me.

In IIS, I had to add bindings for https to the default website (or, I suppose, the website you are running the app under).

enter image description here

Now my localhost works when debugging from Visual Studio.

Regex not operator

No, there's no direct not operator. At least not the way you hope for.

You can use a zero-width negative lookahead, however:

\((?!2001)[0-9a-zA-z _\.\-:]*\)

The (?!...) part means "only match if the text following (hence: lookahead) this doesn't (hence: negative) match this. But it doesn't actually consume the characters it matches (hence: zero-width).

There are actually 4 combinations of lookarounds with 2 axes:

  • lookbehind / lookahead : specifies if the characters before or after the point are considered
  • positive / negative : specifies if the characters must match or must not match.

How to display request headers with command line curl

You get a nice header output with the following command:

 curl -L -v -s -o /dev/null google.de
  • -L, --location follow redirects
  • -v, --verbose more output, indicates the direction
  • -s, --silent don't show a progress bar
  • -o, --output /dev/null don't show received body

Or the shorter version:

 curl -Lvso /dev/null google.de

Results in:

* Rebuilt URL to: google.de/
*   Trying 2a00:1450:4008:802::2003...
* Connected to google.de (2a00:1450:4008:802::2003) port 80 (#0)
> GET / HTTP/1.1
> Host: google.de
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Location: http://www.google.de/
< Content-Type: text/html; charset=UTF-8
< Date: Fri, 12 Aug 2016 15:45:36 GMT
< Expires: Sun, 11 Sep 2016 15:45:36 GMT
< Cache-Control: public, max-age=2592000
< Server: gws
< Content-Length: 218
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
<
* Ignoring the response-body
{ [218 bytes data]
* Connection #0 to host google.de left intact
* Issue another request to this URL: 'http://www.google.de/'
*   Trying 2a00:1450:4008:800::2003...
* Connected to www.google.de (2a00:1450:4008:800::2003) port 80 (#1)
> GET / HTTP/1.1
> Host: www.google.de
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 12 Aug 2016 15:45:36 GMT
< Expires: -1
< Cache-Control: private, max-age=0
< Content-Type: text/html; charset=ISO-8859-1
< P3P: CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."
< Server: gws
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< Set-Cookie: NID=84=Z0WT_INFoDbf_0FIe_uHqzL9mf3DMSQs0mHyTEDAQOGY2sOrQaKVgN2domEw8frXvo4I3x3QVLqCH340HME3t1-6gNu8R-ArecuaneSURXNxSXYMhW2kBIE8Duty-_w7; expires=Sat, 11-Feb-2017 15:45:36 GMT; path=/; domain=.google.de; HttpOnly
< Accept-Ranges: none
< Vary: Accept-Encoding
< Transfer-Encoding: chunked
<
{ [11080 bytes data]
* Connection #1 to host www.google.de left intact

As you can see curl outputs both the outgoing and the incoming headers and skips the bodydata althought telling you how big the body is.

Additionally for every line the direction is indicated so that it is easy to read. I found it particular useful to trace down long chains of redirects.

How to resize a custom view programmatically?

Here's a more generic version of the solution above from @herbertD :

private void resizeView(View view, int newWidth, int newHeight) { 
    try { 
        Constructor<? extends LayoutParams> ctor = view.getLayoutParams().getClass().getDeclaredConstructor(int.class, int.class); 
        view.setLayoutParams(ctor.newInstance(newWidth, newHeight));   
    } catch (Exception e) { 
        e.printStackTrace(); 
    }
}

RegEx: Grabbing values between quotation marks

This version

  • accounts for escaped quotes
  • controls backtracking

    /(["'])((?:(?!\1)[^\\]|(?:\\\\)*\\[^\\])*)\1/
    

How to apply a CSS class on hover to dynamically generated submit buttons?

The most efficient selector you can use is an attribute selector.

 input[name="btnPage"]:hover {/*your css here*/}

Here's a live demo: http://tinkerbin.com/3G6B93Cb

Timer function to provide time in nano seconds using C++

You can use the following function with gcc running under x86 processors:

unsigned long long rdtsc()
{
  #define rdtsc(low, high) \
         __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))

  unsigned int low, high;
  rdtsc(low, high);
  return ((ulonglong)high << 32) | low;
}

with Digital Mars C++:

unsigned long long rdtsc()
{
   _asm
   {
        rdtsc
   }
}

which reads the high performance timer on the chip. I use this when doing profiling.

How to import the class within the same directory or sub directory?

You can import the module and have access through its name if you don't want to mix functions and classes with yours

import util # imports util.py

util.clean()
util.setup(4)

or you can import the functions and classes to your code

from util import clean, setup
clean()
setup(4)

you can use wildchar * to import everything in that module to your code

from util import *
clean()
setup(4)

Text in HTML Field to disappear when clicked?

This is as simple I think the solution that should solve all your problems:

<input name="myvalue" id="valueText" type="text" value="ENTER VALUE">

This is your submit button:

<input type="submit" id= "submitBtn" value="Submit">

then put this small jQuery in a js file:

//this will submit only if the value is not default
$("#submitBtn").click(function () {
    if ($("#valueText").val() === "ENTER VALUE")
    {
        alert("please insert a valid value");
        return false;
    }
});

//this will put default value if the field is empty
$("#valueText").blur(function () {
    if(this.value == ''){ 
        this.value = 'ENTER VALUE';
    }
}); 

 //this will empty the field is the value is the default one
 $("#valueText").focus(function () {
    if (this.value == 'ENTER VALUE') {
        this.value = ''; 
    }
});

And it works also in older browsers. Plus it can easily be converted to normal javascript if you need.

Error renaming a column in MySQL

Lone Ranger is very close... in fact, you also need to specify the datatype of the renamed column. For example:

ALTER TABLE `xyz` CHANGE `manufacurerid` `manufacturerid` INT;

Remember :

  • Replace INT with whatever your column data type is (REQUIRED)
  • Tilde/ Backtick (`) is optional

Embed Youtube video inside an Android app

The video quality depends upon the Connection speed using API

alternatively for other than API means without YouTube app you can follow this link

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

always use 'r' to get a raw string when you want to avoid escape.

test_file=open(r'c:\Python27\test.txt','r')

Rounding a number to the nearest 5 or 10 or X

In VB, math.round has additional arguments to specify number of decimal places and rounding method. Math.Round(10.665, 2, MidpointRounding.AwayFromZero) will return 10.67 . If the number is a decimal or single data type, math.round returns a decimal data type. If it is double, it returns double data type. That might be important if option strict is on.

The result of (10.665).ToString("n2") rounds away from zero to give "10.67". without additional arguments math.round returns 10.66, which could lead to unwanted discrepancies.

Java Compare Two Lists

Simple solution :-

    List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "d", "c"));
    List<String> list2 = new ArrayList<String>(Arrays.asList("b", "f", "c"));

    list.retainAll(list2);
    list2.removeAll(list);
    System.out.println("similiar " + list);
    System.out.println("different " + list2);

Output :-

similiar [b, c]
different [f]

How do I change the background color of a plot made with ggplot2

To change the panel's background color, use the following code:

myplot + theme(panel.background = element_rect(fill = 'green', colour = 'red'))

To change the color of the plot (but not the color of the panel), you can do:

myplot + theme(plot.background = element_rect(fill = 'green', colour = 'red'))

See here for more theme details Quick reference sheet for legends, axes and themes.

How to sort a HashMap in Java

Without any more information, it's hard to know exactly what you want. However, when choosing what data structure to use, you need to take into account what you need it for. Hashmaps are not designed for sorting - they are designed for easy retrieval. So in your case, you'd probably have to extract each element from the hashmap, and put them into a data structure more conducive to sorting, such as a heap or a set, and then sort them there.

Combine two tables that have no common fields

To get a meaningful/useful view of the two tables, you normally need to determine an identifying field from each table that can then be used in the ON clause in a JOIN.

THen in your view:

SELECT T1.*, T2.* FROM T1 JOIN T2 ON T1.IDFIELD1 = T2.IDFIELD2

You mention no fields are "common", but although the identifying fields may not have the same name or even be the same data type, you could use the convert / cast functions to join them in some way.

How to install Cmake C compiler and CXX compiler

Try to install gcc and gcc-c++, as Cmake works smooth with them.

RedHat-based

yum install gcc gcc-c++

Debian/Ubuntu-based

apt-get install cmake gcc g++

Then,

  1. remove 'CMakeCache.txt'
  2. run compilation again.

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

What is the Sign Off feature in Git for?

There are some nice answers on this question. I’ll try to add a more broad answer, namely about what these kinds of lines/headers/trailers are about in current practice. Not so much about the sign-off header in particular (it’s not the only one).

Headers or trailers (?1) like “sign-off” (?2) is, in current practice in projects like Git and Linux, effectively structured metadata for the commit. These are all appended to the end of the commit message, after the “free form” (unstructured) part of the body of the message. These are token–value (or key–value) pairs typically delimited by a colon and a space (:?).

Like I mentioned, “sign-off” is not the only trailer in current practice. See for example this commit, which has to do with “Dirty Cow”:

 mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
 This is an ancient bug that was actually attempted to be fixed once
 (badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
 get_user_pages() race for write access") but that was then undone due to
 problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").

 In the meantime, the s390 situation has long been fixed, and we can now
 fix it by checking the pte_dirty() bit properly (and do it better).  The
 s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
 software dirty bits") which made it into v3.9.  Earlier kernels will
 have to look at the page state itself.

 Also, the VM has become more scalable, and what used a purely
 theoretical race back then has become easier to trigger.

 To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
 we already did a COW" rather than play racy games with FOLL_WRITE that
 is very fundamental, and then use the pte dirty flag to validate that
 the FOLL_COW flag is still valid.

 Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
 Acked-by: Hugh Dickins <[email protected]>
 Reviewed-by: Michal Hocko <[email protected]>
 Cc: Andy Lutomirski <[email protected]>
 Cc: Kees Cook <[email protected]>
 Cc: Oleg Nesterov <[email protected]>
 Cc: Willy Tarreau <[email protected]>
 Cc: Nick Piggin <[email protected]>
 Cc: Greg Thelen <[email protected]>
 Cc: [email protected]
 Signed-off-by: Linus Torvalds <[email protected]>

In addition to the “sign-off” trailer in the above, there is:

  • “Cc” (was notified about the patch)
  • “Acked-by” (acknowledged by the owner of the code, “looks good to me”)
  • “Reviewed-by” (reviewed)
  • “Reported-and-tested-by” (reported and tested the issue (I assume))

Other projects, like for example Gerrit, have their own headers and associated meaning for them.

See: https://git.wiki.kernel.org/index.php/CommitMessageConventions

Moral of the story

It is my impression that, although the initial motivation for this particular metadata was some legal issues (judging by the other answers), the practice of such metadata has progressed beyond just dealing with the case of forming a chain of authorship.

[?1]: man git-interpret-trailers
[?2]: These are also sometimes called “s-o-b” (initials), it seems.

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

There is a whole new approach that you may want to consider if what you're after is the power and performance of stored procedures, and the rapid development that tools like Entity Framework provide.

I've taken SQL+ for a test drive on a small project, and it is really something special. You basically add what amounts to comments to your SQL routines, and those comments provide instructions to a code generator, which then builds a really nice object oriented class library based on the actual SQL routine. Kind of like entity framework in reverse.

Input parameters become part of an input object, output parameters and result sets become part of an output object, and a service component provides the method calls.

If you want to use stored procedures, but still want rapid development, you might want to have a look at this stuff.

multiple axis in matplotlib with different scales

Since Steve Tjoa's answer always pops up first and mostly lonely when I search for multiple y-axes at Google, I decided to add a slightly modified version of his answer. This is the approach from this matplotlib example.

Reasons:

  • His modules sometimes fail for me in unknown circumstances and cryptic intern errors.
  • I don't like to load exotic modules I don't know (mpl_toolkits.axisartist, mpl_toolkits.axes_grid1).
  • The code below contains more explicit commands of problems people often stumble over (like single legend for multiple axes, using viridis, ...) rather than implicit behavior.

Plot

import matplotlib.pyplot as plt 

# Create figure and subplot manually
# fig = plt.figure()
# host = fig.add_subplot(111)

# More versatile wrapper
fig, host = plt.subplots(figsize=(8,5)) # (width, height) in inches
# (see https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html)
    
par1 = host.twinx()
par2 = host.twinx()
    
host.set_xlim(0, 2)
host.set_ylim(0, 2)
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
    
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

color1 = plt.cm.viridis(0)
color2 = plt.cm.viridis(0.5)
color3 = plt.cm.viridis(.9)

p1, = host.plot([0, 1, 2], [0, 1, 2],    color=color1, label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2],    color=color2, label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], color=color3, label="Velocity")

lns = [p1, p2, p3]
host.legend(handles=lns, loc='best')

# right, left, top, bottom
par2.spines['right'].set_position(('outward', 60))

# no x-ticks                 
par2.xaxis.set_ticks([])

# Sometimes handy, same for xaxis
#par2.yaxis.set_ticks_position('right')

# Move "Velocity"-axis to the left
# par2.spines['left'].set_position(('outward', 60))
# par2.spines['left'].set_visible(True)
# par2.yaxis.set_label_position('left')
# par2.yaxis.set_ticks_position('left')

host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())

# Adjust spacings w.r.t. figsize
fig.tight_layout()
# Alternatively: bbox_inches='tight' within the plt.savefig function 
#                (overwrites figsize)

# Best for professional typesetting, e.g. LaTeX
plt.savefig("pyplot_multiple_y-axis.pdf")
# For raster graphics use the dpi argument. E.g. '[...].png", dpi=200)'

jQuery AJAX Call to PHP Script with JSON Return

I recommend you use:

var returnedData = JSON.parse(data);

to convert the JSON string (if it is just text) to a JavaScript object.

Disabled href tag

In my case, I use

<a href="/" onClick={e => e.preventDefault()}>

Root user/sudo equivalent in Cygwin?

Based on @mat-khor's answer, I took the syswin su.exe, saved it as manufacture-syswin-su.exe, and wrote this wrapper script. It handles redirection of the command's stdout and stderr, so it can be used in a pipe, etc. Also, the script exits with the status of the given command.

Limitations:

  • The syswin-su options are currently hardcoded to use the current user. Prepending env USERNAME=... to the script invocation overrides it. If other options were needed, the script would have to distinguish between syswin-su and command arguments, e.g. splitting at the first --.
  • If the UAC prompt is cancelled or declined, the script hangs.

.

#!/bin/bash
set -e

# join command $@ into a single string with quoting (required for syswin-su)
cmd=$( ( set -x; set -- "$@"; ) 2>&1 | perl -nle 'print $1 if /\bset -- (.*)/' )

tmpDir=$(mktemp -t -d -- "$(basename "$0")_$(date '+%Y%m%dT%H%M%S')_XXX")
mkfifo -- "$tmpDir/out"
mkfifo -- "$tmpDir/err"

cat >> "$tmpDir/script" <<-SCRIPT
    #!/bin/env bash
    $cmd > '$tmpDir/out' 2> '$tmpDir/err'
    echo \$? > '$tmpDir/status'
SCRIPT

chmod 700 -- "$tmpDir/script"

manufacture-syswin-su -s bash -u "$USERNAME" -m -c "cygstart --showminimized bash -c '$tmpDir/script'" > /dev/null &
cat -- "$tmpDir/err" >&2 &
cat -- "$tmpDir/out"
wait $!
exit $(<"$tmpDir/status")

How can you strip non-ASCII characters from a string? (in C#)

I use this regular expression to filter out bad characters in a filename.

Regex.Replace(directory, "[^a-zA-Z0-9\\:_\- ]", "")

That should be all the characters allowed for filenames.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

In perl, for an input of 1 (A), 27 (AA), etc.

sub excel_colname {
  my ($idx) = @_;       # one-based column number
  --$idx;               # zero-based column index
  my $name = "";
  while ($idx >= 0) {
    $name .= chr(ord("A") + ($idx % 26));
    $idx   = int($idx / 26) - 1;
  }
  return scalar reverse $name;
}

How to copy a file from one directory to another using PHP?

Hi guys wanted to also add on how to copy using a dynamic copying and pasting.

let say we don't know the actual folder the user will create but we know in that folder we need files to be copied to, to activate some function like delete, update, views etc.

you can use something like this... I used this code in one of the complex project which I am currently busy on. i just build it myself because all answers i got on the internet was giving me an error.

    $dirPath1 = "users/$uniqueID"; #creating main folder and where $uniqueID will be called by a database when a user login.
    $result = mkdir($dirPath1, 0755);
            $dirPath2 = "users/$uniqueID/profile"; #sub folder
            $result = mkdir($dirPath2, 0755);
                $dirPath3 = "users/$uniqueID/images"; #sub folder 
                $result = mkdir($dirPath3, 0755);
                    $dirPath4 = "users/$uniqueID/uploads";#sub folder
                    $result = mkdir($dirPath4, 0755);
                    @copy('blank/dashboard.php', 'users/'.$uniqueID.'/dashboard.php');#from blank folder to dynamic user created folder
                    @copy('blank/views.php', 'users/'.$uniqueID.'/views.php'); #from blank folder to dynamic user created folder
                    @copy('blank/upload.php', 'users/'.$uniqueID.'/upload.php'); #from blank folder to dynamic user created folder
                    @copy('blank/delete.php', 'users/'.$uniqueID.'/delete.php'); #from blank folder to dynamic user created folder

I think facebook or twitter uses something like this to build every new user dashboard dynamic....

Why is my Git Submodule HEAD detached from master?

Adding a branch option in .gitmodule is NOT related to the detached behavior of submodules at all. The old answer from @mkungla is incorrect, or obsolete.

From git submodule --help, HEAD detached is the default behavior of git submodule update --remote.

First, there's no need to specify a branch to be tracked. origin/master is the default branch to be tracked.

--remote

Instead of using the superproject's recorded SHA-1 to update the submodule, use the status of the submodule's remote-tracking branch. The remote used is branch's remote (branch.<name>.remote), defaulting to origin. The remote branch used defaults to master.

Why

So why is HEAD detached after update? This is caused by the default module update behavior: checkout.

--checkout

Checkout the commit recorded in the superproject on a detached HEAD in the submodule. This is the default behavior, the main use of this option is to override submodule.$name.update when set to a value other than checkout.

To explain this weird update behavior, we need to understand how do submodules work?

Quote from Starting with Submodules in book Pro Git

Although sbmodule DbConnector is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository.

The main repo tracks the submodule with its state at a specific point, the commit id. So when you update modules, you're updating the commit id to a new one.

How

If you want the submodule merged with remote branch automatically, use --merge or --rebase.

--merge

This option is only valid for the update command. Merge the commit recorded in the superproject into the current branch of the submodule. If this option is given, the submodule's HEAD will not be detached.

--rebase

Rebase the current branch onto the commit recorded in the superproject. If this option is given, the submodule's HEAD will not be detached.

All you need to do is,

git submodule update --remote --merge
# or
git submodule update --remote --rebase

Recommended alias:

git config alias.supdate 'submodule update --remote --merge'

# do submodule update with
git supdate

There's also an option to make --merge or --rebase as the default behavior of git submodule update, by setting submodule.$name.update to merge or rebase.

Here's an example about how to config the default update behavior of submodule update in .gitmodule.

[submodule "bash/plugins/dircolors-solarized"]
    path = bash/plugins/dircolors-solarized
    url = https://github.com/seebi/dircolors-solarized.git
    update = merge # <-- this is what you need to add

Or configure it in command line,

# replace $name with a real submodule name
git config -f .gitmodules submodule.$name.update merge

References

Setting the classpath in java using Eclipse IDE

Just had the same issue, for those having the same one it may be that you put the library on the modulepath rather than the classpath while adding it to your project

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

What are file descriptors, explained in simple terms?

In simple words, when you open a file, the operating system creates an entry to represent that file and store the information about that opened file. So if there are 100 files opened in your OS then there will be 100 entries in OS (somewhere in kernel). These entries are represented by integers like (...100, 101, 102....). This entry number is the file descriptor. So it is just an integer number that uniquely represents an opened file in operating system. If your process opens 10 files then your Process table will have 10 entries for file descriptors.

Similarly when you open a network socket, it is also represented by an integer and it is called Socket Descriptor. I hope you understand.

What is the difference between UTF-8 and Unicode?

They are the same thing, aren't they?

No, they aren't.


I think the first sentence of the Wikipedia page you referenced gives a nice, brief summary:

UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.

To elaborate:

  • Unicode is a standard, which defines a map from characters to numbers, the so-called code points, (like in the example below). For the full mapping, you can have a look here.

    ! -> U+0021 (21),  
    " -> U+0022 (22),  
    \# -> U+0023 (23)
    
  • UTF-8 is one of the ways to encode these code points in a form a computer can understand, aka bits. In other words, it's a way/algorithm to convert each of those code points to a sequence of bits or convert a sequence of bits to the equivalent code points. Note that there are a lot of alternative encodings for Unicode.


Joel gives a really nice explanation and an overview of the history here.

Xcode project not showing list of simulators

Cmd below solved my problem:

$ sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

In my case, I upgraded to Xcode 8 and downloaded another version 7.3.1 later (renamed it to "Xcode 7.3.1"), then cannot get the simulator list in Xcode 8.

How do I activate a virtualenv inside PyCharm's terminal?

Edit:

According to https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal, PyCharm 2016.3 (released Nov 2016) has virutalenv support for terminals out of the box

Auto virtualenv is supported for bash, zsh, fish, and Windows cmd. You can customize your shell preference in Settings (Preferences) | Tools | Terminal.


Old Method:

Create a file .pycharmrc in your home folder with the following contents

source ~/.bashrc
source ~/pycharmvenv/bin/activate

Using your virtualenv path as the last parameter.

Then set the shell Preferences->Project Settings->Shell path to

/bin/bash --rcfile ~/.pycharmrc

Where can I view Tomcat log files in Eclipse?

Another forum provided this answer:

Ahh, figured this out. The following system properties need to be set, so that the "logging.properties" file can be picked up.

Assuming that the tomcat is located under an Eclipse project, add the following under the "Arguments" tab of its launch configuration:

-Dcatalina.base="${project_loc}\<apache-tomcat-5.5.23_loc>" 
-Dcatalina.home="${project_loc}\<apache-tomcat-5.5.23_loc>" 
-Djava.util.logging.config.file="${project_loc}\<apache-tomcat-5.5.23_loc>\conf\logging.properties" 
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager 

http://www.coderanch.com/t/442412/Tomcat/Tweaking-tomcat-logging-properties-file

javascript clear field value input

HTML:

<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);" onblur="fillField(this);"/>

JS:

function clearField(input) {
  if(input.value=="Name") { //Only clear if value is "Name"
    input.value = "";
  }
}
function fillField(input) {
    if(input.value=="") {
        input.value = "Name";
    }
}

How to get the text of the selected value of a dropdown list?

You can use option:selected to get the chosen option of the select element, then the text() method:

$("select option:selected").text();

Here's an example:

_x000D_
_x000D_
console.log($("select option:selected").text());
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<select>_x000D_
    <option value="1">Volvo</option>_x000D_
    <option value="2" selected="selected">Saab</option>_x000D_
    <option value="3">Mercedes</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

fcntl substitute on Windows

Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker

It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.

The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker

How to percent-encode URL parameters in Python?

It is better to use urlencode here. Not much difference for single parameter but IMHO makes the code clearer. (It looks confusing to see a function quote_plus! especially those coming from other languates)

In [21]: query='lskdfj/sdfkjdf/ksdfj skfj'

In [22]: val=34

In [23]: from urllib.parse import urlencode

In [24]: encoded = urlencode(dict(p=query,val=val))

In [25]: print(f"http://example.com?{encoded}")
http://example.com?p=lskdfj%2Fsdfkjdf%2Fksdfj+skfj&val=34

Docs

urlencode: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode

quote_plus: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus

Getting unique values in Excel by using formulas only

You can also do it this way.

Create the following named ranges:

nList = the list of original values
nRow = ROW(nList)-ROW(OFFSET(nList,0,0,1,1))+1
nUnique = IF(COUNTIF(OFFSET(nList,nRow,0),nList)=0,COUNTIF(nList, "<"&nList),"")

With these 3 named ranges you can generate the ordered list of unique values with the formula below. It will be sorted in ascending order.

IFERROR(INDEX(nList,MATCH(SMALL(nUnique,ROW()-?),nUnique,0)),"")

You will need to substitute the row number of the cell just above the first element of your unique ordered list for the '?' character.

eg. If your unique ordered list begins in cell B5 then the formula will be:

IFERROR(INDEX(nList,MATCH(SMALL(nUnique,ROW()-4),nUnique,0)),"")

pull/push from multiple remote locations

I wanted to work in VSO/TFS, then push publicly to GitHub when ready. Initial repo created in private VSO. When it came time to add to GitHub I did:

git remote add mygithubrepo https://github.com/jhealy/kinect2.git
git push -f mygithubrepo master

Worked like a champ...

For a sanity check, issue "git remote -v" to list the repositories associated with a project.

C:\dev\kinect\vso-repo-k2work\FaceNSkinWPF>git remote -v
githubrepo      https://github.com/jhealy/kinect2.git (fetch)
githubrepo      https://github.com/jhealy/kinect2.git (push)
origin  https://devfish.visualstudio.com/DefaultCollection/_git/Kinect2Work (fetch)
origin  https://devfish.visualstudio.com/DefaultCollection/_git/Kinect2Work (push)

Simple way, worked for me... Hope this helps someone.

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

  1. Check if compatible Mysql for your PHP version is correctly installed. (eg. mysql-installer-community-5.5.40.1.msi for PHP 5.2.10, apache 2.2 and phpMyAdmin 3.5.2)
  2. In your php\php.ini set your loadable php extensions path (eg. extension_dir = "C:\php\ext") (https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)
  3. (In your php\php.ini) check if extension=php_mysqli.dll is uncommented (https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)
  4. Set your php folder (eg."C:\php") and php\ext folder (eg."C:\php\ext") as your runtime environment variable path (https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)
  5. Restart apache service (https://drive.google.com/open?id=1kJF5kxPSrj3LdKWJcJTos9ecKFx0ORAW)

Python Pandas Replacing Header with Top Row

header = table_df.iloc[0]
table_df.drop([0], axis =0, inplace=True)
table_df.reset_index(drop=True)
table_df.columns = header
table_df

How to enable remote access of mysql in centos?

In case of Allow IP to mysql server linux machine. you can do following command--

 nano /etc/httpd/conf.d/phpMyAdmin.conf  and add Desired IP.

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8
   Order allow,deny
   allow from all
   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>

    Require ip 192.168.9.1(Desired IP)

</RequireAny>
   </IfModule>
 <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     #Allow from All

     Allow from 192.168.9.1(Desired IP)

</IfModule>

And after Update, please restart using following command--

sudo systemctl restart httpd.service

Java - Check if JTextField is empty or not

Well, the code that renders the button enabled/disabled:

if(name.getText().equals("")) {
    loginbt.setEnabled(false);
}else {
    loginbt.setEnabled(true);
}

must be written in javax.swing.event.ChangeListener and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?

Is it possible to play music during calls so that the partner can hear it ? Android

No, It is not possible. But if you want to dig it more, then you can visit Using Android phone as GSM Gateway for VoIP where author has concluded that

It's not possible to use Android as a GSM Gateway in its current form. Even after flashing custom ROM because they also depends on proprietary RIL (Radio Interface Layer) firmwares. Hurdles 1 and 2 (API limitation) can be removed because the source code is available for the open source community to make it possible. However, the hurdle 3 (proprietary RIL) is dependent on the hardware vendors. Hardware vendors do not usually make their device drivers code available.

How to remove a file from the index in git?

git reset HEAD <file> 

for removing a particular file from the index.

and

git reset HEAD

for removing all indexed files.

How to disable HTML links

You can use this to disabled the Hyperlink of asp.net or link buttons in html.

$("td > a").attr("disabled", "disabled").on("click", function() {
    return false; 
});

MySQL stored procedure vs function, which would I use when?

One significant difference is that you can include a function in your SQL queries, but stored procedures can only be invoked with the CALL statement:

UDF Example:

CREATE FUNCTION hello (s CHAR(20))
   RETURNS CHAR(50) DETERMINISTIC
   RETURN CONCAT('Hello, ',s,'!');
Query OK, 0 rows affected (0.00 sec)

CREATE TABLE names (id int, name varchar(20));
INSERT INTO names VALUES (1, 'Bob');
INSERT INTO names VALUES (2, 'John');
INSERT INTO names VALUES (3, 'Paul');

SELECT hello(name) FROM names;
+--------------+
| hello(name)  |
+--------------+
| Hello, Bob!  |
| Hello, John! |
| Hello, Paul! |
+--------------+
3 rows in set (0.00 sec)

Sproc Example:

delimiter //

CREATE PROCEDURE simpleproc (IN s CHAR(100))
BEGIN
   SELECT CONCAT('Hello, ', s, '!');
END//
Query OK, 0 rows affected (0.00 sec)

delimiter ;

CALL simpleproc('World');
+---------------------------+
| CONCAT('Hello, ', s, '!') |
+---------------------------+
| Hello, World!             |
+---------------------------+
1 row in set (0.00 sec)

Importing .py files in Google Colab

  1. You can upload local files to google colab by using upload() function in google.colab.files
  2. If you have files on github, then clone the repo using !git clone https://github.com/username/repo_name.git. Then just like in jupyter notebook load it using the magic function %load %load filename.py.

Recursively look for files with a specific extension

Without using find:

du -a $directory | awk '{print $2}' | grep '\.in$'

How to configure nginx to enable kinda 'file browser' mode?

I've tried many times.

And at last I just put autoindex on; in http but outside of server, and it's OK.

Google Maps API 3 - Custom marker color for default (dot) marker

Sometimes something really simple, can be answered complex. I am not saying that any of the above answers are incorrect, but I would just apply, that it can be done as simple as this:

I know this question is old, but if anyone just wants to change to pin or marker color, then check out the documentation: https://developers.google.com/maps/documentation/android-sdk/marker

when you add your marker simply set the icon-property:

GoogleMap gMap;
LatLng latLng;
....
// write your code...
....
gMap.addMarker(new MarkerOptions()
    .position(latLng)
    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

There are 10 default colors to choose from. If that isn't enough (the simple solution) then I would probably go for the more complex given in the other answers, fulfilling a more complex need.

ps: I've written something similar in another answer and therefore I should refer to that answer, but the last time I did that, I was asked to post the answer since it was so short (as this one)..

How can I toggle word wrap in Visual Studio?

In VS Code === Version: 1.52.1

  1. Open VS Code settings

  2. From the settings find the settings.json file and open it

  3. add this code - "editor.accessibilitySupport": "off"

If you already added "editor.accessibilitySupport" with the value "on" before then simply turn it to "off". This is the code worked for me when I faced the same problem while working with one of my JS Project.

How to add click event to a iframe with JQuery

None of the suggested answers worked for me. I solved a similar case the following way:

<a href="http://my-target-url.com" id="iframe-wrapper"></a>
<iframe id="iframe_id" src="http://something.com" allowtrancparency="yes" frameborder="o"></iframe>

The css (of course exact positioning should change according to the app requirements):

#iframe-wrapper, iframe#iframe_id {
  width: 162px;
  border: none;
  height: 21px;
  position: absolute;
  top: 3px;
  left: 398px;
}
#alerts-wrapper {
  z-index: 1000;
}

Of course now you can catch any event on the iframe-wrapper.

C# catch a stack overflow exception

From the MSDN page on StackOverflowExceptions:

In prior versions of the .NET Framework, your application could catch a StackOverflowException object (for example, to recover from unbounded recursion). However, that practice is currently discouraged because significant additional code is required to reliably catch a stack overflow exception and continue program execution.

Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop. Note that an application that hosts the common language runtime (CLR) can specify that the CLR unload the application domain where the stack overflow exception occurs and let the corresponding process continue. For more information, see ICLRPolicyManager Interface and Hosting the Common Language Runtime.

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How to check Grants Permissions at Run-Time?

Nice !!

I just found my need we can check if the permission is granted by :

checkSelfPermission(Manifest.permission.READ_CONTACTS)

Request permissions if necessary

if (checkSelfPermission(Manifest.permission.READ_CONTACTS)
            != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant

        return;
    }

Handle the permissions request response

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! do the
                // calendar task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'switch' lines to check for other
        // permissions this app might request
    }
}