Programs & Examples On #Startup

Startup usually refers to the processes or events that occur at the start of a program, at the beginning of execution of a code block, or when a device is first booted.

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

After following the steps from @Johnride, I still got the same error.

This fixed the problem:

Tools-> Options-> Select no proxy

source: https://www.youtube.com/watch?v=uI1j-8F8eN4

How to create windows service from java jar?

Another option is winsw: https://github.com/kohsuke/winsw/

Configure an xml file to specify the service name, what to execute, any arguments etc. And use the exe to install. Example xml: https://github.com/kohsuke/winsw/tree/master/examples

I prefer this to nssm, because it is one lightweight exe; and the config xml is easy to share/commit to source code.

PS the service is installed by running your-service.exe install

How do I start my app on startup?

The Sean's solution didn't work for me initially (Android 4.2.2). I had to add a dummy activity to the same Android project and run the activity manually on the device at least once. Then the Sean's solution started to work and the BroadcastReceiver was notified after subsequent reboots.

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

Error: Selection does not contain a main type

When you save your file, make sure it has the extension .java. If it does not, Eclipse won't know to read it as a java file.

how to start the tomcat server in linux?

Go to your Tomcat Directory with : cd/home/user/apache-tomcat6.0

  • sh bin/startup.sh.>> tail -f logs/catelina.out.>>

How to run a program automatically as admin on Windows 7 at startup?

This is not possible.
However, you can create a service that runs under an administrative user.

The service can run automatically at startup and communicate with your existing application.
When the application needs to do something as an administrator, it can ask the service to do it for it.

Remember that multiple users can be logged on at once.

Run Batch File On Start-up

Go to Run (WINDOWS + R) and Type shell:startup, paste your .bat file there !

How to call a method after bean initialization is complete?

To expand on the @PostConstruct suggestion in other answers, this really is the best solution, in my opinion.

  • It keeps your code decoupled from the Spring API (@PostConstruct is in javax.*)
  • It explicitly annotates your init method as something that needs to be called to initialize the bean
  • You don't need to remember to add the init-method attribute to your spring bean definition, spring will automatically call the method (assuming you register the annotation-config option somewhere else in the context, anyway).

Cannot run Eclipse; JVM terminated. Exit code=13

Just uninstalled jre-32 bit version and It worked fine for me.

How to run a C# application at Windows startup?

I did not find any of the above code worked. Maybe that's because my app is running .NET 3.5. I don't know. The following code worked perfectly for me. I got this from a senior level .NET app developer on my team.

Write(Microsoft.Win32.Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\", "WordWatcher", "\"" + Application.ExecutablePath.ToString() + "\"");
public bool Write(RegistryKey baseKey, string keyPath, string KeyName, object Value)
{
    try
    {
        // Setting 
        RegistryKey rk = baseKey;
        // I have to use CreateSubKey 
        // (create or open it if already exits), 
        // 'cause OpenSubKey open a subKey as read-only 
        RegistryKey sk1 = rk.CreateSubKey(keyPath);
        // Save the value 
        sk1.SetValue(KeyName.ToUpper(), Value);

        return true;
    }
    catch (Exception e)
    {
        // an error! 
        MessageBox.Show(e.Message, "Writing registry " + KeyName.ToUpper());
        return false;
    }
}

Spring Boot application as a Service

In systemd unit files you can set environment variables directory or through an EnvironmentFile. I would propose doing things this way since it seems to be the least amount of friction.

Sample unit file

$ cat /etc/systemd/system/hello-world.service
[Unit]
Description=Hello World Service
After=systend-user-sessions.service

[Service]
EnvironmentFile=/etc/sysconfig/hello-world
Type=simple
ExecStart=/usr/bin/java ... hello-world.jar

Then setup a file under /etc/sysconfig/hello-world which includes uppercase names of your Spring Boot variables. For example, a variable called server.port would follow the form SERVER_PORT as an environment variable:

$ cat /etc/sysconfig/hello-world
SERVER_PORT=8081

The mechanism being exploited here is that Spring Boot applications will take the list of properties and then translate them, making everything uppercase, and replacing dots with underscores. Once the Spring Boot app goes through this process, it then looks for environment variables that match, and uses any found accordingly.

This is highlighted in more detail in this SO Q&A titled: How to set a Spring Boot property with an underscore in its name via Environment Variables?

References

Visual c++ can't open include file 'iostream'

quick fix for small programs:

add: #include <cstdlib>

"fatal: Not a git repository (or any of the parent directories)" from git status

Simply, after you clone the repo you need to cd (change your current directory) to the new cloned folder

git clone https://[email protected]/Repo_Name.git

cd Repo_Name

Display the binary representation of a number in C?

There is no direct format specifier for this in the C language. Although I wrote this quick python snippet to help you understand the process step by step to roll your own.

#!/usr/bin/python

dec = input("Enter a decimal number to convert: ")
base = 2
solution = ""

while dec >= base:
    solution = str(dec%base) + solution
    dec = dec/base
if dec > 0:
    solution = str(dec) + solution

print solution

Explained:

dec = input("Enter a decimal number to convert: ") - prompt the user for numerical input (there are multiple ways to do this in C via scanf for example)

base = 2 - specify our base is 2 (binary)

solution = "" - create an empty string in which we will concatenate our solution

while dec >= base: - while our number is bigger than the base entered

solution = str(dec%base) + solution - get the modulus of the number to the base, and add it to the beginning of our string (we must add numbers right to left using division and remainder method). the str() function converts the result of the operation to a string. You cannot concatenate integers with strings in python without a type conversion.

dec = dec/base - divide the decimal number by the base in preperation to take the next modulo

if dec > 0: solution = str(dec) + solution - if anything is left over, add it to the beginning (this will be 1, if anything)

print solution - print the final number

Position buttons next to each other in the center of page

your code will look something like this ...

<!doctype html>
<html lang="en">

<head>
<style>
#button1{
width: 300px;
height: 40px;

}
#button2{
width: 300px;
height: 40px;
}
display:inline-block;
</style>

<meta charset="utf-8">
<meta name="Homepage" content="Starting page for the survey website ">

 <title> Survey HomePage</title>
</head>
<body>
<center>
<img src="kingstonunilogo.jpg" alt="uni logo" style="width:180px;height:160px">
 <button type="button home-button" id="button1" >Home</button>
 <button type="button contact-button" id="button2">Contact Us</button>
</center>
</body>
 </html>

Border length smaller than div width?

The border is given the whole html element. If you want half bottom border, you can wrap it with some other identifiable block like span.

HTML code:

<div> <span>content here </span></div>

CSS as below:

 div{
    width:200px;
    height:50px;   
    }
 span{
        width:100px;
        border-bottom:1px solid magenta;   
    } 

Form Submit Execute JavaScript Best Practice?

I know it's a little late for this. But I always thought that the best way to create event listeners is directly from JavaScript. Kind of like not applying inline CSS styles.

function validate(){
    //do stuff
}
function init(){
    document.getElementById('form').onsubmit = validate;
}
window.onload = init;

That way you don't have a bunch of event listeners throughout your HTML.

How would I get everything before a : in a string Python

I have benchmarked these various technics under Python 3.7.0 (IPython).

TLDR

  • fastest (when the split symbol c is known): pre-compiled regex.
  • fastest (otherwise): s.partition(c)[0].
  • safe (i.e., when c may not be in s): partition, split.
  • unsafe: index, regex.

Code

import string, random, re

SYMBOLS = string.ascii_uppercase + string.digits
SIZE = 100

def create_test_set(string_length):
    for _ in range(SIZE):
        random_string = ''.join(random.choices(SYMBOLS, k=string_length))
        yield (random.choice(random_string), random_string)

for string_length in (2**4, 2**8, 2**16, 2**32):
    print("\nString length:", string_length)
    print("  regex (compiled):", end=" ")
    test_set_for_regex = ((re.compile("(.*?)" + c).match, s) for (c, s) in test_set)
    %timeit [re_match(s).group() for (re_match, s) in test_set_for_regex]
    test_set = list(create_test_set(16))
    print("  partition:       ", end=" ")
    %timeit [s.partition(c)[0] for (c, s) in test_set]
    print("  index:           ", end=" ")
    %timeit [s[:s.index(c)] for (c, s) in test_set]
    print("  split (limited): ", end=" ")
    %timeit [s.split(c, 1)[0] for (c, s) in test_set]
    print("  split:           ", end=" ")
    %timeit [s.split(c)[0] for (c, s) in test_set]
    print("  regex:           ", end=" ")
    %timeit [re.match("(.*?)" + c, s).group() for (c, s) in test_set]

Results

String length: 16
  regex (compiled): 156 ns ± 4.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.3 µs ± 430 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            26.1 µs ± 341 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.8 µs ± 1.26 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.3 µs ± 835 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 4.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 256
  regex (compiled): 167 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 694 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  index:            28.6 µs ± 2.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.4 µs ± 979 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            31.5 µs ± 4.86 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            148 µs ± 7.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

String length: 65536
  regex (compiled): 173 ns ± 3.95 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 613 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 515 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.2 µs ± 796 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.5 µs ± 377 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 4294967296
  regex (compiled): 165 ns ± 1.2 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.9 µs ± 144 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 571 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.1 µs ± 472 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            28.1 µs ± 1.69 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            137 µs ± 6.53 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Splitting a list into N parts of approximately equal length

#!/usr/bin/python


first_names = ['Steve', 'Jane', 'Sara', 'Mary','Jack','Bob', 'Bily', 'Boni', 'Chris','Sori', 'Will', 'Won','Li']

def chunks(l, n):
for i in range(0, len(l), n):
    # Create an index range for l of n items:
    yield l[i:i+n]

result = list(chunks(first_names, 5))
print result

Picked from this link, and this was what helped me. I had a pre-defined list.

Check to see if cURL is installed locally?

Assuming you want curl installed: just execute the install command and see what happens.

$ sudo yum install curl

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.cat.pdx.edu
 * epel: mirrors.kernel.org
 * extras: mirrors.cat.pdx.edu
 * remi-php72: repo1.sea.innoscale.net
 * remi-safe: repo1.sea.innoscale.net
 * updates: mirrors.cat.pdx.edu
Package curl-7.29.0-54.el7_7.1.x86_64 already installed and latest version
Nothing to do

Convert java.util.Date to java.time.LocalDate

first, it's easy to convert a Date to an Instant

Instant timestamp = new Date().toInstant(); 

Then, you can convert the Instant to any date api in jdk 8 using ofInstant() method:

LocalDateTime date = LocalDateTime.ofInstant(timestamp, ZoneId.systemDefault()); 

Get contentEditable caret index position

Kinda late to the party, but in case anyone else is struggling. None of the Google searches I've found for the past two days have come up with anything that works, but I came up with a concise and elegant solution that will always work no matter how many nested tags you have:

_x000D_
_x000D_
function cursor_position() {_x000D_
    var sel = document.getSelection();_x000D_
    sel.modify("extend", "backward", "paragraphboundary");_x000D_
    var pos = sel.toString().length;_x000D_
    if(sel.anchorNode != undefined) sel.collapseToEnd();_x000D_
_x000D_
    return pos;_x000D_
}_x000D_
_x000D_
// Demo:_x000D_
var elm = document.querySelector('[contenteditable]');_x000D_
elm.addEventListener('click', printCaretPosition)_x000D_
elm.addEventListener('keydown', printCaretPosition)_x000D_
_x000D_
function printCaretPosition(){_x000D_
  console.log( cursor_position(), 'length:', this.textContent.trim().length )_x000D_
}
_x000D_
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>
_x000D_
_x000D_
_x000D_

It selects all the way back to the beginning of the paragraph and then counts the length of the string to get the current position and then undoes the selection to return the cursor to the current position. If you want to do this for an entire document (more than one paragraph), then change paragraphboundary to documentboundary or whatever granularity for your case. Check out the API for more details. Cheers! :)

How to round a Double to the nearest Int in swift?

Swift 3: If you want to round to a certain digit number e.g. 5.678434 -> 5.68 you can just combine the round() or roundf() function with a multiplication:

let value:Float = 5.678434
let roundedValue = roundf(value * 100) / 100
print(roundedValue) //5.68

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

This Error mainly came when the SQL Service is stopped.You need to Restart the service.To go to this window you have to search the Services like this- enter image description here

Then Search for SQLSERVER(MSSQLSERVER) and Restart the service.

enter image description here

Hope this will work.

Spring RequestMapping for controllers that produce and consume JSON

There are 2 annotations in Spring: @RequestBody and @ResponseBody. These annotations consumes, respectively produces JSONs. Some more info here.

Convert char * to LPWSTR

You may use CString, CStringA, CStringW to do automatic conversions and convert between these types. Further, you may also use CStrBuf, CStrBufA, CStrBufW to get RAII pattern modifiable strings

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

In PrimeFaces 3.0, that style get applied on the generated inner <div> of the table cell, not on the <td> as you (and I) would expect. The following example should work out for you:

<p:dataTable styleClass="myTable">

with

.myTable td:nth-child(1) {
    width: 20px;
}

In PrimeFaces 3.5 and above, it should work exactly the way you coded and expected.

Index all *except* one item in python

Note that if variable is list of lists, some approaches would fail. For example:

v1 = [[range(3)] for x in range(4)]
v2 = v1[:3]+v1[4:] # this fails
v2

For the general case, use

removed_index = 1
v1 = [[range(3)] for x in range(4)]
v2 = [x for i,x in enumerate(v1) if x!=removed_index]
v2

Generate table relationship diagram from existing schema (SQL Server)

For SQL statements you can try reverse snowflakes. You can join at sourceforge or the demo site at http://snowflakejoins.com/.

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.

Writing a dictionary to a text file?

You can do as follow :

import json
exDict = {1:1, 2:2, 3:3}
file.write(json.dumps(exDict))

https://developer.rhino3d.com/guides/rhinopython/python-xml-json/

How to mock private method for testing using PowerMock?

For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.

import java.util.Random;

public class CodeWithPrivateMethod {

    public void meaningfulPublicApi() {
        if (doTheGamble("Whatever", 1 << 3)) {
            throw new RuntimeException("boom");
        }
    }

    private boolean doTheGamble(String whatever, int binary) {
        Random random = new Random(System.nanoTime());
        boolean gamble = random.nextBoolean();
        return gamble;
    }
}

The test class looks as follows:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
    private CodeWithPrivateMethod classToTest;

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        classToTest = PowerMockito.spy(classToTest);

        doReturn(true).when(classToTest, "doTheGamble", anyString(), anyInt());

        classToTest.meaningfulPublicApi();
    }
}

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

Android - default value in editText

You can use text property in your xml file for particular Edittext fields. For example :

<EditText
    android:id="@+id/ET_User"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="yourusername"/>

like this all Edittext fields contains text whatever u want,if user wants to change particular Edittext field he remove older text and enter his new text.

In Another way just you get the particular Edittext field id in activity class and set text to that one.

Another way = programmatically

Example:

EditText username=(EditText)findViewById(R.id.ET_User);

username.setText("jack");

Sorting object property by values

Here is one more example:

_x000D_
_x000D_
function sortObject(obj) {_x000D_
  var arr = [];_x000D_
  var prop;_x000D_
  for (prop in obj) {_x000D_
    if (obj.hasOwnProperty(prop)) {_x000D_
      arr.push({_x000D_
        'key': prop,_x000D_
        'value': obj[prop]_x000D_
      });_x000D_
    }_x000D_
  }_x000D_
  arr.sort(function(a, b) {_x000D_
    return a.value - b.value;_x000D_
  });_x000D_
  return arr; // returns array_x000D_
}_x000D_
var list = {_x000D_
  car: 300,_x000D_
  bike: 60,_x000D_
  motorbike: 200,_x000D_
  airplane: 1000,_x000D_
  helicopter: 400,_x000D_
  rocket: 8 * 60 * 60_x000D_
};_x000D_
var arr = sortObject(list);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

How to use custom packages

I try so many ways but the best I use go.mod and put

module nameofProject.com

and then i import from same project I use

import("nameofProject.com/folder")

It's very useful to create project in any place

How to show the text on a ImageButton?

As you can't use android:text I recommend you to use a normal button and use one of the compound drawables. For instance:

<Button 
    android:id="@+id/buttonok" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/buttonok"
    android:text="OK"/>

You can put the drawable wherever you want by using: drawableTop, drawableBottom, drawableLeft or drawableRight.

UPDATE

For a button this too works pretty fine. Putting android:background is fine!

<Button
    android:id="@+id/fragment_left_menu_login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_bg"
    android:text="@string/login_string" />

I just had this issue and is working perfectly.

Maven : error in opening zip file when running maven

This error can occur when your connection gets interrupted during your dependencies are being downloaded. Delete the relevant repository folder and run following command again to download a fresh copy of corrupted file.

mvn clean install 

How to revert initial git commit?

You can delete the HEAD and restore your repository to a new state, where you can create a new initial commit:

git update-ref -d HEAD

After you create a new commit, if you have already pushed to remote, you will need to force it to the remote in order to overwrite the previous initial commit:

git push --force origin

How can I see function arguments in IPython Notebook Server 3?

Adding screen shots(examples) and some more context for the answer of @Thomas G.

if its not working please make sure if you have executed code properly. In this case make sure import pandas as pd is ran properly before checking below shortcut.

Place the cursor in middle of parenthesis () before you use shortcut.

shift + tab

Display short document and few params

enter image description here

shift + tab + tab

Expands document with scroll bar

enter image description here

shift + tab + tab + tab

Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.

enter image description here

shift + tab + tab + tab + tab

It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.

enter image description here

jQuery iframe load() event?

use iframe onload event

$('#theiframe').on("load", function() {
    alert(1);
});

Write single CSV file using spark-csv

I'm using this in Python to get a single file:

df.toPandas().to_csv("/tmp/my.csv", sep=',', header=True, index=False)

How to close existing connections to a DB

This should disconnect everyone else, and leave you as the only user:

alter database YourDb set single_user with rollback immediate

Note: Don't forget

alter database YourDb set MULTI_USER

after you're done!

How can I get a value from a map?

The main problem is that operator [] is used to insert and read a value into and from the map, so it cannot be const. If the key does not exist, it will create a new entry with a default value in it, incrementing the size of the map, that will contain a new key with an empty string ,in this particular case, as a value if the key does not exist yet. You should avoid operator[] when reading from a map and use, as was mention before, "map.at(key)" to ensure bound checking. This is one of the most common mistakes people often do with maps. You should use "insert" and "at" unless your code is aware of this fact. Check this talk about common bugs Curiously Recurring C++ Bugs at Facebook

Pandas DataFrame Groupby two columns and get counts

Inserting data into a pandas dataframe and providing column name.

import pandas as pd
df = pd.DataFrame([['A','C','A','B','C','A','B','B','A','A'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['Alphabet','Words']]
print(df)   #printing dataframe.

This is our printed data:

enter image description here

For making a group of dataframe in pandas and counter,
You need to provide one more column which counts the grouping, let's call that column as, "COUNTER" in dataframe.

Like this:

df['COUNTER'] =1       #initially, set that counter to 1.
group_data = df.groupby(['Alphabet','Words'])['COUNTER'].sum() #sum function
print(group_data)

OUTPUT:

enter image description here

How do I log a Python error with debug information?

This answer builds up from the above excellent ones.

In most applications, you won't be calling logging.exception(e) directly. Most likely you have defined a custom logger specific for your application or module like this:

# Set the name of the app or module
my_logger = logging.getLogger('NEM Sequencer')
# Set the log level
my_logger.setLevel(logging.INFO)

# Let's say we want to be fancy and log to a graylog2 log server
graylog_handler = graypy.GELFHandler('some_server_ip', 12201)
graylog_handler.setLevel(logging.INFO)
my_logger.addHandler(graylog_handler)

In this case, just use the logger to call the exception(e) like this:

try:
    1/0
except ZeroDivisionError, e:
    my_logger.exception(e)

Warning: #1265 Data truncated for column 'pdd' at row 1

As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)

EDIT 1:

Following your comment, I run a test table:

mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)

Insertion:

mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)

EDIT 2:

So, aparently you want to insert a NULL value to pdd field as your comment states ? You can do that in 2 ways like this:

Method 1:

mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)

Method 2:

mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)

EDIT 3:

You failed to change the default value of pdd field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)

mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3  Duplicates: 0  Warnings: 1

What algorithms compute directions from point A to point B on a map?

This is pure speculation on my part, but I suppose that they may use an influence map data structure overlaying the directed map in order to narrow the search domain. This would allow the search algorithm to direct the path to major routes when the desired trip is long.

Given that this is a Google app, it's also reasonable to suppose that a lot of the magic is done via extensive caching. :) I wouldn't be surprised if caching the top 5% most common Google Map route requests allowed for a large chunk (20%? 50%?) of requests to be answered by a simple look-up.

Call a function after previous function is complete

Try this :

function method1(){
   // some code

}

function method2(){
   // some code
}

$.ajax({
   url:method1(),
   success:function(){
   method2();
}
})

How can I represent an infinite number in Python?

There is an infinity in the NumPy library: from numpy import inf. To get negative infinity one can simply write -inf.

Linux command to print directory structure in the form of a tree

Adding the below function in bashrc lets you run the command without any arguments which displays the current directory structure and when run with any path as argument, will display the directory structure of that path. This avoids the need to switch to a particular directory before running the command.

function tree() {
    find ${1:-.} | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/"
}

This works in gitbash too.

Source: Comment from @javasheriff here

How to do jquery code AFTER page loading?

write the code that you want to be executed inside this. When your document is ready, this will be executed.

$(document).ready(function() { 

});

How to check for file lock?

You can also check if any process is using this file and show a list of programs you must close to continue like an installer does.

public static string GetFileProcessName(string filePath)
{
    Process[] procs = Process.GetProcesses();
    string fileName = Path.GetFileName(filePath);

    foreach (Process proc in procs)
    {
        if (proc.MainWindowHandle != new IntPtr(0) && !proc.HasExited)
        {
            ProcessModule[] arr = new ProcessModule[proc.Modules.Count];

            foreach (ProcessModule pm in proc.Modules)
            {
                if (pm.ModuleName == fileName)
                    return proc.ProcessName;
            }
        }
    }

    return null;
}

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

Making Enter key on an HTML form submit instead of activating button

You can use jQuery:

$(function() {
    $("form input").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('button[type=submit] .default').click();
            return false;
        } else {
            return true;
        }
    });
});

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

How to store a dataframe using Pandas

pyarrow compatibility across versions

Overall move has been to pyarrow/feather (deprecation warnings from pandas/msgpack). However I have a challenge with pyarrow with transient in specification Data serialized with pyarrow 0.15.1 cannot be deserialized with 0.16.0 ARROW-7961. I'm using serialization to use redis so have to use a binary encoding.

I've retested various options (using jupyter notebook)

import sys, pickle, zlib, warnings, io
class foocls:
    def pyarrow(out): return pa.serialize(out).to_buffer().to_pybytes()
    def msgpack(out): return out.to_msgpack()
    def pickle(out): return pickle.dumps(out)
    def feather(out): return out.to_feather(io.BytesIO())
    def parquet(out): return out.to_parquet(io.BytesIO())

warnings.filterwarnings("ignore")
for c in foocls.__dict__.values():
    sbreak = True
    try:
        c(out)
        print(c.__name__, "before serialization", sys.getsizeof(out))
        print(c.__name__, sys.getsizeof(c(out)))
        %timeit -n 50 c(out)
        print(c.__name__, "zlib", sys.getsizeof(zlib.compress(c(out))))
        %timeit -n 50 zlib.compress(c(out))
    except TypeError as e:
        if "not callable" in str(e): sbreak = False
        else: raise
    except (ValueError) as e: print(c.__name__, "ERROR", e)
    finally: 
        if sbreak: print("=+=" * 30)        
warnings.filterwarnings("default")

With following results for my data frame (in out jupyter variable)

pyarrow before serialization 533366
pyarrow 120805
1.03 ms ± 43.9 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
pyarrow zlib 20517
2.78 ms ± 81.8 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
msgpack before serialization 533366
msgpack 109039
1.74 ms ± 72.8 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
msgpack zlib 16639
3.05 ms ± 71.7 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
pickle before serialization 533366
pickle 142121
733 µs ± 38.3 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
pickle zlib 29477
3.81 ms ± 60.4 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
feather ERROR feather does not support serializing a non-default index for the index; you can .reset_index() to make the index into column(s)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
parquet ERROR Nested column branch had multiple children: struct<x: double, y: double>
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=

feather and parquet do not work for my data frame. I'm going to continue using pyarrow. However I will supplement with pickle (no compression). When writing to cache store pyarrow and pickle serialised forms. When reading from cache fallback to pickle if pyarrow deserialisation fails.

What is the Regular Expression For "Not Whitespace and Not a hyphen"

It can be done much easier:

\S which equals [^ \t\r\n\v\f]

Owl Carousel Won't Autoplay

Owl Carousel version matters a lot, as of now (2nd Aug 2020) the version is 2.3.4 and the right options for autoplay are:

$(".owl-carousel").owlCarousel({
    autoplay : true,
    autoplayTimeout: 3000,//Autoplay interval timeout.
    loop:true,//Infinity loop. Duplicate last and first items to get loop illusion.
    items:1 //The number of items you want to see on the screen.
});

Read more Owl configurations

ssl_error_rx_record_too_long and Apache SSL

Ask the user for the exact URL they're using in their browser. If they're entering https://your.site:80, they may receive the ssl_error_rx_record_too_long error.

How to add minutes to current time in swift

Save this little extension:

extension Int {

 var seconds: Int {
    return self
 }

 var minutes: Int {
    return self.seconds * 60
 }

 var hours: Int {
    return self.minutes * 60
 }

 var days: Int {
    return self.hours * 24
 }

 var weeks: Int {
    return self.days * 7
 }

 var months: Int {
    return self.weeks * 4
 }

 var years: Int {
    return self.months * 12
 }
}

Then use it intuitively like:

let threeDaysLater = TimeInterval(3.days)
date.addingTimeInterval(threeDaysLater)

Iterate a certain number of times without storing the iteration number anywhere

exec 'print "hello";' * 2

should work, but I'm kind of ashamed that I thought of it.

Update: Just thought of another one:

for _ in " "*10: print "hello"

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

in this scenario:

DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));

aren't you missing the column you want to compare to? example:

DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));    

I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.

DNS caching in linux

Here are two other software packages which can be used for DNS caching on Linux:

  • dnsmasq
  • bind

After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.

If your system is using NetworkManager you can either try using the dns=dnsmasq option in /etc/NetworkManager/NetworkManager.conf or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.

How to delete directory content in Java?

All files must be delete from the directory before it is deleted.

There are third party libraries that have a lot of common utilities, including ones that does that for you:

Where does Console.WriteLine go in ASP.NET?

This is confusing for everyone when it comes IISExpress. There is nothing to read console messages. So for example, in the ASPCORE MVC apps it configures using appsettings.json which does nothing if you are using IISExpress.

For right now you can just add loggerFactory.AddDebug(LogLevel.Debug); in your Configure section and it will at least show you your logs in the Debug Output window.

Good news CORE 2.0 this will all be changing: https://github.com/aspnet/Announcements/issues/255

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

It used to be easy, but Microsoft decided to make a breaking change: Before version 4.5, each version of .NET resided in its own directory below C:\Windows\Microsoft.NET\Framework (subdirectories v1.0.3705, v1.1.4322, v2.0.50727, v3.0, v3.5 and v4.0.30319).

Since version 4.5 this has been changed: Each version of .NET (i.e. 4.5.x, 4.6.x, 4.7.x, 4.8.x, ...) is being installed in the same subdirectory v4.0.30319 - so you are no longer able to check the installed .NET version by looking into Microsoft.NET\Framework.

To check the .NET version, Microsoft has provided two different sample scripts depending on the .NET version that is being checked, but I don't like having two different C# scripts for this. So I tried to combine them into one, here's the script GetDotNetVersion.cs I created (and updated it for 4.7.1 framework):

using System;
using Microsoft.Win32;
public class GetDotNetVersion
{
    public static void Main(string[] args)
    {
        Console.WriteLine((args != null && args.Length > 0) 
                          ? "Command line arguments: " + string.Join(",", args) 
                          : "");

        string maxDotNetVersion = GetVersionFromRegistry();
        if (String.Compare(maxDotNetVersion, "4.5") >= 0)
        {
            string v45Plus = GetDotNetVersion.Get45PlusFromRegistry();
            if (v45Plus != "") maxDotNetVersion = v45Plus;
        }
        Console.WriteLine("*** Maximum .NET version number found is: " + maxDotNetVersion + "***");
    }

    private static string Get45PlusFromRegistry()
    {
        String dotNetVersion = "";
        const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
        using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
        {
            if (ndpKey != null && ndpKey.GetValue("Release") != null)
            {
                dotNetVersion = CheckFor45PlusVersion((int)ndpKey.GetValue("Release"));
                Console.WriteLine(".NET Framework Version: " + dotNetVersion);
            }
            else
            {
                Console.WriteLine(".NET Framework Version 4.5 or later is not detected.");
            }
        }
        return dotNetVersion;
    }

    // Checking the version using >= will enable forward compatibility.
    private static string CheckFor45PlusVersion(int releaseKey)
    {
        if (releaseKey >= 528040) return "4.8 or later";
        if (releaseKey >= 461808) return "4.7.2";
        if (releaseKey >= 461308) return "4.7.1";
        if (releaseKey >= 460798) return "4.7";
        if (releaseKey >= 394802) return "4.6.2";
        if (releaseKey >= 394254) return "4.6.1";
        if (releaseKey >= 393295) return "4.6";
        if ((releaseKey >= 379893)) return "4.5.2";
        if ((releaseKey >= 378675)) return "4.5.1";
        if ((releaseKey >= 378389)) return "4.5";

        // This code should never execute. A non-null release key should mean
        // that 4.5 or later is installed.
        return "No 4.5 or later version detected";
    }

    private static string GetVersionFromRegistry()
    {
        String maxDotNetVersion = "";
        // Opens the registry key for the .NET Framework entry.
        using (RegistryKey ndpKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "")
                                        .OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
        {
            // As an alternative, if you know the computers you will query are running .NET Framework 4.5 
            // or later, you can use:
            // using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, 
            // RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
            foreach (string versionKeyName in ndpKey.GetSubKeyNames())
            {
                if (versionKeyName.StartsWith("v"))
                {
                    RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
                    string name = (string)versionKey.GetValue("Version", "");
                    string sp = versionKey.GetValue("SP", "").ToString();
                    string install = versionKey.GetValue("Install", "").ToString();
                    if (install == "") //no install info, must be later.
                    {
                        Console.WriteLine(versionKeyName + "  " + name);
                        if (String.Compare(maxDotNetVersion, name) < 0) maxDotNetVersion = name;
                    }
                    else
                    {
                        if (sp != "" && install == "1")
                        {
                            Console.WriteLine(versionKeyName + "  " + name + "  SP" + sp);
                            if (String.Compare(maxDotNetVersion, name) < 0) maxDotNetVersion = name;
                        }

                    }
                    if (name != "")
                    {
                        continue;
                    }
                    foreach (string subKeyName in versionKey.GetSubKeyNames())
                    {
                        RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
                        name = (string)subKey.GetValue("Version", "");
                        if (name != "")
                        {
                            sp = subKey.GetValue("SP", "").ToString();
                        }
                        install = subKey.GetValue("Install", "").ToString();
                        if (install == "")
                        {
                            //no install info, must be later.
                            Console.WriteLine(versionKeyName + "  " + name);
                            if (String.Compare(maxDotNetVersion, name) < 0) maxDotNetVersion = name;
                        }
                        else
                        {
                            if (sp != "" && install == "1")
                            {
                                Console.WriteLine("  " + subKeyName + "  " + name + "  SP" + sp);
                                if (String.Compare(maxDotNetVersion, name) < 0) maxDotNetVersion = name;
                            }
                            else if (install == "1")
                            {
                                Console.WriteLine("  " + subKeyName + "  " + name);
                                if (String.Compare(maxDotNetVersion, name) < 0) maxDotNetVersion = name;
                            } // if
                        } // if
                    } // for
                } // if
            } // foreach
        } // using
        return maxDotNetVersion;
    }
    
} // class

On my machine it outputs:

v2.0.50727 2.0.50727.4927 SP2
v3.0 3.0.30729.4926 SP2
v3.5 3.5.30729.4926 SP1
v4
Client 4.7.03056
Full 4.7.03056
v4.0
Client 4.0.0.0
.NET Framework Version: 4.7.2 or later
**** Maximum .NET version number found is: 4.7.2 or later ****

The only thing that needs to be maintained over time is the build number once a .NET version greater than 4.7.1 comes out - that can be done easily by modifying the function CheckFor45PlusVersion, you need to know the release key for the new version then you can add it. For example:

if (releaseKey >= 461308) return "4.7.1 or later";

This release key is still the latest one and valid for the Fall Creators update of Windows 10. If you're still running other (older) Windows versions, there is another one as per this documentation from Microsoft:

.NET Framework 4.7.1 installed on all other Windows OS versions 461310

So, if you need that as well, you'll have to add

if (releaseKey >= 461310) return "4.7.1 or later";

to the top of the function CheckFor45PlusVersion. Likewise it works for newer versions. For example, I have added the check for 4.8 recently. You can find those build numbers usually at Microsoft.


Note: You don't need Visual Studio to be installed, not even PowerShell - you can use csc.exe to compile and run the script above, which I have described here.


Update: The question is about the .NET Framework, for the sake of completeness I'd like to mention how to query the version of .NET Core as well - compared with the above, that is easy: Open a command shell and type:

dotnet --info Enter

and it will list the .NET Core version number, the Windows version and the versions of each related runtime DLL as well. Sample output:

.NET Core SDK (reflecting any global.json):
  Version: 2.1.300
  Commit: adab45bf0c

Runtime Environment:
  OS Name: Windows
  OS Version: 10.0.15063
  OS Platform: Windows
  RID: win10-x64
  Base Path: C:\Program Files\dotnet\sdk\2.1.300


Host (useful for support):
  Version: 2.1.0
  Commit: caa7b7e2ba

.NET Core SDKs installed:
  1.1.9 [C:\Program Files\dotnet\sdk]
  2.1.102 [C:\Program Files\dotnet\sdk]
  ...
  2.1.300 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.0 [C:\Program
  Files\dotnet\shared\Microsoft.AspNetCore.All]
  ...
  Microsoft.NETCore.App 2.1.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download

Note that

  • if you only need the version number without all the additional information, you can use
    dotnet --version.

  • on a 64 bit Windows PC, it is possible to install the x86 version side by side with the x64 version of .NET Core. If that is the case, you will only get the version that comes first in the environment variable PATH. That is especially important if you need to keep it up to date and want to know each version. To query both versions, use:

C:\Program Files\dotnet\dotnet.exe --version
3.0.100-preview6-012264
C:\Program Files (x86)\dotnet\dotnet.exe --version
3.0.100-preview6-012264

In the example above, both are the same, but if you forgot to update both instances, you might get different results! Note that Program Files is for the 64bit version, and Program Files (x86) is the 32bit version.


Update: If you prefer to keep the build numbers in a list rather than in a cascade of if-statements (as Microsoft suggested), then you can use this code for CheckFor45PlusVersion instead:

private static string CheckFor45PlusVersion(int releaseKey)
{
    var release = new Dictionary<int, string>()
    {
            { 378389, "4.5" },
            { 378675, "4.5.1" }, { 379893, "4.5.2" },
            { 393295, "4.6" },
            { 394254, "4.6.1" }, { 394802, "4.6.2" },
            { 460798, "4.7" },
            { 461308, "4.7.1" }, { 461808, "4.7.2" },
            { 528040, "4.8 or later" }
    };
    int result = -1;
    foreach(var k in release.OrderBy(k=>k.Key))
    {
        if (k.Key <= releaseKey) result = k.Key; else break;
    };
    return (result > 0) ? release[result] : "No 4.5 or later version detected";
}

execute shell command from android

A modification of the code by @CarloCannas:

public static void sudo(String...strings) {
    try{
        Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        outputStream.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

(You are welcome to find a better place for outputStream.close())

Usage example:

private static void suMkdirs(String path) {
    if (!new File(path).isDirectory()) {
        sudo("mkdir -p "+path);
    }
}

Update: To get the result (the output to stdout), use:

public static String sudoForResult(String...strings) {
    String res = "";
    DataOutputStream outputStream = null;
    InputStream response = null;
    try{
        Process su = Runtime.getRuntime().exec("su");
        outputStream = new DataOutputStream(su.getOutputStream());
        response = su.getInputStream();

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        res = readFully(response);
    } catch (IOException e){
        e.printStackTrace();
    } finally {
        Closer.closeSilently(outputStream, response);
    }
    return res;
}
public static String readFully(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = is.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
    }
    return baos.toString("UTF-8");
}

The utility to silently close a number of Closeables (So?ket may be no Closeable) is:

public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
    // Note: on Android API levels prior to 19 Socket does not implement Closeable
    for (Object x : xs) {
        if (x != null) {
            try {
                Log.d("closing: "+x);
                if (x instanceof Closeable) {
                    ((Closeable)x).close();
                } else if (x instanceof Socket) {
                    ((Socket)x).close();
                } else if (x instanceof DatagramSocket) {
                    ((DatagramSocket)x).close();
                } else {
                    Log.d("cannot close: "+x);
                    throw new RuntimeException("cannot close "+x);
                }
            } catch (Throwable e) {
                Log.x(e);
            }
        }
    }
}
}

Validate IPv4 address in Java

my solution (supports leading 0s):

   String pattern="^[0-9](\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25?[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?$";

Get the value in an input text box

You can simply set the value in text box.

First, you get the value like

var getValue = $('#txt_name').val();

After getting a value set in input like

$('#txt_name').val(getValue);

Rollback to an old Git commit in a public repo

Here is an example to do that

    cd /yourprojects/project-acme 


    git checkout efc11170c78 .

How to list files in a directory in a C program?

An example, available for POSIX compliant systems :

/*
 * This program displays the names of all files in the current directory.
 */

#include <dirent.h> 
#include <stdio.h> 

int main(void) {
  DIR *d;
  struct dirent *dir;
  d = opendir(".");
  if (d) {
    while ((dir = readdir(d)) != NULL) {
      printf("%s\n", dir->d_name);
    }
    closedir(d);
  }
  return(0);
}

Beware that such an operation is platform dependant in C.

Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

Date object to Calendar [Java]

Calendar.setTime()

It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.

Fastest way to ping a network range and return responsive hosts?

BSD's

for i in $(seq 1 254); do (ping -c1 -W5 192.168.1.$i >/dev/null && echo "192.168.1.$i" &) ;done

How to read files and stdout from a running Docker container

The stdout of the process started by the docker container is available through the docker logs $containerid command (use -f to keep it going forever). Another option would be to stream the logs directly through the docker remote API.

For accessing log files (only if you must, consider logging to stdout or other standard solution like syslogd) your only real-time option is to configure a volume (like Marcus Hughes suggests) so the logs are stored outside the container and available for processing from the host or another container.

If you do not need real-time access to the logs, you can export the files (in tar format) with docker export

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

I found this answer to the question:

http://padcom13.blogspot.co.uk/2011/10/creating-standalone-applications-with.html

Not only do you get the dependent lib files in a lib folder, you also get a bin director with both a unix and a dos executable.

The executable ultimately calls java with a -cp argument that lists all of your dependent libs too.

The whole lot sits in an appasembly folder inside the target folder. Epic.

============= Yes I know this is an old thread, but it's still coming high on search results so I thought it might help someone like me.

MongoDB: update every document on one field

This code will be helpful for you

        Model.update({
            'type': "newuser"
        }, {
            $set: {
                email: "[email protected]",
                phoneNumber:"0123456789"
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  

how to read a text file using scanner in Java?

I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath

Why rgb and not cmy?

The difference lies in whether mixing colours results in LIGHTER or DARKER colours. When mixing light, the result is a lighter colour, so mixing red light and blue light becomes a lighter pink. When mixing paint (or ink), red and blue become a darker purple. Mixing paint results in DARKER colours, whereas mixing light results in LIGHTER colours. Therefore for paint the primary colours are Red Yellow Blue (or Cyan Magenta Yellow) as you stated. Yet for light the primary colours are Red Green Blue. It is (virtually) impossible to mix Red Green Blue paint into Yellow paint, or mixing Red Yellow Blue light into Green light.

Round float to x decimals?

The Mark Dickinson answer, although complete, didn't work with the float(52.15) case. After some tests, there is the solution that I'm using:

import decimal
        
def value_to_decimal(value, decimal_places):
    decimal.getcontext().rounding = decimal.ROUND_HALF_UP  # define rounding method
    return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))

(The conversion of the 'value' to float and then string is very important, that way, 'value' can be of the type float, decimal, integer or string!)

Hope this helps anyone.

Is there a way to detach matplotlib plots so that the computation can continue?

Use plt.show(block=False), and at the end of your script call plt.show().

This will ensure that the window won't be closed when the script is finished.

How do you get total amount of RAM the computer has?

you can simply use this code to get those information, just add the reference

using Microsoft.VisualBasic.Devices;

and the simply use the following code

    private void button1_Click(object sender, EventArgs e)
    {
        getAvailableRAM();
    }

    public void getAvailableRAM()
    {
        ComputerInfo CI = new ComputerInfo();
        ulong mem = ulong.Parse(CI.TotalPhysicalMemory.ToString());
        richTextBox1.Text = (mem / (1024*1024) + " MB").ToString();
    }

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

Handling MySQL datetimes and timestamps in Java

In Java side, the date is usually represented by the (poorly designed, but that aside) java.util.Date. It is basically backed by the Epoch time in flavor of a long, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.

In SQL side, there are several standard date and time types, DATE, TIME and TIMESTAMP (at some DB's also called DATETIME), which are represented in JDBC as java.sql.Date, java.sql.Time and java.sql.Timestamp, all subclasses of java.util.Date. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.

In contrary to java.util.Date, the java.sql.Date contains only information about the date part (year, month, day). The Time contains only information about the time part (hours, minutes, seconds) and the Timestamp contains information about the both parts, like as java.util.Date does.

The normal practice to store a timestamp in the DB (thus, java.util.Date in Java side and java.sql.Timestamp in JDBC side) is to use PreparedStatement#setTimestamp().

java.util.Date date = getItSomehow();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);

The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp().

Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can just upcast.

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

This is the solution i found.

https://github.com/aspnet/EntityFramework.Docs/blob/master/entity-framework/core/miscellaneous/configuring-dbcontext.md

Configure DBContext via AddDbContext

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}

Add new constructor to your DBContext class

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
      :base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}

Inject context to your controllers

public class MyController
{
    private readonly BloggingContext _context;

    public MyController(BloggingContext context)
    {
      _context = context;
    }

    ...
}

Changing iframe src with Javascript

Maybe this can be helpful... It's plain html - no javascript:

_x000D_
_x000D_
<p>Click on link bellow to change iframe content:</p>_x000D_
<a href="http://www.bing.com" target="search_iframe">Bing</a> -_x000D_
<a href="http://en.wikipedia.org" target="search_iframe">Wikipedia</a> -_x000D_
<a href="http://google.com" target="search_iframe">Google</a> (not allowed in inframe)_x000D_
_x000D_
<iframe src="http://en.wikipedia.org" width="100%" height="100%" name="search_iframe"></iframe>
_x000D_
_x000D_
_x000D_

By the way some sites do not allow you to open them in iframe (security reasons - clickjacking)

jQuery $.ajax request of dataType json will not retrieve data from PHP script

  session_start();
include('connection.php');

/* function msg($subjectname,$coursename,$sem)
    {
    return '{"subjectname":'.$subjectname.'"coursename":'.$coursename.'"sem":'.$sem.'}';
    }*/ 
$title_id=$_POST['title_id'];
$result=mysql_query("SELECT * FROM `video` WHERE id='$title_id'") or die(mysql_error());
$qr=mysql_fetch_array($result);
$subject=$qr['subject'];
$course=$qr['course'];
$resultes=mysql_query("SELECT * FROM course JOIN subject ON course.id='$course' AND subject.id='$subject'");
$qqr=mysql_fetch_array($resultes);
$subjectname=$qqr['subjectname'];
$coursename=$qqr['coursename'];
$sem=$qqr['sem'];
$json = array("subjectname" => $subjectname, "coursename" => $coursename, "sem" => $sem,);
header("Content-Type: application/json", true);
echo json_encode( $json_arr );


 $.ajax({type:"POST",    
                  dataType: "json",    
                   url:'select-title.php',
                   data:$('#studey-form').serialize(),
                   contentType: "application/json; charset=utf-8",
                   beforeSend: function(x) {
        if(x && x.overrideMimeType) {
            x.overrideMimeType("application/j-son;charset=UTF-8");
        }
    },
                   success:function(response)
                  {
                    var response=$.parseJSON(response)
                    alert(response.subjectname);
                    $('#course').html("<option>"+response.coursename+"</option>"); 
                    $('#subject').html("<option>"+response.subjectname+"</option>");

                  },
                  error: function( error,x,y)
                  {

                  alert( x,y );

              }
                   });

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

jQuery changing style of HTML element

$('#navigation ul li').css('display', 'inline-block');

not a colon, a comma

C# DataTable.Select() - How do I format the filter criteria to include null?

Try this

myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )

Edit: Relevant sources:

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Im new to java hibernate but i could solve this problem, this is how i did it : I was working with hibernate and maven project. First you have to put persistence.xml under project directory, then add jdbc manually. Maven couldn't download my dependency so i added it manually. In the persistence.xml in design jdbc connection add it manually ps: i work with netbeans good luck

C# send a simple SSH command

SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo");
cSSH.Connect();
SshCommand x = cSSH.RunCommand("exec \"/var/lib/asterisk/bin/retrieve_conf\"");
cSSH.Disconnect();
cSSH.Dispose();

//using SSH.Net

Can Selenium WebDriver open browser windows silently in the background?

If you are using the Google Chrome driver, you can use this very simple code (it worked for me):

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome('chromedriver2_win32/chromedriver.exe', options=chrome_options)
driver.get('https://www.anywebsite.com')

How do you change the width and height of Twitter Bootstrap's tooltips?

Just override bootstrap.css

The default value in BS2 is max-width:200px; So you can increase it with whatever fits your needs.

.tooltip-inner {
    max-width: 350px;
    /* If max-width does not work, try using width instead */
    width: 350px; 
}

Root element is missing

Hi this is odd way but try it once

  1. Read the file content into a string
  2. print the string and check whether you are getting proper XML or not
  3. you can use XMLDocument.LoadXML(xmlstring)

I try with your code and same XML without adding any XML declaration it works for me

XmlDocument doc = new XmlDocument();
        doc.Load(@"H:\WorkSpace\C#\TestDemos\TestDemos\XMLFile1.xml");
        XmlNodeList nodes = doc.GetElementsByTagName("Product");
        XmlNode node = null;
        foreach (XmlNode n in nodes)
        {
            Console.WriteLine("HI");
        }

Its working perfectly fine

Convert float to std::string in C++

Use std::to_chars once your standard library provides it:

std::array<char, 32> buf;
auto result = std::to_chars(buf.data(), buf.data() + buf.size(), val);
if (result.ec == std::errc()) {
  auto str = std::string(buf.data(), result.ptr - buf.data());
  // use the string
} else {
  // handle the error
}

The advantages of this method are:

  • It is locale-independent, preventing bugs when writing data into formats such as JSON that require '.' as a decimal point
  • It provides shortest decimal representation with round trip guarantees
  • It is potentially more efficient than other standard methods because it doesn't use the locale and doesn't require allocation

Unfortunately std::to_string is of limited utility with floating point because it uses the fixed representation, rounding small values to zero and producing long strings for large values, e.g.

auto s1 = std::to_string(1e+40);
// s1 == 10000000000000000303786028427003666890752.000000

auto s2 = std::to_string(1e-40);
// s2 == 0.000000

C++20 might get a more convenient std::format API with the same benefits as std::to_chars if the P0645 standards proposal gets approved.

How to launch jQuery Fancybox on page load?

Window.load (as opposed to document.ready()) appears to the be the trick used in the JSFiddler onload demos of Fancybox 2.0:

$(window).load(function()
{
    $.fancybox("test");
});

Bare in mind you may be using document.ready() elsewhere, and IE9 gets upset with the load order of the two. This leaves you with two options: change everything to window.load or use a setTimer().

How to fix C++ error: expected unqualified-id

There should be no semicolon here:

class WordGame;

...but there should be one at the end of your class definition:

...
private:
    string theWord;
}; // <-- Semicolon should be at the end of your class definition

Android Button click go to another xml page

Write below code in your MainActivity.java file instead of your code.

public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button mBtn1 = (Button) findViewById(R.id.mBtn1);
        mBtn1.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        Log.i("clicks","You Clicked B1");
        Intent i=new Intent(MainActivity.this, MainActivity2.class);
        startActivity(i);
    }
}

And Declare MainActivity2 into your Androidmanifest.xml file using below code.

<activity
    android:name=".MainActivity2"
    android:label="@string/title_activity_main">
</activity>

How do I directly modify a Google Chrome Extension File? (.CRX)

I searched it in Google and I found this:

The Google Chrome Extension file type is CRX. It is essentially a compression format. So if you want to see what is behind an extension, the scripts and the code, just change the file-type from “CRX” to “ZIP” .

Unzip the file and you will get all the info you need. This way you can see the guts, learn how to write an extension yourself, or modify it for your own needs.

Then you can pack it back up with Chrome’s internal tools which automatically create the file back into CRX. Installing it just requires a click.

Compare if BigDecimal is greater than zero

This works too:

value > BigDecimal.ZERO

Cannot declare instance members in a static class in C#

public static class Employee
{
    public static string SomeSetting
    {
        get 
        {
            return ConfigurationManager.AppSettings["SomeSetting"];    
        }
    }
}

Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.

If you feel that you must store a reference to appsettings, try

public static class Employee
{
    private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;

    public static NameValueCollection AppSettings { get { return _appSettings; } }

}

It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.

How do I open an .exe from another C++ .exe?

When executable path has whitespace in system, call

#include<iostream>
using namespace std;
int main()
{
    system("explorer C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe ");
    system("pause");
return 0;
}

How to change row color in datagridview?

You have not mentioned how value is changed. I have used similar functionality when user is entering value. i.e. entering and leaving edit mode.

Using CellEndEdit event of datagridview.

private void dgMapTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    double newInteger;

    if (double.TryParse(dgMapTable[e.ColumnIndex,e.RowIndex].Value.ToString(), out newInteger)
    {
        if (newInteger < 0 || newInteger > 50)
        {
            dgMapTable[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red; 

            dgMapTable[e.ColumnIndex, e.RowIndex].ErrorText 
                = "Keep value in Range:" + "0 to " + "50";
        }
    }                               
}

You may add logic for clearing error notification in a similar way.

if in your case, if data is loaded programmatically, then CellLeave event can be used with same code.

How to display gpg key details without importing it?

When I stumbled up on this answer I was looking for a way to get an output that is easy to parse. For me the option --with-colons did the trick:

$ gpg --with-colons file
sec::4096:1:AAAAAAAAAAAAAAAA:YYYY-MM-DD::::Name (comment) email
ssb::4096:1:BBBBBBBBBBBBBBBB:YYYY-MM-DD::::

Documentation can be found here.

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I came across the same problem using a Wordpress page and plugin. This didn't work for the iframe plugin

[iframe src="https://itunes.apple.com/gb/app/witch-hunt/id896152730#?platform=iphone"]

but this does:

[iframe src="https://itunes.apple.com/gb/app/witch-hunt/id896152730"  width="100%" height="480" ]

As you see, I just left off the #?platform=iphone part in the end.

C/C++ check if one bit is set in, i.e. int variable

I use this:

#define CHECK_BIT(var,pos) ( (((var) & (pos)) > 0 ) ? (1) : (0) )

where "pos" is defined as 2^n (i.g. 1,2,4,8,16,32 ...)

Returns: 1 if true 0 if false

How to get the nvidia driver version from the command line?

On any linux system with the NVIDIA driver installed and loaded into the kernel, you can execute:

cat /proc/driver/nvidia/version

to get the version of the currently loaded NVIDIA kernel module, for example:

$ cat /proc/driver/nvidia/version 
NVRM version: NVIDIA UNIX x86_64 Kernel Module  304.54  Sat Sep 29 00:05:49 PDT 2012
GCC version:  gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

If you use .NET as your middle tier, check the route attribute clearly, for example,

I had issue when it was like this,

[Route("something/{somethingLong: long}")] //Space.

Fixed it by this,

[Route("something/{somethingLong:long}")] //No space

How to insert a new key value pair in array in php?

If you are creating new array then try this :

$arr = ['key' => 'value'];

And if array is already created then try this :

$arr['key'] = 'value';

Dynamically Add Images React Webpack

You do not embed the images in the bundle. They are called through the browser. So its;

var imgSrc = './image/image1.jpg';

return <img src={imgSrc} />

Splitting a dataframe string column into multiple different columns

A very direct way is to just use read.table on your character vector:

> read.table(text = text, sep = ".", colClasses = "character")
   V1 V2  V3  V4
1   F US CLE V13
2   F US CA6 U13
3   F US CA6 U13
4   F US CA6 U13
5   F US CA6 U13
6   F US CA6 U13
7   F US CA6 U13
8   F US CA6 U13
9   F US  DL U13
10  F US  DL U13
11  F US  DL U13
12  F US  DL Z13
13  F US  DL Z13

colClasses needs to be specified, otherwise F gets converted to FALSE (which is something I need to fix in "splitstackshape", otherwise I would have recommended that :) )


Update (> a year later)...

Alternatively, you can use my cSplit function, like this:

cSplit(as.data.table(text), "text", ".")
#     text_1 text_2 text_3 text_4
#  1:      F     US    CLE    V13
#  2:      F     US    CA6    U13
#  3:      F     US    CA6    U13
#  4:      F     US    CA6    U13
#  5:      F     US    CA6    U13
#  6:      F     US    CA6    U13
#  7:      F     US    CA6    U13
#  8:      F     US    CA6    U13
#  9:      F     US     DL    U13
# 10:      F     US     DL    U13
# 11:      F     US     DL    U13
# 12:      F     US     DL    Z13
# 13:      F     US     DL    Z13

Or, separate from "tidyr", like this:

library(dplyr)
library(tidyr)

as.data.frame(text) %>% separate(text, into = paste("V", 1:4, sep = "_"))
#    V_1 V_2 V_3 V_4
# 1    F  US CLE V13
# 2    F  US CA6 U13
# 3    F  US CA6 U13
# 4    F  US CA6 U13
# 5    F  US CA6 U13
# 6    F  US CA6 U13
# 7    F  US CA6 U13
# 8    F  US CA6 U13
# 9    F  US  DL U13
# 10   F  US  DL U13
# 11   F  US  DL U13
# 12   F  US  DL Z13
# 13   F  US  DL Z13

How do you see recent SVN log entries?

In case anybody is looking at this old question, a handy command to see the changes since your last update:

svn log -r $(svn info | grep Revision | cut -f 2 -d ' '):HEAD -v

LE (thanks Gary for the comment)
same thing, but much shorter and more logical:

svn log -r BASE:HEAD -v

JPA and Hibernate - Criteria vs. JPQL or HQL

HQL is much easier to read, easier to debug using tools like the Eclipse Hibernate plugin, and easier to log. Criteria queries are better for building dynamic queries where a lot of the behavior is determined at runtime. If you don't know SQL, I could understand using Criteria queries, but overall I prefer HQL if I know what I want upfront.

What does "|=" mean? (pipe equal operator)

|= reads the same way as +=.

notification.defaults |= Notification.DEFAULT_SOUND;

is the same as

notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;

where | is the bit-wise OR operator.

All operators are referenced here.

A bit-wise operator is used because, as is frequent, those constants enable an int to carry flags.

If you look at those constants, you'll see that they're in powers of two :

public static final int DEFAULT_SOUND = 1;
public static final int DEFAULT_VIBRATE = 2; // is the same than 1<<1 or 10 in binary
public static final int DEFAULT_LIGHTS = 4; // is the same than 1<<2 or 100 in binary

So you can use bit-wise OR to add flags

int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // same as 001 | 010, producing 011

so

myFlags |= DEFAULT_LIGHTS;

simply means we add a flag.

And symmetrically, we test a flag is set using & :

boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;

How to increment a number by 2 in a PHP For Loop

Another simple solution with +=:

$y = 1;

for ($x = $y; $x <= 15; $y++) {
  printf("The number of first paragraph is: $y <br>");
  printf("The number of second paragraph is: $x+=2 <br>");
} 

How do I add more members to my ENUM-type column in MySQL?

In MYSQL server version: 5.0.27 i tried this and it worked fine for me check in your version

ALTER TABLE carmake
     MODIFY `country` ENUM('Japan', 'USA', 'England', 'Australia', 'Germany', 'France', 'Italy', 'Spain', 'Czech Republic', 'China', 'South Korea', 'India', 'Sweden', 'Malaysia');

Delete last char of string

strgroupids = strgroupids.Remove(strgroupids.Length - 1);

MSDN:

String.Remove(Int32):

Deletes all the characters from this string beginning at a specified position and continuing through the last position

If statement with String comparison fails

You can use

if("/quit".equals(s))
   ...

or

if("/quit".compareTo(s) == 0) 
    ...

The latter makes a lexicographic comparison, and will return 0 if the two strings are the same.

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

How to Configure SSL for Amazon S3 bucket

Custom domain SSL certs were just added today for $600/cert/month. Sign up for your invite below: http://aws.amazon.com/cloudfront/custom-ssl-domains/

Update: SNI customer provided certs are now available for no additional charge. Much cheaper than $600/mo, and with XP nearly killed off, it should work well for most use cases.

@skalee AWS has a mechanism for achieving what the poster asks for, "implement SSL for an Amazon s3 bucket", it's called CloudFront. I'm reading "implement" as "use my SSL certs," not "just put an S on the HTTP URL which I'm sure the OP could have surmised.

Since CloudFront costs exactly the same as S3 ($0.12/GB), but has a ton of additional features around SSL AND allows you to add your own SNI cert at no additional cost, it's the obvious fix for "implementing SSL" on your domain.

Export to csv/excel from kibana

I totally missed the export button at the bottom of each visualization. As for read only access...Shield from Elasticsearch might be worth exploring.

comparing two strings in ruby

Comparison of strings is very easy in Ruby:

v1 = "string1"
v2 = "string2"
puts v1 == v2 # prints false
puts "hello"=="there" # prints false
v1 = "string2"
puts v1 == v2 # prints true

Make sure your var2 is not an array (which seems to be like)

Member '<method>' cannot be accessed with an instance reference

You can only access static members using the name of the type.

Therefore, you need to either write,

MyClass.MyItem.Property1

Or (this is probably what you need to do) make Property1 an instance property by removing the static keyword from its definition.

Static properties are shared between all instances of their class, so that they only have one value. The way it's defined now, there is no point in making any instances of your MyItem class.

What is the difference between public, protected, package-private and private in Java?

  • public - accessible from anywhere in the application.

  • default - accessible from package.

  • protected - accessible from package and sub-classes in other package. as well

  • private - accessible from its class only.

CSS align images and text on same line

See example at: http://jsfiddle.net/6Rpkh/

<style>
img.likeordisklike { height: 24px; width: 24px; margin-right: 4px; }
h4.liketext { color:#F00; display:inline }
?</style>

<img class='likeordislike' src='design/like.png'/><h4 class='liketext'>$likes</h4>
<img class='likeordislike' src='design/dislike.png'/><h4 class='liketext'>$dislikes</h4>

?

SQLite3 database or disk is full / the database disk image is malformed

while using Google App Engine, i had this problem. For some reason i did following since then Google App Engine was never starting.

$ echo '' > /tmp/appengine.apprtc.root/*.db

To fix it i required to do manually:

$ sqlite3 datastore.db
sqlite> begin immediate;
<press CTRL+Z>
$ cp datastore.db logs.db

And then run the Google App Engine with flag:

$ dev_appserver.py --clear_datastore --clear_search_index

after that it finally worked.

Entry point for Java applications: main(), init(), or run()?

The main() method is the entry point for a Java application. run() is typically used for new threads or tasks.

Where have you been writing a run() method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?

How to create a circle icon button in Flutter?

You can also use a RaisedButton with an image inside (for example for social login) like this (sizedbox with fittebox is needed to contraint the image on the specified size):

FittedBox(
    fit: BoxFit.scaleDown,
    child: SizedBox(
        height: 60,
        width: 60,
        child: RaisedButton(
             child: Image.asset(
                 'assets/images/google_logo.png'),
                 shape: StadiumBorder(),
                 color: Colors.white,
                     onPressed: () {},
                 ),
             ),
         ),

Split string and get first value only

These are the two options I managed to build, not having the luxury of working with var type, nor with additional variables on the line:

string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);

string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);

This is what it gets:

enter image description here

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

How do I navigate to a parent route from a child route?

This seems to work for me as of Spring 2017:

goBack(): void {
  this.router.navigate(['../'], { relativeTo: this.route });
}

Where your component ctor accepts ActivatedRoute and Router, imported as follows:

import { ActivatedRoute, Router } from '@angular/router';

what is Promotional and Feature graphic in Android Market/Play Store?

Promo graphic

The promo graphic is used for promotions on older versions of the Android OS (earlier than 4.0). This image is not required to submit an update for your Store Listing.

Requirements

  • JPG or 24-bit PNG (no alpha)
  • Dimensions: 180px by 120px

https://support.google.com/googleplay/android-developer/answer/1078870

How to perform a fade animation on Activity transition?

you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...

View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);

Calling Web API from MVC controller

Its very late here but thought to share below code. If we have our WebApi as a different project altogether in the same solution then we can call the same from MVC controller like below

public class ProductsController : Controller
    {
        // GET: Products
        public async Task<ActionResult> Index()
        {
            string apiUrl = "http://localhost:58764/api/values";

            using (HttpClient client=new HttpClient())
            {
                client.BaseAddress = new Uri(apiUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync(apiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsStringAsync();
                    var table = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(data);

                }


            }
            return View();

        }
    }

Nginx serves .php files as downloads, instead of executing them

I was about to go mental trying to fix this, for me the issue was that Cloudflare had cached the php file and kept making me download it.

The fix for me was to purge the cache on Cloudflare.

Mailto on submit button

In HTML you can specify a mailto: address in the <form> element's [action] attribute.

<form action="mailto:[email protected]" method="GET">
    <input name="subject" type="text" />
    <textarea name="body"></textarea>
    <input type="submit" value="Send" />
</form>

What this will do is allow the user's email client to create an email prepopulated with the fields in the <form>.

What this will not do is send an email.

Creating a select box with a search option

Full option searchable select box

This also supports Control buttons keyboards such as ArrowDown ArrowUp and Enter keys

_x000D_
_x000D_
function filterFunction(that, event) {_x000D_
    let container, input, filter, li, input_val;_x000D_
    container = $(that).closest(".searchable");_x000D_
    input_val = container.find("input").val().toUpperCase();_x000D_
_x000D_
    if (["ArrowDown", "ArrowUp", "Enter"].indexOf(event.key) != -1) {_x000D_
        keyControl(event, container)_x000D_
    } else {_x000D_
        li = container.find("ul li");_x000D_
        li.each(function (i, obj) {_x000D_
            if ($(this).text().toUpperCase().indexOf(input_val) > -1) {_x000D_
                $(this).show();_x000D_
            } else {_x000D_
                $(this).hide();_x000D_
            }_x000D_
        });_x000D_
_x000D_
        container.find("ul li").removeClass("selected");_x000D_
        setTimeout(function () {_x000D_
            container.find("ul li:visible").first().addClass("selected");_x000D_
        }, 100)_x000D_
    }_x000D_
}_x000D_
_x000D_
function keyControl(e, container) {_x000D_
    if (e.key == "ArrowDown") {_x000D_
_x000D_
        if (container.find("ul li").hasClass("selected")) {_x000D_
            if (container.find("ul li:visible").index(container.find("ul li.selected")) + 1 < container.find("ul li:visible").length) {_x000D_
                container.find("ul li.selected").removeClass("selected").nextAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
            }_x000D_
_x000D_
        } else {_x000D_
            container.find("ul li:first-child").addClass("selected");_x000D_
        }_x000D_
_x000D_
    } else if (e.key == "ArrowUp") {_x000D_
_x000D_
        if (container.find("ul li:visible").index(container.find("ul li.selected")) > 0) {_x000D_
            container.find("ul li.selected").removeClass("selected").prevAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
        }_x000D_
    } else if (e.key == "Enter") {_x000D_
        container.find("input").val(container.find("ul li.selected").text()).blur();_x000D_
        onSelect(container.find("ul li.selected").text())_x000D_
    }_x000D_
_x000D_
    container.find("ul li.selected")[0].scrollIntoView({_x000D_
        behavior: "smooth",_x000D_
    });_x000D_
}_x000D_
_x000D_
function onSelect(val) {_x000D_
    alert(val)_x000D_
}_x000D_
_x000D_
$(".searchable input").focus(function () {_x000D_
    $(this).closest(".searchable").find("ul").show();_x000D_
    $(this).closest(".searchable").find("ul li").show();_x000D_
});_x000D_
$(".searchable input").blur(function () {_x000D_
    let that = this;_x000D_
    setTimeout(function () {_x000D_
        $(that).closest(".searchable").find("ul").hide();_x000D_
    }, 300);_x000D_
});_x000D_
_x000D_
$(document).on('click', '.searchable ul li', function () {_x000D_
    $(this).closest(".searchable").find("input").val($(this).text()).blur();_x000D_
    onSelect($(this).text())_x000D_
});_x000D_
_x000D_
$(".searchable ul li").hover(function () {_x000D_
    $(this).closest(".searchable").find("ul li.selected").removeClass("selected");_x000D_
    $(this).addClass("selected");_x000D_
});
_x000D_
div.searchable {_x000D_
    width: 300px;_x000D_
    float: left;_x000D_
    margin: 0 15px;_x000D_
}_x000D_
_x000D_
.searchable input {_x000D_
    width: 100%;_x000D_
    height: 50px;_x000D_
    font-size: 18px;_x000D_
    padding: 10px;_x000D_
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */_x000D_
    -moz-box-sizing: border-box; /* Firefox, other Gecko */_x000D_
    box-sizing: border-box; /* Opera/IE 8+ */_x000D_
    display: block;_x000D_
    font-weight: 400;_x000D_
    line-height: 1.6;_x000D_
    color: #495057;_x000D_
    background-color: #fff;_x000D_
    background-clip: padding-box;_x000D_
    border: 1px solid #ced4da;_x000D_
    border-radius: .25rem;_x000D_
    transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;_x000D_
    background: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .75rem center/8px 10px;_x000D_
}_x000D_
_x000D_
.searchable ul {_x000D_
    display: none;_x000D_
    list-style-type: none;_x000D_
    background-color: #fff;_x000D_
    border-radius: 0 0 5px 5px;_x000D_
    border: 1px solid #add8e6;_x000D_
    border-top: none;_x000D_
    max-height: 180px;_x000D_
    margin: 0;_x000D_
    overflow-y: scroll;_x000D_
    overflow-x: hidden;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
.searchable ul li {_x000D_
    padding: 7px 9px;_x000D_
    border-bottom: 1px solid #e1e1e1;_x000D_
    cursor: pointer;_x000D_
    color: #6e6e6e;_x000D_
}_x000D_
_x000D_
.searchable ul li.selected {_x000D_
    background-color: #e8e8e8;_x000D_
    color: #333;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="searchable">_x000D_
    <input type="text" placeholder="search countries" onkeyup="filterFunction(this,event)">_x000D_
    <ul>_x000D_
        <li>Algeria</li>_x000D_
        <li>Bulgaria</li>_x000D_
        <li>Canada</li>_x000D_
        <li>Egypt</li>_x000D_
        <li>Fiji</li>_x000D_
        <li>India</li>_x000D_
        <li>Japan</li>_x000D_
        <li>Iran (Islamic Republic of)</li>_x000D_
        <li>Lao People's Democratic Republic</li>_x000D_
        <li>Micronesia (Federated States of)</li>_x000D_
        <li>Nicaragua</li>_x000D_
        <li>Senegal</li>_x000D_
        <li>Tajikistan</li>_x000D_
        <li>Yemen</li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

String parsing in Java with delimiter tab "\t" using split

String.split implementations will have serious limitations if the data in a tab-delimited field itself contains newline, tab and possibly " characters.

TAB-delimited formats have been around for donkey's years, but format is not standardised and varies. Many implementations don't escape characters (newlines and tabs) appearing within a field. Rather, they follow CSV conventions and wrap any non-trivial fields in "double quotes". Then they escape only double-quotes. So a "line" could extend over multiple lines.

Reading around I heard "just reuse apache tools", which sounds like good advice.

In the end I personally chose opencsv. I found it light-weight, and since it provides options for escape and quote characters it should cover most popular comma- and tab- delimited data formats.

Example:

CSVReader tabFormatReader = new CSVReader(new FileReader("yourfile.tsv"), '\t');

jQuery UI Sortable Position

You can use the ui object provided to the events, specifically you want the stop event, the ui.item property and .index(), like this:

$("#sortable").sortable({
    stop: function(event, ui) {
        alert("New position: " + ui.item.index());
    }
});

You can see a working demo here, remember the .index() value is zero-based, so you may want to +1 for display purposes.

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

I've extended vokimon's answer a bit, making it a bit more convenient for changing other properties as well.

function customIcon (opts) {
  return Object.assign({
    path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z M -2,-30 a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0',
    fillColor: '#34495e',
    fillOpacity: 1,
    strokeColor: '#000',
    strokeWeight: 2,
    scale: 1,
  }, opts);
}

Usage:

marker.setIcon(customIcon({
  fillColor: '#fff',
  strokeColor: '#000'
}));

Or when defining a new marker:

const marker = new google.maps.Marker({
  position: {
    lat: ...,
    lng: ...
  },
  icon: customIcon({
    fillColor: '#2ecc71'
  }),
  map: map
});

Variable not accessible when initialized outside function

Declare systemStatus in an outer scope and assign it in an onload handler.

systemStatus = null;

function onloadHandler(evt) {
    systemStatus = document.getElementById("....");
}

Or if you don't want the onload handler, put your script tag at the bottom of your HTML.

Finding first blank row, then writing to it

I know this is an older thread however I needed to write a function that returned the first blank row WITHIN a range. All of the code I found online actually searches the entire row (even the cells outside of the range) for a blank row. Data in ranges outside the search range was triggering a used row. This seemed to me to be a simple solution:

Function FirstBlankRow(ByVal rngToSearch As Range) As Long
   Dim R As Range
   Dim C As Range
   Dim RowIsBlank As Boolean

   For Each R In rngToSearch.Rows
      RowIsBlank = True
      For Each C In R.Cells
         If IsEmpty(C.Value) = False Then RowIsBlank = False
      Next C
      If RowIsBlank Then
         FirstBlankRow = R.Row
         Exit For
      End If
   Next R
End Function

Finding Variable Type in JavaScript

In Javascript you can do that by using the typeof function

function foo(bar){
  alert(typeof(bar));
}

Cmake doesn't find Boost

Are you sure you are doing it the correct way? The idea is that CMake sets BOOST_INCLUDE_DIR, BOOST_LIBRARYDIR and BOOST_ROOT automatically. Do something like this in CMakeLists.txt:

FIND_PACKAGE(Boost)
IF (Boost_FOUND)
    INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
    ADD_DEFINITIONS( "-DHAS_BOOST" )
ENDIF()

If boost is not installed in a default location and can, thus, not be found by CMake, you can tell CMake where to look for boost like this:

SET(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "C:/win32libs/boost")
SET(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "C:/win32libs/boost/lib")

Of course, those two lines have to be before the FIND_PACKAGE(Boost) in CMakeLists.txt.

set up device for development (???????????? no permissions)

For those using debian, the guide for setting up a device under Ubuntu to create the file "/etc/udev/rules.d/51-android.rules" does not work. I followed instructions from here. Putting down the same here for reference.

Edit this file as superuser

sudo nano /lib/udev/rules.d/91-permissions.rules

Find the text similar to this

# usbfs-like devices 
SUBSYSTEM==”usb”, ENV{DEVTYPE}==”usb_device”, \ MODE=”0664"

Then change the mode to 0666 like below

# usbfs-like devices 
SUBSYSTEM==”usb”, ENV{DEVTYPE}==”usb_device”, \ MODE=”0666"

This allows adb to work, however we still need to set up the device so it can be recognized. We need to create this file as superuser,

sudo nano /lib/udev/rules.d/99-android.rules

and enter

SUBSYSTEM==”usb”, ENV{DEVTYPE}==”usb_device”, ATTRS{idVendor}==”0bb4", MODE=”0666"

the above line is for HTC, follow @grebulon's post for complete list.

Save the file and then restart udev as super user

sudo /etc/init.d/udev restart

Connect the phone via USB and it should be detected when you compile and run a project.

Convert a negative number to a positive one in JavaScript

What about x *= -1? I like its simplicity.

Convert javascript object or array to json for ajax data

You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}

To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:

// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        return oldJSONStringify(convArrToObj(input));
    };
})();

And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)


Edit:

Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):

(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

jsFiddle with example here

js Performance test here, via jsPerf

How to toggle (hide / show) sidebar div using jQuery

This help to hide and show the sidebar, and the content take place of the empty space left by the sidebar.

<div id="A">Sidebar</div>
<div id="B"><button>toggle</button>
Content here: Bla, bla, bla
</div>


//Toggle Hide/Show sidebar slowy
  $(document).ready(function(){
      $('#B').click(function(e) {
          e.preventDefault();
          $('#A').toggle('slow');
          $('#B').toggleClass('extended-panel'); 
      });
  }); 


html, body {
    margin: 0;
    padding: 0;
    border: 0;
}
#A, #B {
    position: absolute;
}
#A {
    top: 0px;
    width: 200px;
    bottom: 0px;
    background:orange;
}
#B {
    top: 0px;
    left: 200px;
    right: 0;
    bottom: 0px;
    background:green;
}

/* makes the content take place of the SIDEBAR 
   which is empty when is hided */
.extended-panel {
  left: 0px !important;
}

Python error "ImportError: No module named"

I faced the same problem: Import error. In addition the library've been installed 100% correctly. The source of the problem was that on my PC 3 version of python (anaconda packet) have been installed). This is why the library was installed no to the right place. After that I just changed to the proper version of python in the my IDE PyCharm.

What is the difference between 'java', 'javaw', and 'javaws'?

From http://publib.boulder.ibm.com/infocenter/javasdk/v6r0/index.jsp?topic=%2Fcom.ibm.java.doc.user.aix32.60%2Fuser%2Fjava.html:

The javaw command is identical to java, except that javaw has no associated console window. Use javaw when you do not want a command prompt window to be displayed. The javaw launcher displays a window with error information if it fails.

And javaws is for Java web start applications, applets, or something like that, I would suspect.

Convert a file path to Uri in Android

Below code works fine before 18 API :-

public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( contentUri,
                        proj, // Which columns to return
                        null,       // WHERE clause; which rows to return (all rows)
                        null,       // WHERE clause selection arguments (none)
                        null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
}

below code use on kitkat :-

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

see below link for more info:-

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

How can I use random numbers in groovy?

Generate pseudo random numbers between 1 and an [UPPER_LIMIT]

You can use the following to generate a number between 1 and an upper limit.

Math.abs(new Random().nextInt() % [UPPER_LIMIT]) + 1

Here is a specific example:

Example - Generate pseudo random numbers in the range 1 to 600:

Math.abs(new Random().nextInt() % 600) + 1

This will generate a random number within a range for you. In this case 1-600. You can change the value 600 to anything you need in the range of integers.


Generate pseudo random numbers between a [LOWER_LIMIT] and an [UPPER_LIMIT]

If you want to use a lower bound that is not equal to 1 then you can use the following formula.

Math.abs(new Random().nextInt() % ([UPPER_LIMIT] - [LOWER_LIMIT])) + [LOWER_LIMIT]

Here is a specific example:

Example - Generate pseudo random numbers in the range of 40 to 99:

Math.abs( new Random().nextInt() % (99 - 40) ) + 40

This will generate a random number within a range of 40 and 99.

Correct way to create rounded corners in Twitter Bootstrap

As per bootstrap 3.0 documentation. there is no rounded corners class or id for div tag.

you can use circle behavior for image by using

<img class="img-circle"> 

or just use custom border-radius css3 property in css

for only bottom rounded coner use following

border-bottom-left-radius:25%; // i use percentage  u can use pix.
border-bottom-right-radius:25%;// i use percentage  u can use pix.

if you want responsive circular div then try this

referred from Responsive CSS Circles

How to reload page every 5 seconds?

 <meta http-equiv="refresh" content="5; URL=http://www.yourdomain.com/yoursite.html">

If it has to be in the script use setTimeout like:

setTimeout(function(){
   window.location.reload(1);
}, 5000);

iOS - UIImageView - how to handle UIImage image orientation

Swift 3.1

func fixImageOrientation(_ image: UIImage)->UIImage {
    UIGraphicsBeginImageContext(image.size)
    image.draw(at: .zero)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage ?? image
}

How to hide Soft Keyboard when activity starts

In the AndroidManifest.xml:

<activity android:name="com.your.package.ActivityName"
          android:windowSoftInputMode="stateHidden"  />

or try

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)??;

Please check this also

Should import statements always be at the top of a module?

Module initialization only occurs once - on the first import. If the module in question is from the standard library, then you will likely import it from other modules in your program as well. For a module as prevalent as datetime, it is also likely a dependency for a slew of other standard libraries. The import statement would cost very little then since the module intialization would have happened already. All it is doing at this point is binding the existing module object to the local scope.

Couple that information with the argument for readability and I would say that it is best to have the import statement at module scope.

Confirm deletion in modal / dialog using Twitter Bootstrap?

You can try more reusable my solution with callback function. In this function you can use POST request or some logic. Used libraries: JQuery 3> and Bootstrap 3>.

https://jsfiddle.net/axnikitenko/gazbyv8v/

Html code for test:

...
<body>
    <a href='#' id="remove-btn-a-id" class="btn btn-default">Test Remove Action</a>
</body>
...

Javascript:

$(function () {
    function remove() {
        alert('Remove Action Start!');
    }
    // Example of initializing component data
    this.cmpModalRemove = new ModalConfirmationComponent('remove-data', remove,
        'remove-btn-a-id', {
            txtModalHeader: 'Header Text For Remove', txtModalBody: 'Body For Text Remove',
            txtBtnConfirm: 'Confirm', txtBtnCancel: 'Cancel'
        });
    this.cmpModalRemove.initialize();
});

//----------------------------------------------------------------------------------------------------------------------
// COMPONENT SCRIPT
//----------------------------------------------------------------------------------------------------------------------
/**
 * Script processing data for confirmation dialog.
 * Used libraries: JQuery 3> and Bootstrap 3>.
 *
 * @param name unique component name at page scope
 * @param callback function which processing confirm click
 * @param actionBtnId button for open modal dialog
 * @param text localization data, structure:
 *              > txtModalHeader - text at header of modal dialog
 *              > txtModalBody - text at body of modal dialog
 *              > txtBtnConfirm - text at button for confirm action
 *              > txtBtnCancel - text at button for cancel action
 *
 * @constructor
 * @author Aleksey Nikitenko
 */
function ModalConfirmationComponent(name, callback, actionBtnId, text) {
    this.name = name;
    this.callback = callback;
    // Text data
    this.txtModalHeader =   text.txtModalHeader;
    this.txtModalBody =     text.txtModalBody;
    this.txtBtnConfirm =    text.txtBtnConfirm;
    this.txtBtnCancel =     text.txtBtnCancel;
    // Elements
    this.elmActionBtn = $('#' + actionBtnId);
    this.elmModalDiv = undefined;
    this.elmConfirmBtn = undefined;
}

/**
 * Initialize needed data for current component object.
 * Generate html code and assign actions for needed UI
 * elements.
 */
ModalConfirmationComponent.prototype.initialize = function () {
    // Generate modal html and assign with action button
    $('body').append(this.getHtmlModal());
    this.elmActionBtn.attr('data-toggle', 'modal');
    this.elmActionBtn.attr('data-target', '#'+this.getModalDivId());
    // Initialize needed elements
    this.elmModalDiv =  $('#'+this.getModalDivId());
    this.elmConfirmBtn = $('#'+this.getConfirmBtnId());
    // Assign click function for confirm button
    var object = this;
    this.elmConfirmBtn.click(function() {
        object.elmModalDiv.modal('toggle'); // hide modal
        object.callback(); // run callback function
    });
};

//----------------------------------------------------------------------------------------------------------------------
// HTML GENERATORS
//----------------------------------------------------------------------------------------------------------------------
/**
 * Methods needed for get html code of modal div.
 *
 * @returns {string} html code
 */
ModalConfirmationComponent.prototype.getHtmlModal = function () {
    var result = '<div class="modal fade" id="' + this.getModalDivId() + '"';
    result +=' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">';
    result += '<div class="modal-dialog"><div class="modal-content"><div class="modal-header">';
    result += this.txtModalHeader + '</div><div class="modal-body">' + this.txtModalBody + '</div>';
    result += '<div class="modal-footer">';
    result += '<button type="button" class="btn btn-default" data-dismiss="modal">';
    result += this.txtBtnCancel + '</button>';
    result += '<button id="'+this.getConfirmBtnId()+'" type="button" class="btn btn-danger">';
    result += this.txtBtnConfirm + '</button>';
    return result+'</div></div></div></div>';
};

//----------------------------------------------------------------------------------------------------------------------
// UTILITY
//----------------------------------------------------------------------------------------------------------------------
/**
 * Get id element with name prefix for this component.
 *
 * @returns {string} element id
 */
ModalConfirmationComponent.prototype.getModalDivId = function () {
    return this.name + '-modal-id';
};

/**
 * Get id element with name prefix for this component.
 *
 * @returns {string} element id
 */
ModalConfirmationComponent.prototype.getConfirmBtnId = function () {
    return this.name + '-confirm-btn-id';
};

Running Node.Js on Android

You can use Node.js for Mobile Apps.

It works on Android devices and simulators, with pre-built binaries for armeabi-v7a, x86, arm64-v8a, x86_64. It also works on iOS, though that's outside the scope of this question.

Like JXcore, it is used to host a Node.js engine in the same process as the app, in a dedicated thread. Unlike JXcore, it is basically pure Node.js, built as a library, with a few portability fixes to run on Android. This means that it's much easier to keep the project up to date with mainline Node.js.

Plugins for Cordova and React Native are also available. The plugins provide a communication layer between the JavaScript side of those frameworks and the Node.js side. They also simplify development by taking care of a few things automatically, like packaging modules and cross-compiling native modules at build time.

Full disclosure: I work for the company that develops Node.js for Mobile Apps.

Limit the height of a responsive image with css

I set the below 3 styles to my img tag

max-height: 500px;
height: 70%;
width: auto;

What it does that for desktop screen img doesn't grow beyond 500px but for small mobile screens, it will shrink to 70% of the outer container. Works like a charm.

It also works width property.

How to ignore whitespace in a regular expression subject string?

While the accepted answer is technically correct, a more practical approach, if possible, is to just strip whitespace out of both the regular expression and the search string.

If you want to search for "my cats", instead of:

myString.match(/m\s*y\s*c\s*a\*st\s*s\s*/g)

Just do:

myString.replace(/\s*/g,"").match(/mycats/g)

Warning: You can't automate this on the regular expression by just replacing all spaces with empty strings because they may occur in a negation or otherwise make your regular expression invalid.

Context.startForegroundService() did not then call Service.startForeground()

Service

class TestService : Service() {

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "onCreate")

        val nBuilder = NotificationCompat.Builder(this, "all")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("TestService")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        startForeground(1337, nBuilder.build())
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val rtn = super.onStartCommand(intent, flags, startId)

        if (intent?.action == STOP_ACTION) {
            Log.d(TAG, "onStartCommand -> STOP")
            stopForeground(true)
            stopSelf()
        } else {
            Log.d(TAG, "onStartCommand -> START")
        }

        return rtn
    }

    override fun onDestroy() {
        Log.d(TAG, "onDestroy")
        super.onDestroy()
    }

    override fun onBind(intent: Intent?): IBinder? = null

    companion object {

        private val TAG = "TestService"
        private val STOP_ACTION = "ly.zen.test.TestService.ACTION_STOP"

        fun start(context: Context) {
            ContextCompat.startForegroundService(context, Intent(context, TestService::class.java))
        }

        fun stop(context: Context) {
            val intent = Intent(context, TestService::class.java)
            intent.action = STOP_ACTION
            ContextCompat.startForegroundService(context, intent)
        }

    }

}

Tester

val nChannel = NotificationChannel("all", "All", NotificationManager.IMPORTANCE_NONE)
val nManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nManager.createNotificationChannel(nChannel)

start_test_service.setOnClickListener {
    TestService.start(this@MainActivity)
    TestService.stop(this@MainActivity)
}

Result

D/TestService: onCreate
D/TestService: onStartCommand -> START
D/TestService: onStartCommand -> STOP
D/TestService: onDestroy

insert datetime value in sql database with c#

This is an older question with a proper answer (please use parameterized queries) which I'd like to extend with some timezone discussion. For my current project I was interested in how do the datetime columns handle timezones and this question is the one I found.

Turns out, they do not, at all.

datetime column stores the given DateTime as is, without any conversion. It does not matter if the given datetime is UTC or local.

You can see for yourself:

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "SELECT * FROM (VALUES (@a, @b, @c)) example(a, b, c);";

        var local = DateTime.Now;
        var utc = local.ToUniversalTime();

        command.Parameters.AddWithValue("@a", utc);
        command.Parameters.AddWithValue("@b", local);
        command.Parameters.AddWithValue("@c", utc.ToLocalTime());

        using (var reader = command.ExecuteReader())
        {
            reader.Read();

            var localRendered = local.ToString("o");

            Console.WriteLine($"a = {utc.ToString("o").PadRight(localRendered.Length, ' ')} read = {reader.GetDateTime(0):o}, {reader.GetDateTime(0).Kind}");
            Console.WriteLine($"b = {local:o} read = {reader.GetDateTime(1):o}, {reader.GetDateTime(1).Kind}");
            Console.WriteLine($"{"".PadRight(localRendered.Length + 4, ' ')} read = {reader.GetDateTime(2):o}, {reader.GetDateTime(2).Kind}");
        }
    }
}

What this will print will of course depend on your time zone but most importantly the read values will all have Kind = Unspecified. The first and second output line will be different by your timezone offset. Second and third will be the same. Using the "o" format string (roundtrip) will not show any timezone specifiers for the read values.

Example output from GMT+02:00:

a = 2018-11-20T10:17:56.8710881Z      read = 2018-11-20T10:17:56.8700000, Unspecified
b = 2018-11-20T12:17:56.8710881+02:00 read = 2018-11-20T12:17:56.8700000, Unspecified
                                      read = 2018-11-20T12:17:56.8700000, Unspecified

Also note of how the data gets truncated (or rounded) to what seems like 10ms.

SQL Server : Transpose rows to columns

SQL Server has a PIVOT command that might be what you are looking for.

select * from Tag
pivot (MAX(Value) for TagID in ([A1],[A2],[A3],[A4])) as TagTime;

If the columns are not constant, you'll have to combine this with some dynamic SQL.

DECLARE @columns AS VARCHAR(MAX);
DECLARE @sql AS VARCHAR(MAX);

select @columns = substring((Select DISTINCT ',' + QUOTENAME(TagID) FROM Tag FOR XML PATH ('')),2, 1000);

SELECT @sql =

'SELECT *
FROM TAG
PIVOT 
(
  MAX(Value) 
  FOR TagID IN( ' + @columns + ' )) as TagTime;';

 execute(@sql);

Combine GET and POST request methods in Spring

@RequestMapping(value = "/books", method = { RequestMethod.GET, 
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
     HttpServletRequest request) 
    throws ParseException {

//your code 
}

This will works for both GET and POST.

For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter

like below

public class BooksFilter{

private String parameter1;
private String parameter2;

   //getters and setters

URl should be like below

/books?parameter1=blah

Like this way u can use it for both GET and POST

Android studio, gradle and NDK

Just add this lines to app build.gradle

dependencies {
    ...
    compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
}

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/armeabi/'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I've created a new scheme based on my current app.config to get the messages to disappear. I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me.

Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

Can I try/catch a warning?

I would only recommend using @ to suppress warnings when it's a straight forward operation (e.g. $prop = @($high/($width - $depth)); to skip division by zero warnings). However in most cases it's better to handle.

When should I use the new keyword in C++?

The second method creates the instance on the stack, along with such things as something declared int and the list of parameters that are passed into the function.

The first method makes room for a pointer on the stack, which you've set to the location in memory where a new MyClass has been allocated on the heap - or free store.

The first method also requires that you delete what you create with new, whereas in the second method, the class is automatically destructed and freed when it falls out of scope (the next closing brace, usually).

XPath to get all child nodes (elements, comments, and text) without parent

From the documentation of XPath ( http://www.w3.org/TR/xpath/#location-paths ):

child::* selects all element children of the context node

child::text() selects all text node children of the context node

child::node() selects all the children of the context node, whatever their node type

So I guess your answer is:

$doc/PRESENTEDIN/X/child::node()

And if you want a flatten array of all nested nodes:

$doc/PRESENTEDIN/X/descendant::node()

calling server side event from html button control

Please follow this tutorial: http://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-javascript/

On a sidenote: ASP.NET generates a client side javascript function that you can call from your own functions to perform the postback you want.

-- More info on hijacking the postback event:

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

Might it be possible that you're using a WCF-based web service reference? By default, the ServiceThrottlingBehavior.MaxConcurrentCalls is 16.

You could try updating your service reference behavior's <serviceThrottling> element

<serviceThrottling
    maxConcurrentCalls="999" 
    maxConcurrentSessions="999" 
    maxConcurrentInstances="999" />

(Note that I'd recommend the settings above.) See MSDN for more information how to configure an appropriate <behavior> element.

incompatible character encodings: ASCII-8BIT and UTF-8

Try to find the exact line which causing this problem and then enforce UTF8 coding, this solution worked for me.

title.to_s.force_encoding("UTF-8")

Why do we assign a parent reference to the child object in Java?

You declare parent as Parent, so java will provide only methods and attributes of the Parent class.

Child child = new Child();

should work. Or

Parent child = new Child();
((Child)child).salary = 1;

What's the difference between lists and tuples?

Difference between list and tuple

  1. Literal

    someTuple = (1,2)
    someList  = [1,2] 
    
  2. Size

    a = tuple(range(1000))
    b = list(range(1000))
    
    a.__sizeof__() # 8024
    b.__sizeof__() # 9088
    

    Due to the smaller size of a tuple operation, it becomes a bit faster, but not that much to mention about until you have a huge number of elements.

  3. Permitted operations

    b    = [1,2]   
    b[0] = 3       # [3, 2]
    
    a    = (1,2)
    a[0] = 3       # Error
    

    That also means that you can't delete an element or sort a tuple. However, you could add a new element to both list and tuple with the only difference that since the tuple is immutable, you are not really adding an element but you are creating a new tuple, so the id of will change

    a     = (1,2)
    b     = [1,2]  
    
    id(a)          # 140230916716520
    id(b)          # 748527696
    
    a   += (3,)    # (1, 2, 3)
    b   += [3]     # [1, 2, 3]
    
    id(a)          # 140230916878160
    id(b)          # 748527696
    
  4. Usage

    As a list is mutable, it can't be used as a key in a dictionary, whereas a tuple can be used.

    a    = (1,2)
    b    = [1,2] 
    
    c = {a: 1}     # OK
    c = {b: 1}     # Error
    

Alternative to mysql_real_escape_string without connecting to DB

In direct opposition to my other answer, this following function is probably safe, even with multi-byte characters.

// replace any non-ascii character with its hex code.
function escape($value) {
    $return = '';
    for($i = 0; $i < strlen($value); ++$i) {
        $char = $value[$i];
        $ord = ord($char);
        if($char !== "'" && $char !== "\"" && $char !== '\\' && $ord >= 32 && $ord <= 126)
            $return .= $char;
        else
            $return .= '\\x' . dechex($ord);
    }
    return $return;
}

I'm hoping someone more knowledgeable than myself can tell me why the code above won't work ...

What is the purpose of the return statement?

return means, "output this value from this function".

print means, "send this value to (generally) stdout"

In the Python REPL, a function return will be output to the screen by default (this isn't quite the same as print).

This is an example of print:

>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>

This is an example of return:

>>> def getN():
...    return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>

Start HTML5 video at a particular position when loading?

You have to wait until the browser knows the duration of the video before you can seek to a particular time. So, I think you want to wait for the 'loadedmetadata' event something like this:

document.getElementById('vid1').addEventListener('loadedmetadata', function() {
  this.currentTime = 50;
}, false);

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

How to turn on line numbers in IDLE?

There's a set of useful extensions to IDLE called IDLEX that works with MacOS and Windows http://idlex.sourceforge.net/

It includes line numbering and I find it quite handy & free.

Otherwise there are a bunch of other IDEs some of which are free: https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

What does "connection reset by peer" mean?

It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.

Best way to overlay an ESRI shapefile on google maps?

I like using (open source and gui friendly) Quantum GIS to convert the shapefile to kml.

Google Maps API supports only a subset of the KML standard. One limitation is file size.

To reduce your file size, you can Quantum GIS's "simplify geometries" function. This "smooths" polygons.

Then you can select your layer and do a "save as kml" on it.

If you need to process a bunch of files, the process can be batched with Quantum GIS's ogr2ogr command from osgeo4w shell.

Finally, I recommend zipping your kml (with your favorite compression program) for reduced file size and saving it as kmz.

UILabel text margin

A lot of the answers are missing the override of sizeThatFits. With this subclass you can just create the label, set the padding, and then say label.SizeToFit() and voila.

import UIKit

class UILabelEx : UILabel
{
    var padding : UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

    override func drawTextInRect(rect: CGRect) {

        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, padding))
    }

    override func sizeThatFits(size: CGSize) -> CGSize
    {

        var adjSize = super.sizeThatFits(size)
        adjSize.width += padding.left + padding.right
        adjSize.height += padding.top + padding.bottom

        return adjSize
    }
}

C/C++ macro string concatenation

You don't need that sort of solution for string literals, since they are concatenated at the language level, and it wouldn't work anyway because "s""1" isn't a valid preprocessor token.

[Edit: In response to the incorrect "Just for the record" comment below that unfortunately received several upvotes, I will reiterate the statement above and observe that the program fragment

#define PPCAT_NX(A, B) A ## B
PPCAT_NX("s", "1")

produces this error message from the preprocessing phase of gcc: error: pasting ""s"" and ""1"" does not give a valid preprocessing token

]

However, for general token pasting, try this:

/*
 * Concatenate preprocessor tokens A and B without expanding macro definitions
 * (however, if invoked from a macro, macro arguments are expanded).
 */
#define PPCAT_NX(A, B) A ## B

/*
 * Concatenate preprocessor tokens A and B after macro-expanding them.
 */
#define PPCAT(A, B) PPCAT_NX(A, B)

Then, e.g., both PPCAT_NX(s, 1) and PPCAT(s, 1) produce the identifier s1, unless s is defined as a macro, in which case PPCAT(s, 1) produces <macro value of s>1.

Continuing on the theme are these macros:

/*
 * Turn A into a string literal without expanding macro definitions
 * (however, if invoked from a macro, macro arguments are expanded).
 */
#define STRINGIZE_NX(A) #A

/*
 * Turn A into a string literal after macro-expanding it.
 */
#define STRINGIZE(A) STRINGIZE_NX(A)

Then,

#define T1 s
#define T2 1
STRINGIZE(PPCAT(T1, T2)) // produces "s1"

By contrast,

STRINGIZE(PPCAT_NX(T1, T2)) // produces "T1T2"
STRINGIZE_NX(PPCAT_NX(T1, T2)) // produces "PPCAT_NX(T1, T2)"

#define T1T2 visit the zoo
STRINGIZE(PPCAT_NX(T1, T2)) // produces "visit the zoo"
STRINGIZE_NX(PPCAT(T1, T2)) // produces "PPCAT(T1, T2)"

Adding IN clause List to a JPA Query

public List<DealInfo> getDealInfos(List<String> dealIds) {
        String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
        TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
        query.setParameter("inclList", dealIds);
        return query.getResultList();
    }

Works for me with JPA 2, Jboss 7.0.2

SQL query: Delete all records from the table except latest N?

If your id is incremental then use something like

delete from table where id < (select max(id) from table)-N

Get index of current item in a PowerShell loop

For PowerShell 3.0 and later, there is one built in :)

foreach ($item in $array) {
    $array.IndexOf($item)
}

How to detect iPhone 5 (widescreen devices)?

If the project is created using Xcode 6, then use the below mentioned code to detect the devices..

printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] nativeBounds].size.width,(int)[[UIScreen mainScreen] nativeBounds].size.height);

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
    if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
    {
        if([[UIScreen mainScreen] nativeBounds].size.height == 960 || [[UIScreen mainScreen] nativeBounds].size.height == 480){
            printf("Device Type : iPhone 4,4s ");

        }else if([[UIScreen mainScreen] nativeBounds].size.height == 1136){
            printf("Device Type : iPhone 5,5S/iPod 5 ");

        }else if([[UIScreen mainScreen] nativeBounds].size.height == 1334){
            printf("Device Type : iPhone 6 ");

        }else if([[UIScreen mainScreen] nativeBounds].size.height == 2208){
            printf("Device Type : iPhone 6+ ");

        }
    }
}else{
    printf("Device Type : iPad");
}

If the project was created in Xcode 5 and opened in Xcode 6, then use the below mentioned code to detect the devices.(This code works if no launching images for iPhone 6,6+ are assigned)

printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] nativeBounds].size.width,(int)[[UIScreen mainScreen] nativeBounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
    if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
    {
       if([[UIScreen mainScreen] nativeBounds].size.height == 960 || [[UIScreen mainScreen] nativeBounds].size.height == 480){
            printf("Device Type : iPhone 4,4s");
            appType=1;
        }else if([[UIScreen mainScreen] nativeBounds].size.height == 1136 || [[UIScreen mainScreen] nativeBounds].size.height == 1704){
            printf("Device Type : iPhone 5,5S,6,6S/iPod 5 ");
            appType=3;
        }
    }
}else{
    printf("Device Type : iPad");
    appType=2;
}

If you are still using Xcode 5 all together then use the following code to detect the devices (iPhone 6 and 6+ will not be detected)

printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] bounds].size.width,(int)[[UIScreen mainScreen] bounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
    if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
    {
        CGSize result = [[UIScreen mainScreen] bounds].size;
        CGFloat scale = [UIScreen mainScreen].scale;
        result = CGSizeMake(result.width * scale, result.height * scale);
        if(result.height == 960 || result.height == 480){
            printf("Device Type : iPhone 4,4S ");

        }else if(result.height == 1136){
            printf("Device Type : iPhone 5s/iPod 5");

        }
    }
}else{
    printf("Device Type : iPad");

}

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});

Async always WaitingForActivation

The reason is your result assigned to the returning Task which represents continuation of your method, and you have a different Task in your method which is running, if you directly assign Task like this you will get your expected results:

var task = Task.Run(() =>
        {
            for (int i = 10; i < 432543543; i++)
            {
                // just for a long job
                double d3 = Math.Sqrt((Math.Pow(i, 5) - Math.Pow(i, 2)) / Math.Sin(i * 8));
            }
           return "Foo Completed.";

        });

        while (task.Status != TaskStatus.RanToCompletion)
        {
            Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId,task.Status);

        }

        Console.WriteLine("Result: {0}", task.Result);
        Console.WriteLine("Finished.");
        Console.ReadKey(true);

The output:

enter image description here

Consider this for better explanation: You have a Foo method,let's say it Task A, and you have a Task in it,let's say it Task B, Now the running task, is Task B, your Task A awaiting for Task B result.And you assing your result variable to your returning Task which is Task A, because Task B doesn't return a Task, it returns a string. Consider this:

If you define your result like this:

Task result = Foo(5);

You won't get any error.But if you define it like this:

string result = Foo(5);

You will get:

Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'string'

But if you add an await keyword:

string result = await Foo(5);

Again you won't get any error.Because it will wait the result (string) and assign it to your result variable.So for the last thing consider this, if you add two task into your Foo Method:

private static async Task<string> Foo(int seconds)
{
    await Task.Run(() =>
        {
            for (int i = 0; i < seconds; i++)
            {
                Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
                Task.Delay(TimeSpan.FromSeconds(1)).Wait();
            }

            // in here don't return anything
        });

   return await Task.Run(() =>
        {
            for (int i = 0; i < seconds; i++)
            {
                Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
                Task.Delay(TimeSpan.FromSeconds(1)).Wait();
            }

            return "Foo Completed.";
        });
}

And if you run the application, you will get the same results.(WaitingForActivation) Because now, your Task A is waiting those two tasks.

"unmappable character for encoding" warning in Java

For those wondering why this happens on some systems and not on others (with the same source, build parameters, and so on), check your LANG environment variable. I get the warning/error when LANG=C.UTF-8, but not when LANG=en_US.UTF-8.

What is the best way to know if all the variables in a Class are null?

The best way in my opinion is Reflection as others have recommended. Here's a sample that evaluates each local field for null. If it finds one that is not null, method will return false.

public class User {

    String id = null;
    String name = null;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isNull() {
        Field fields[] = this.getClass().getDeclaredFields();
        for (Field f : fields) {
            try {
                Object value = f.get(this);
                if (value != null) {
                    return false;
                }
            }
            catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
        return true;

    }

    public static void main(String args[]) {
        System.out.println(new User().isNull());
    }
}

C#: Looping through lines of multiline string

To update this ancient question for .NET 4, there is now a much neater way:

var lines = File.ReadAllLines(filename);

foreach (string line in lines)
{
    Console.WriteLine(line);
}

generate a random number between 1 and 10 in c

srand(time(NULL));

int nRandonNumber = rand()%((nMax+1)-nMin) + nMin;
printf("%d\n",nRandonNumber);

Change some value inside the List<T>

You could use ForEach, but you have to convert the IEnumerable<T> to a List<T> first.

list.Where(w => w.Name == "height").ToList().ForEach(s => s.Value = 30);

how to implement Pagination in reactJs

I have implemented pagination + search in ReactJs, see the output: Pagination in React

View complete code on GitHub: https://github.com/navanathjadhav/generic-pagination

Also visit this article for step by step implementation of pagination: https://everblogs.com/react/3-simple-steps-to-add-pagination-in-react/

Read pdf files with php

Check out FPDF (with FPDI):

http://www.fpdf.org/

http://www.setasign.de/products/pdf-php-solutions/fpdi/

These will let you open an pdf and add content to it in PHP. I'm guessing you can also use their functionality to search through the existing content for the values you need.

Another possible library is TCPDF: https://tcpdf.org/

Update to add a more modern library: PDF Parser

Padding In bootstrap

The suggestion from @Dawood is good if that works for you.

If you need more fine-tuning than that, one option is to use padding on the text elements, here's an example: http://jsfiddle.net/panchroma/FtBwe/

CSS

p, h2 {
    padding-left:10px;
}

JavaScript unit test tools for TDD

MochiKit has a testing framework called SimpleTest that seems to have caught on. Here's a blog post from the original author.

How to make lists contain only distinct element in Python?

The simplest is to convert to a set then back to a list:

my_list = list(set(my_list))

One disadvantage with this is that it won't preserve the order. You may also want to consider if a set would be a better data structure to use in the first place, instead of a list.

jQuery get html of container including the container itself

var x = $($('div').html($('#container').clone())).html();

How do I delete an item or object from an array using ng-click?

if you have ID or any specific field in your item, you can use filter(). its act like Where().

<a class="btn" ng-click="remove(item)">Delete</a>

in controller:

$scope.remove = function(item) { 
  $scope.bdays = $scope.bdays.filter(function (element) {
                    return element.ID!=item.ID
                });
}

Use LIKE %..% with field values in MySQL

  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

Specifying ssh key in ansible playbook file

You can use the ansible.cfg file, it should look like this (There are other parameters which you might want to include):

[defaults]
inventory = <PATH TO INVENTORY FILE>
remote_user = <YOUR USER>
private_key_file =  <PATH TO KEY_FILE>

Hope this saves you some typing

Comparing boxed Long values 127 and 128

TL;DR

Java caches boxed Integer instances from -128 to 127. Since you are using == to compare objects references instead of values, only cached objects will match. Either work with long unboxed primitive values or use .equals() to compare your Long objects.

Long (pun intended) version

Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.

Java caches Integer objects instances from the range -128 to 127. That said:

  • If you set to N Long variables the value 127 (cached), the same object instance will be pointed by all references. (N variables, 1 instance)
  • If you set to N Long variables the value 128 (not cached), you will have an object instance pointed by every reference. (N variables, N instances)

That's why this:

Long val1 = 127L;
Long val2 = 127L;

System.out.println(val1 == val2);

Long val3 = 128L;
Long val4 = 128L;

System.out.println(val3 == val4);

Outputs this:

true
false

For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true.

On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false on the comparison between them.

That happens solely because you are comparing two Long object references, not long primitive values, with the == operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with == operator.

Changing these variables to primitive long types will prevent this from happening, but in case you need to keep your code using Long objects, you can safely make these comparisons with the following approaches:

System.out.println(val3.equals(val4));                     // true
System.out.println(val3.longValue() == val4.longValue());  // true
System.out.println((long)val3 == (long)val4);              // true

(Proper null checking is necessary, even for castings)

IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.

Reference links:

How to center a navigation bar with CSS or HTML?

The best way to fix it I have looked for the code or trick how to center nav menu and found the real solutions it works for all browsers and for my friends ;)

Here is how I have done:

body {
    margin: 0;
    padding: 0;
}

div maincontainer {
    margin: 0 auto;
    width: ___px;
    text-align: center;
}

ul {
    margin: 0;
    padding: 0;
}

ul li {
    margin-left: auto;
    margin-right: auto;
}

and do not forget to set doctype html5

Exit a Script On Error

If you want to be able to handle an error instead of blindly exiting, instead of using set -e, use a trap on the ERR pseudo signal.

#!/bin/bash
f () {
    errorCode=$? # save the exit code as the first thing done in the trap function
    echo "error $errorCode"
    echo "the command executing at the time of the error was"
    echo "$BASH_COMMAND"
    echo "on line ${BASH_LINENO[0]}"
    # do some error handling, cleanup, logging, notification
    # $BASH_COMMAND contains the command that was being executed at the time of the trap
    # ${BASH_LINENO[0]} contains the line number in the script of that command
    # exit the script or return to try again, etc.
    exit $errorCode  # or use some other value or do return instead
}
trap f ERR
# do some stuff
false # returns 1 so it triggers the trap
# maybe do some other stuff

Other traps can be set to handle other signals, including the usual Unix signals plus the other Bash pseudo signals RETURN and DEBUG.