Programs & Examples On #Android lifecycle

Questions regarding the events forwarded by the system to components, during their lifetime, in an Android Application. Most components have a specific LifeCycle that is imposed upon them. This tag is not meant to be used alone: use with [tag:android-activity], [tag:android-service], [tag:android-broadcastreceiver]

How to use onResume()?

After an activity started, restarted (onRestart() happens before onStart()), or paused (onPause()), onResume() called. When the activity is in the state of onResume(), the activity is ready to be used by the app user.

I have studied the activity lifecycle a little bit, and here's my understanding of this topic: If you want to restart the activity (A) at the end of the execution of another, there could be a few different cases.

  1. The other activity (B) has been paused and/or stopped or destroyed, and the activity A possibly had been paused (onPause()), in this case, activity A will call onResume()

  2. The activity B has been paused and/or stopped or destroyed, the activity A possibly had been stopped (onStop()) due to memory thing, in this case, activity A will call onRestart() first, onStart() second, then onResume()

  3. The activity B has been paused and/or stopped or destroyed, the activity A has been destroyed, the programmer can call onStart() manually to start the activity first, then onResume() because when an activity is in the destroyed status the activity has not started, and this happens before the activity being completely removed. If the activity is removed, the activity needs to be created again. Manually calling onStart() I think it's because if the activity not started and it is created, onStart() will be called after onCreate().

If you want to update data, make a data update function and put the function inside the onResume(). Or put a loadData function inside onResume()

It's better to understand the lifecycle with the help of the Activity lifecycle diagram.

java.lang.IllegalStateException: Fragment not attached to Activity

This issue occurs whenever you call a context which is unavailable or null when you call it. This can be a situation when you are calling main activity thread's context on a background thread or background thread's context on main activity thread.

For instance , I updated my shared preference string like following.

editor.putString("penname",penNameEditeText.getText().toString());
editor.commit();
finish();

And called finish() right after it. Now what it does is that as commit runs on main thread and stops any other Async commits if coming until it finishes. So its context is alive until the write is completed. Hence previous context is live , causing the error to occur.

So make sure to have your code rechecked if there is some code having this context issue.

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

UPDATE

the super finishAffinity() method will help to reduce the code but achieve the same. It will finish the current activity as well as all activities in the stack, use getActivity().finishAffinity() if you are in a fragment.

finishAffinity(); 
startActivity(new Intent(mActivity, LoginActivity.class));

ORIGINAL ANSWER

Assume that LoginActivity --> HomeActivity --> ... --> SettingsActivity call signOut():

void signOut() {
    Intent intent = new Intent(this, HomeActivity.class);
    intent.putExtra("finish", true);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // To clean up all activities
    startActivity(intent);
    finish();
}

HomeActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    boolean finish = getIntent().getBooleanExtra("finish", false);
    if (finish) {
        startActivity(new Intent(mContext, LoginActivity.class));
        finish();
        return;
    }
    initializeView();
}

This works for me, hope that it is helpful for you too. :)

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

How to start new activity on button click

Place button widget in xml like below

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
/>

After that initialise and handle on click listener in Activity like below ..

In Activity On Create method :

Button button =(Button) findViewById(R.id.button); 
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
       Intent intent = new 
            Intent(CurrentActivity.this,DesiredActivity.class);
            startActivity(intent);
    }
});

laravel 5.4 upload image

In Laravel 5.4, you can use guessClientExtension

Display JSON as HTML

You can use the JSON.stringify function with unformatted JSON. It outputs it in a formatted way.

JSON.stringify({ foo: "sample", bar: "sample" }, null, 4)

This turns

{ "foo": "sample", "bar": "sample" }

into

 {
     "foo": "sample", 
     "bar": "sample" 
 }

Now the data is a readable format you can use the Google Code Prettify script as suggested by @A. Levy to colour code it.

It is worth adding that IE7 and older browsers do not support the JSON.stringify method.

Error: Could not find or load main class in intelliJ IDE

In my case, the application runs well when code initially was under /src directory under the project. Later I added /main/java directory after the /src, then "Could not find or load main class ..." error happened. At that time you couldn't add /src/main/java/YourMain.java to the run configuration. What I did was to remove the run configuration, then right click the project->Open Module Settings (or F4 after click the Project panel)->Project Settings->Modules delete (x) the old Content Root and + Add Content Root, choose /src/main/java. Rebuild the project and it runs.

NodeJs : TypeError: require(...) is not a function

I've faced to something like this too. in your routes file , export the function as an object like this :

 module.exports = {
     hbd: handlebar
 }

and in your app file , you can have access to the function by .hbd and there is no ptoblem ....!

Dynamically create and submit form

Yes, it is possible. One of the solutions is below (jsfiddle as a proof).

HTML:

<a id="fire" href="#" title="submit form">Submit form</a>

(see, above there is no form)

JavaScript:

jQuery('#fire').click(function(event){
    event.preventDefault();
    var newForm = jQuery('<form>', {
        'action': 'http://www.google.com/search',
        'target': '_top'
    }).append(jQuery('<input>', {
        'name': 'q',
        'value': 'stack overflow',
        'type': 'hidden'
    }));
    newForm.submit();
});

The above example shows you how to create form, how to add inputs and how to submit. Sometimes display of the result is forbidden by X-Frame-Options, so I have set target to _top, which replaces the main window's content. Alternatively if you set _blank, it can show within new window / tab.

Change tab bar item selected color in a storyboard

On Xcode8 I have changed the ImageTint from the storyboard and it works well.

enter image description here

The result:

enter image description here

What do $? $0 $1 $2 mean in shell script?

These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

How to move mouse cursor using C#?

First Add a Class called Win32.cs

public class Win32
{ 
    [DllImport("User32.Dll")]
    public static extern long SetCursorPos(int x, int y);

    [DllImport("User32.Dll")]
    public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int x;
        public int y;

        public POINT(int X, int Y)
        {
            x = X;
            y = Y;
        }
    }
}

You can use it then like this:

Win32.POINT p = new Win32.POINT(xPos, yPos);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

How to use an arraylist as a prepared statement parameter

@JulienD Best way is to break above process into two steps.

Step 1 : Lets say 'rawList' as your list that you want to add as parameters in prepared statement.

Create another list :

ArrayList<String> listWithQuotes = new ArrayList<String>();

for(String element : rawList){
    listWithQuotes.add("'"+element+"'");
}

Step 2 : Make 'listWithQuotes' comma separated.

String finalString = StringUtils.join(listWithQuotes.iterator(),",");

'finalString' will be string parameters with each element as single quoted and comma separated.

How can I change or remove HTML5 form validation default error messages?

To set custom error message for HTML 5 validation use,

oninvalid="this.setCustomValidity('Your custom message goes here.')"

and to remove this message when user enters valid data use,

onkeyup="setCustomValidity('')"

Hope this works for you. Enjoy ;)

How to manually trigger click event in ReactJS?

If it doesn't work in the latest version of reactjs, try using innerRef

class MyComponent extends React.Component {


  render() {
    return (
      <div onClick={this.handleClick}>
        <input innerRef={input => this.inputElement = input} />
      </div>
    );
  }

  handleClick = (e) => {
    this.inputElement.click();
  }
}

Make browser window blink in task Bar

Why not take the approach that GMail uses and show the number of messages in the page title?

Sometimes users don't want to be distracted when a new message arrives.

How can I simulate mobile devices and debug in Firefox Browser?

Use the Responsive Design Tool using Ctrl + Shift + M.

Python pip install module is not found. How to link python to pip location?

Below steps helped me fix this.

  • upgrade pip version
  • remove the created environment by using command rm -rf env-name
  • create environment using command python3 -m venv env-aide
  • now install the package and check

Python loop counter in a for loop

I'll sometimes do this:

def draw_menu(options, selected_index):
    for i in range(len(options)):
        if i == selected_index:
            print " [*] %s" % options[i]
        else:
            print " [ ] %s" % options[i]

Though I tend to avoid this if it means I'll be saying options[i] more than a couple of times.

Adding two numbers concatenates them instead of calculating the sum

This can also be achieved with a more native HTML solution by using the output element.

<form oninput="result.value=parseInt(a.valueAsNumber)+parseInt(b.valueAsNumber)">
  <input type="number" id="a" name="a" value="10" /> +
  <input type="number" id="b" name="b" value="50" /> =
  <output name="result" for="a b">60</output>
</form>

https://jsfiddle.net/gxu1rtqL/

The output element can serve as a container element for a calculation or output of a user's action. You can also change the HTML type from number to range and keep the same code and functionality with a different UI element, as shown below.

<form oninput="result.value=parseInt(a.valueAsNumber)+parseInt(b.valueAsNumber)">
  <input type="range" id="a" name="a" value="10" /> +
  <input type="number" id="b" name="b" value="50" /> =
  <output name="result" for="a b">60</output>
</form>

https://jsfiddle.net/gxu1rtqL/2/

How can I set the focus (and display the keyboard) on my EditText programmatically

I tried the top answer by David Merriman and it also didn't work in my case. But I found the suggestion to run this code delayed here and it works like a charm.

val editText = view.findViewById<View>(R.id.settings_input_text)

editText.postDelayed({
    editText.requestFocus()

    val imm = context.getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
}, 100)

How to deploy a React App on Apache web server

You can run it through the Apache proxy, but it would have to be running in a virtual directory (e.g. http://mysite.something/myreactapp ).

This may seem sort of redundant but if you have other pages that are not part of your React app (e.g. PHP pages), you can serve everything via port 80 and make it apear that the whole thing is a cohesive website.

1.) Start your react app with npm run, or whatever command you are using to start the node server. Assuming it is running on http://127.0.0.1:8080

2.) Edit httpd-proxy.conf and add:

ProxyRequests On
ProxyVia On
<Proxy *>
  Order deny,allow
  Allow from all
  </Proxy>

ProxyPass /myreactapp http://127.0.0.1:8080/
ProxyPassReverse /myreactapp  http://127.0.0.1:8080/

3.) Restart Apache

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

I think you should not rely on the implicit conversion. It is a bad practice.

Instead you should try like this:

datenum >= to_date('11/26/2013','mm/dd/yyyy')

or like

datenum >= date '2013-09-01'

Relative paths based on file location instead of current working directory

@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.

This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:


Linux / GNU readlink solution:

If your script needs to run on Linux only or you know that GNU readlink is in the $PATH, use readlink -f, which conveniently resolves a symlink to its ultimate target:

 scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")

Note that GNU readlink has 3 related options for resolving a symlink to its ultimate target's full path: -f (--canonicalize), -e (--canonicalize-existing), and -m (--canonicalize-missing) - see man readlink.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f here, because it is the most well-known one.


Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):

If your script must run on any platform that:

  • has a readlink utility, but lacks the -f option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.

    • macOS uses an older version of the BSD implementation of readlink; note that recent versions of FreeBSD/PC-BSD do support -f.
  • does not even have readlink, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).

The following solution, inspired by https://stackoverflow.com/a/1116890/45375, defines helper shell function, rreadlink(), which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink's -e option, which is similar to the -f option, except that the ultimate target must exist.

Note: The function is a bash function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh), see here.

  • If readlink is available, it is used (without options) - true on most modern platforms.

  • Otherwise, the output from ls -l is parsed, which is the only POSIX-compliant way to determine a symlink's target.
    Caveat: this will break if a filename or path contains the literal substring -> - which is unlikely, however.
    (Note that platforms that lack readlink may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find utility supporting the %l format char. with its -printf primary; in the interest of brevity the function does NOT try to detect such cases.)

  • An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink; on other platforms (assuming they have bash), follow the manual installation instructions.

If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.

#!/usr/bin/env bash

# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...

  local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH= 

  # Since we'll be using `command` below for a predictable execution
  # environment, we make sure that it has its original meaning.
  { \unalias command; \unset -f command; } &>/dev/null

  while :; do # Resolve potential symlinks until the ultimate target is found.
      [[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
      fname=$(command basename -- "$target") # Extract filename.
      [[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
      if [[ -L $fname ]]; then
        # Extract [next] target path, which is defined
        # relative to the symlink's own directory.
        if [[ -n $readlinkexe ]]; then # Use `readlink`.
          target=$("$readlinkexe" -- "$fname")
        else # `readlink` utility not available.
          # Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant 
          # way to determine a symlink's target. Hypothetically, this can break with
          # filenames containig literal ' -> ' and embedded newlines.
          target=$(command ls -l -- "$fname")
          target=${target#* -> }
        fi
        continue # Resolve [next] symlink target.
      fi
      break # Ultimate target reached.
  done
  targetDir=$(command pwd -P) # Get canonical dir. path
  # Output the ultimate target's canonical path.
  # Note that we manually resolve paths ending in /. and /.. to make sure we
  # have a normalized path.
  if [[ $fname == '.' ]]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [[ $fname == '..' ]]; then
    # Caveat: something like /var/.. will resolve to /private (assuming
    # /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")

How to correctly set Http Request Header in Angular 2

You have a typo.

Change: headers.append('authentication', ${student.token});

To: headers.append('Authentication', student.token);

NOTE the Authentication is capitalized

Plotting images side by side using matplotlib

One thing that I found quite helpful to use to print all images :

_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
    ax.imshow(img)
plt.show()

Python - How to convert JSON File to Dataframe

import pandas as pd
print(pd.json_normalize(your_json))

This will Normalize semi-structured JSON data into a flat table

Output

  FirstName LastName MiddleName password    username
      John     Mark      Lewis     2910  johnlewis2

laravel-5 passing variable to JavaScript

The best way for me was to put it in a hidden div in php blade

<div hidden id="token">{{$token}}</div>

then call it in javascript as a constant to avoid undefined var errors

const token = document.querySelector('div[id=token]').textContent

// console.log(token)
// eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI5MjNlOTcyMi02N2NmLTQ4M2UtYTk4Mi01YmE5YTI0Y2M2MzMiLCJqdGkiOiI2Y2I1ZGRhNzRhZjNhYTkwNzA3ZjMzMDFiYjBiZDUzNTZjNjYxMGUyZWJlNmYzOTI5NzBmMjNjNDdiNjhjY2FiYjI0ZWVmMzYwZmNiZDBmNyIsImlhdCI6IjE2MDgwODMyNTYuNTE2NjE4IiwibmJmIjoiMTYwODA4MzI1Ni41MTY2MjUiLCJleHAiOiIxNjIzODA4MDU2LjMxMTg5NSIsInN1YiI6IjUiLCJzY29wZXMiOlsiYWRtaW4iXX0.GbKZ8CIjt3otzFyE5aZEkNBCtn75ApIfS6QbnD6z0nxDjycknQaQYz2EGems9Z3Qjabe5PA9zL1mVnycCieeQfpLvWL9xDu9hKkIMs006Sznrp8gWy6JK8qX4Xx3GkzWEx8Z7ZZmhsKUgEyRkqnKJ-1BqC2tTiTBqBAO6pK_Pz7H74gV95dsMiys9afPKP5ztW93kwaC-pj4h-vv-GftXXc6XDnUhTppT4qxn1r2Hf7k-NXE_IHq4ZPb20LRXboH0RnbJgq2JA1E3WFX5_a6FeWJvLlLnGGNOT0ocdNZq7nTGWwfocHlv6pH0NFaKa3hLoRh79d5KO_nysPVCDt7jYOMnpiq8ybIbe3oYjlWyk_rdQ9067bnsfxyexQwLC3IJpAH27Az8FQuOQMZg2HJhK8WtWUph5bsYUU0O2uPG8HY9922yTGYwzeMEdAqBss85jdpMNuECtlIFM1Pc4S-0nrCtBE_tNXn8ATDrm6FecdSK8KnnrCOSsZhR04MvTyznqCMAnKtN_vMDpmIAmPd181UanjO_kxR7QIlsEmT_UhM1MBmyfdIEvHkgLgUdUouonjQNvOKwCrrgDkP0hkZQff-iuHPwpL-CUjw7GPa70lp-TIDhfei8T90RkAXte1XKv7ku3sgENHTwPrL9QSrNtdc5MfB9AbUV-tFMJn9T7k

How to convert an Image to base64 string in java?

this did it for me. you can vary the options for the output format to Base64.Default whatsoever.

// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);

How to solve javax.net.ssl.SSLHandshakeException Error?

I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..

ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...

Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )

In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..

I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...

P.S I cant get source code before the weekend since external SSH is disabled in my office :(

Filtering collections in C#

List<T> has a FindAll method that will do the filtering for you and return a subset of the list.

MSDN has a great code example here: http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx

EDIT: I wrote this before I had a good understanding of LINQ and the Where() method. If I were to write this today i would probably use the method Jorge mentions above. The FindAll method still works if you're stuck in a .NET 2.0 environment though.

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

Get random integer in range (x, y]?

How about:

Random generator = new Random();
int i = 10 - generator.nextInt(10);

Insert an element at a specific index in a list and return the updated list

Use the Python list insert() method. Usage:

#Syntax

The syntax for the insert() method -

list.insert(index, obj)

#Parameters

  • index - This is the Index where the object obj need to be inserted.
  • obj - This is the Object to be inserted into the given list.

#Return Value This method does not return any value, but it inserts the given element at the given index.

Example:

a = [1,2,4,5]

a.insert(2,3)

print(a)

Returns [1, 2, 3, 4, 5]

UINavigationBar Hide back Button Text

In the interface builder, you can select the navigation item of the previous controller and change the Back Button string to what you'd like the back button to appear as. If you want it blank, for example, just put a space.

You can also change it with this line of code:

[self.navigationItem.backBarButtonItem setTitle:@"Title here"];

Or in Swift:

self.navigationItem.backBarButtonItem?.title = ""

What is considered a good response time for a dynamic, personalized web application?

Our company has a 5 second response time standard limit, and we aim for 2-3 seconds in general. This accounts for 98% of page loads. A few particular tasks are allowed to go up to 15 seconds, but we then mitigate that time by putting up a page and refreshing every 5 seconds telling the user that we are still trying to process the request. That way the user sees that something is happening and doesn't just leave. Although, considering that I work on a website whose users are forced to use for business reasons, they aren't going to leave, but they are capable of complaining quite loudly.

In general, if the processing is going to take more than 5 seconds, put up a temporary page so that the user doesn't lose interest.

update columns values with column of another table based on condition

Something like this should do it :

UPDATE table1 
   SET table1.Price = table2.price 
   FROM table1  INNER JOIN  table2 ON table1.id = table2.id

You can also try this:

UPDATE table1 
   SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);

Trimming text strings in SQL Server 2008

I know this is an old question but I just found a solution which creates a user defined function using LTRIM and RTRIM. It does not handle double spaces in the middle of a string.

The solution is however straight forward:

User Defined Trim Function

How do you Sort a DataTable given column and direction?

If you've only got one DataView, you can sort using that instead:

table.DefaultView.Sort = "columnName asc";

Haven't tried it, but I guess you can do this with any number of DataViews, as long as you reference the right one.

Styling multi-line conditions in 'if' statements?

I've been struggling to find a decent way to do this as well, so I just came up with an idea (not a silver bullet, since this is mainly a matter of taste).

if bool(condition1 and
        condition2 and
        ...
        conditionN):
    foo()
    bar()

I find a few merits in this solution compared to others I've seen, namely, you get exactly an extra 4 spaces of indentation (bool), allowing all conditions to line up vertically, and the body of the if statement can be indented in a clear(ish) way. This also keeps the benefits of short-circuit evaluation of boolean operators, but of course adds the overhead of a function call that basically does nothing. You could argue (validly) that any function returning its argument could be used here instead of bool, but like I said, it's just an idea and it's ultimately a matter of taste.

Funny enough, as I was writing this and thinking about the "problem", I came up with yet another idea, which removes the overhead of a function call. Why not indicate that we're about to enter a complex condition by using extra pairs of parentheses? Say, 2 more, to give a nice 2 space indent of the sub-conditions relative to the body of the if statement. Example:

if (((foo and
      bar and
      frob and
      ninja_bear))):
    do_stuff()

I kind of like this because when you look at it, a bell immediatelly rings in your head saying "hey, there's a complex thing going on here!". Yes, I know that parentheses don't help readability, but these conditions should appear rarely enough, and when they do show up, you are going to have to stop and read them carefuly anyway (because they're complex).

Anyway, just two more proposals that I haven't seen here. Hope this helps someone :)

Get random boolean in Java

Java 8: Use random generator isolated to the current thread: ThreadLocalRandom nextBoolean()

Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.

java.util.concurrent.ThreadLocalRandom.current().nextBoolean();

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

To put a sequence or another numpy array into a numpy array, Just change this line:

kOUT=np.zeros(N+1)

to:

kOUT=np.asarray([None]*(N+1))

Or:

kOUT=np.zeros((N+1), object)

How can I wait for set of asynchronous callback functions?

Use an control flow library like after

after.map(array, function (value, done) {
    // do something async
    setTimeout(function () {
        // do something with the value
        done(null, value * 2)
    }, 10)
}, function (err, mappedArray) {
    // all done, continue here
    console.log(mappedArray)
})

Merging arrays with the same keys

Try this:

$array_one = ['ratio_type'];
$array_two = ['ratio_type', 'ratio_type'];
$array_three = ['ratio_type'];
$array_four = ['ratio_type'];
$array_five = ['ratio_type', 'ratio_type', 'ratio_type'];
$array_six = ['ratio_type'];
$array_seven = ['ratio_type'];
$array_eight = ['ratio_type'];

$all_array_elements = array_merge_recursive(
    $array_one,
    $array_two,
    $array_three,
    $array_four,
    $array_five,
    $array_six,
    $array_seven,
    $array_eight
);

foreach ($all_array_elements as $key => $value) {
    echo "[$key]" . ' - ' . $value . PHP_EOL;
}

// OR
var_dump($all_array_elements);

Databound drop down list - initial value

hi friend in this case you can use the

AppendDataBound="true"

and after this use the list item. for e.g.:

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="--Select One--" Value="" />   
</asp:DropDownList>

but the problem in this is after second time select data are append with old data.

Java: Clear the console

This will work if you are doing this in Bluej or any other similar software.

System.out.print('\u000C');

Android : How to set onClick event for Button in List item of ListView

In your custom adapter inside getView method :

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Do things Here 
    }
});

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

I had the same problem, and because of the "Home" button added automatically in the toolbar, my text was not exactly entered.

I fixed it the dirty way but it works well in my case. I simply added a margin to the right of my TextView to compensate for the home button on the left. Here's my toolbar layout :

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:elevation="1dp"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:layout_collapseMode="pin"
    android:gravity="center"
    android:background="@color/mainBackgroundColor"
    android:fitsSystemWindows="true" >

    <com.lunabee.common.utils.LunabeeShadowTextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="?attr/actionBarSize"
        android:gravity="center"
        style="@style/navigation.toolbar.title" />

</android.support.v7.widget.Toolbar>

How to get status code from webclient?

You can try this code to get HTTP status code from WebException or from OpenReadCompletedEventArgs.Error. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(System.Exception err)
{
    if (err is WebException)
    {
        WebException we = (WebException)err;
        if (we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            return response.StatusCode;
        }
    }
    return 0;
}

Where are the python modules stored?

  1. You can iterate through directories listed in sys.path to find all modules (except builtin ones).
  2. It'll probably be somewhere around /usr/lib/pythonX.X/site-packages (again, see sys.path). And consider using native Python package management (via pip or easy_install, plus yolk) instead, packages in Linux distros-maintained repositories tend to be outdated.

How to get primary key of table?

How about this:

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
  AND TABLE_NAME = 'Your Table name'
  AND COLUMN_KEY = 'PRI';


SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
  AND TABLE_NAME = 'Your Table name'
  AND COLUMN_KEY = 'UNI';

How to stop EditText from gaining focus at Activity startup in Android

Disable it in onCreate()

final KeyListener edtTxtMessageKeyListener = edtTxtMessage.getKeyListener();
edtTxtMessage.setCursorVisible(false);
edtTxtMessage.setKeyListener(null);

And finally enable it in onClick() of EditText

edtTxtMessage.setCursorVisible(true);
edtTxtMessage.setKeyListener(edtTxtMessageKeyListener);

But the problem is with we have to click twise to bring OnScreenKeyboard for very first time.

@Workaround

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

Try this also in onClick() :)

Strip first and last character from C string

Further to @pmg's answer, note that you can do both operations in one statement:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++[strlen(p)-1] = 0;

This will likely work as expected but behavior is undefined in C standard.

Capture key press (or keydown) event on DIV element

tabindex HTML attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key). Read MDN Web Docs for full reference.

Using Jquery

_x000D_
_x000D_
$( "#division" ).keydown(function(evt) {
    evt = evt || window.event;
    console.log("keydown: " + evt.keyCode);
});
_x000D_
#division {
  width: 90px;
  height: 30px;
  background: lightgrey;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="division" tabindex="0"></div>
_x000D_
_x000D_
_x000D_

Using JavaScript

_x000D_
_x000D_
var el = document.getElementById("division");

el.onkeydown = function(evt) {
    evt = evt || window.event;
    console.log("keydown: " + evt.keyCode);
};
_x000D_
#division {
  width: 90px;
  height: 30px;
  background: lightgrey;
}
_x000D_
<div id="division" tabindex="0"></div>
_x000D_
_x000D_
_x000D_

Best approach to real time http streaming to HTML5 video client

Take a look at this solution. As I know, Flashphoner allows to play Live audio+video stream in the pure HTML5 page.

They use MPEG1 and G.711 codecs for playback. The hack is rendering decoded video to HTML5 canvas element and playing decoded audio via HTML5 audio context.

Does HTTP use UDP?

If you are streaming an mp3 or video that may not necessarily be over HTTP, in fact I'd be suprised if it was. It would probably be another protocol over TCP but I see no reason why you cannot stream over UDP.

If you do you have to take into account that there is no certainty that your data will arrive at the other end, but I can take it that you know about UDP.

To answer you question, No, HTTP does NOT use UDP. For what you talk about though, mp3/video streaming COULD happen over UDP and in my opinion should never happen over HTTP.

How do I pass command line arguments to a Node.js program?

If your script is called myScript.js and you want to pass the first and last name, 'Sean Worthington', as arguments like below:

node myScript.js Sean Worthington

Then within your script you write:

var firstName = process.argv[2]; // Will be set to 'Sean'
var lastName = process.argv[3]; // Will be set to 'Worthington'

How to count number of files in each directory?

Easy way to recursively find files of a given type. In this case, .jpg files for all folders in current directory:

find . -name *.jpg -print | wc -l

Where is the Keytool application?

For me it turned out to be in c/Program Files/Java/jdk1.7.0_25/bin (Windows 8). A more general answer to this question is that it will most likely be in the bin sub directory of wherever your jdk is installed.

How do you resize a form to fit its content automatically?

I used this code and it works just fine

const int margin = 5;
        Rectangle rect = new Rectangle(
            Screen.PrimaryScreen.WorkingArea.X + margin,
            Screen.PrimaryScreen.WorkingArea.Y + margin,
            Screen.PrimaryScreen.WorkingArea.Width - 2 * margin,
            Screen.PrimaryScreen.WorkingArea.Height - 2 * (margin - 7));
        this.Bounds = rect;

Select rows from a data frame based on values in a vector

Another option would be to use a keyed data.table:

library(data.table)
setDT(dt, key = 'fct')[J(vc)]  # or: setDT(dt, key = 'fct')[.(vc)]

which results in:

   fct X
1:   a 2
2:   a 7
3:   a 1
4:   c 3
5:   c 5
6:   c 9
7:   c 2
8:   c 4

What this does:

  • setDT(dt, key = 'fct') transforms the data.frame to a data.table (which is an enhanced form of a data.frame) with the fct column set as key.
  • Next you can just subset with the vc vector with [J(vc)].

NOTE: when the key is a factor/character variable, you can also use setDT(dt, key = 'fct')[vc] but that won't work when vc is a numeric vector. When vc is a numeric vector and is not wrapped in J() or .(), vc will work as a rowindex.

A more detailed explanation of the concept of keys and subsetting can be found in the vignette Keys and fast binary search based subset.

An alternative as suggested by @Frank in the comments:

setDT(dt)[J(vc), on=.(fct)]

When vc contains values that are not present in dt, you'll need to add nomatch = 0:

setDT(dt, key = 'fct')[J(vc), nomatch = 0]

or:

setDT(dt)[J(vc), on=.(fct), nomatch = 0]

In C#, how to check whether a string contains an integer?

Maybe this can help

string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));

answer from msdn.

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

Try the next step to "Refresh" your IDE (android studio)

1. Let Gradle rebuild your auto-genrated files by click Build | Rebuild
2. Also try Choose File | Invalidate Caches/Restart.

Find and Replace Inside a Text File from a Bash Command

I was surprised when I stumbled over this...

There is a replace command which ships with the "mysql-server" package, so if you have installed it try it out:

# replace string abc to XYZ in files
replace "abc" "XYZ" -- file.txt file2.txt file3.txt

# or pipe an echo to replace
echo "abcdef" |replace "abc" "XYZ"

See man replace for more on this.

How to get TimeZone from android mobile?

Try this code-

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();

It will return user selected timezone.

How to view table contents in Mysql Workbench GUI?

All the answers above are great. Only one thing is missing, be sure to drag the grey buttons to see the table (step number 2):

enter image description here

ORA-01861: literal does not match format string

Remove the TO_DATE in the WHERE clause

TO_DATE (alarm_datetime,'DD.MM.YYYY HH24:MI:SS')

and change the code to

alarm_datetime

The error comes from to_date conversion of a date column.

Added Explanation: Oracle converts your alarm_datetime into a string using its nls depended date format. After this it calls to_date with your provided date mask. This throws the exception.

Could not load file or assembly 'System.Data.SQLite'

This is very simple if you are not using SQLite:

You can delete the SQLite DLLs from your solution's bin folders, then from the folder where you reference ELMAH. Rebuild, and your app won't try to load this DLL that you are not using.

How to round up with excel VBA round()?

I had a problem where I had to round up only and these answers didnt work for how I had to have my code run so I used a different method. The INT function rounds towards negative (4.2 goes to 4, -4.2 goes to -5) Therefore, I changed my function to negative, applied the INT function, then returned it to positive simply by multiplying it by -1 before and after

Count = -1 * (int(-1 * x))

Fetch first element which matches criteria

I think this is the best way:

this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);

"unexpected token import" in Nodejs5 and babel?

Involve following steps to resolve the issue:

1) Install the CLI and env preset

$ npm install --save-dev babel-cli babel-preset-env

2) Create a .babelrc file

{
  "presets": ["env"]
}

3) configure npm start in package.json

"scripts": {
    "start": "babel-node ./server/app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

4) then start app

$ npm start

The type or namespace name 'System' could not be found

Try to

  1. Clean Solution
  2. Rebuild Solution

How do I pass multiple parameter in URL?

This

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"&param2="+lon);

must work. For whatever strange reason1, you need ? before the first parameter and & before the following ones.

Using a compound parameter like

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);

would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20 or + (but this is even worse style).


1 Stating that ? separates the path and the parameters and that & separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.

Convert array of JSON object strings to array of JS objects

If you really have:

var s = ['{"Select":"11", "PhotoCount":"12"}','{"Select":"21", "PhotoCount":"22"}'];

then simply:

var objs = $.map(s, $.parseJSON);

Here's a demo.

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

If you are testing a logic class and it is calling some internal void methods the doNothing is perfect.

What does <T> denote in C#

It is a generic type parameter, see Generics documentation.

T is not a reserved keyword. T, or any given name, means a type parameter. Check the following method (just as a simple example).

T GetDefault<T>()
{
    return default(T);
}

Note that the return type is T. With this method you can get the default value of any type by calling the method as:

GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00

.NET uses generics in collections, ... example:

List<int> integerList = new List<int>();

This way you will have a list that only accepts integers, because the class is instancited with the type T, in this case int, and the method that add elements is written as:

public class List<T> : ...
{
    public void Add(T item);
}

Some more information about generics.

You can limit the scope of the type T.

The following example only allows you to invoke the method with types that are classes:

void Foo<T>(T item) where T: class
{
}

The following example only allows you to invoke the method with types that are Circle or inherit from it.

void Foo<T>(T item) where T: Circle
{
}

And there is new() that says you can create an instance of T if it has a parameterless constructor. In the following example T will be treated as Circle, you get intellisense...

void Foo<T>(T item) where T: Circle, new()
{
    T newCircle = new T();
}

As T is a type parameter, you can get the object Type from it. With the Type you can use reflection...

void Foo<T>(T item) where T: class
{
    Type type = typeof(T);
}

As a more complex example, check the signature of ToDictionary or any other Linq method.

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

There isn't a T, however there is TKey and TSource. It is recommended that you always name type parameters with the prefix T as shown above.

You could name TSomethingFoo if you want to.

What is and how to fix System.TypeInitializationException error?

System.TypeInitializationException happens when the code that gets executed during the process of loading the type throws an exception.

When .NET loads the type, it must prepare all its static fields before the first time that you use the type. Sometimes, initialization requires running code. It is when that code fails that you get a System.TypeInitializationException.

In your specific case, the following three static fields run some code:

private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

Note that s_bstCommonAppData depends on s_commonAppData, but it is declared ahead of its dependency. Therefore, the value of s_commonAppData is null at the time that the Path.Combine is called, resulting in ArgumentNullException. Same goes for the s_bstUserDataDir and s_bstCommonAppData: they are declared in reverse order to the desired order of initialization.

Re-order the lines to fix this problem:

private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");

Selenium webdriver click google search

@Test
public void google_Search()
{
    WebDriver driver;
    driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    driver.manage().window().maximize();

    WebElement element = driver.findElement(By.name("q"));
    element.sendKeys("Cheese!\n");
    element.submit();

    //Wait until the google page shows the result
    WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));

    List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));

    //Get the url of third link and navigate to it
    String third_link = findElements.get(2).getAttribute("href");
    driver.navigate().to(third_link);
}

set dropdown value by text using jquery

$("#HowYouKnow option:eq(XXX)").attr('selected', 'selected');

where XXX is the index of the one you want.

List method to delete last element in list as well as all elements

you can use lst.pop() or del lst[-1]

pop() removes and returns the item, in case you don't want have a return use del

PostgreSQL unnest() with element number

Try:

select v.*, row_number() over (partition by id order by elem) rn from
(select
    id,
    unnest(string_to_array(elements, ',')) AS elem
 from myTable) v

How to detect when cancel is clicked on file input?

The following seems to work for me (on desktop, windows):

var openFile = function (mimeType, fileExtension) {
    var defer = $q.defer();
    var uploadInput = document.createElement("input");
    uploadInput.type = 'file';
    uploadInput.accept = '.' + fileExtension + ',' + mimeType;

    var hasActivated = false;

    var hasChangedBeenCalled = false;
    var hasFocusBeenCalled = false;
    var focusCallback = function () {
        if (hasActivated) {
            hasFocusBeenCalled = true;
            document.removeEventListener('focus', focusCallback, true);
            setTimeout(function () {
                if (!hasChangedBeenCalled) {
                    uploadInput.removeEventListener('change', changedCallback, true);
                    defer.resolve(null);
                }
            }, 300);
        }
    };

    var changedCallback = function () {
        uploadInput.removeEventListener('change', changedCallback, true);
        if (!hasFocusBeenCalled) {
            document.removeEventListener('focus', focusCallback, true);
        }
        hasChangedBeenCalled = true;
        if (uploadInput.files.length === 1) {
            //File picked
            var reader = new FileReader();
            reader.onload = function (e) {
                defer.resolve(e.target.result);
            };
            reader.readAsText(uploadInput.files[0]);
        }
        else {
            defer.resolve(null);
        }
    };
    document.addEventListener('focus', focusCallback, true); //Detect cancel
    uploadInput.addEventListener('change', changedCallback, true); //Detect when a file is picked
    uploadInput.click();
    hasActivated = true;
    return defer.promise;
}

This does use angularjs $q but you should be able to replace it with any other promise framework if needed.

Tested on IE11, Edge, Chrome, Firefox, but it does not seem to work on Chrome on a Android Tablet as it does not fire the Focus event.

How to dynamically update labels captions in VBA form?

Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

Truncate Decimal number not Round Off

Try this:

decimal original = GetSomeDecimal(); // 22222.22939393
int number1 = (int)original; // contains only integer value of origina number
decimal temporary = original - number1; // contains only decimal value of original number
int decimalPlaces = GetDecimalPlaces(); // 3
temporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer
temporary = (int)temporary; // removes all decimal places
temporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places
decimal result = original + temporary; // add integer and decimal places together

It can be writen shorter, but this is more descriptive.

EDIT: Short way:

decimal original = GetSomeDecimal(); // 22222.22939393
int decimalPlaces = GetDecimalPlaces(); // 3
decimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));

IIS7 Permissions Overview - ApplicationPoolIdentity

I fixed all my asp.net problems simply by creating a new user called IUSER with a password and added it the Network Service and User Groups. Then create all your virtual sites and applications set authentication to IUSER with its password.. set high level file access to include IUSER and BAM it fixed at least 3-4 issues including this one..

Dave

Concatenate two char* strings in a C program

When you use string literals, such as "this is a string" and in your case "sssss" and "kkkk", the compiler puts them in read-only memory. However, strcat attempts to write the second argument after the first. You can solve this problem by making a sufficiently sized destination buffer and write to that.

char destination[10]; // 5 times s, 4 times k, one zero-terminator
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
strcpy(destination, str1);
printf("%s",strcat(destination,str2));

Note that in recent compilers, you usually get a warning for casting string literals to non-const character pointers.

How to iterate through LinkedHashMap with lists as values

You can use the entry set and iterate over the entries which allows you to access both, key and value, directly.

for (Entry<String, ArrayList<String>> entry : test1.entrySet() {
     System.out.println(entry.getKey() + "/" + entry.getValue());
}

I tried this but get only returns string

Why do you think so? The method get returns the type E for which the generic type parameter was chosen, in your case ArrayList<String>.

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

The 'export' keyword is the way to separate out template implementation from template declaration. This was introduced in C++ standard without an existing implementation. In due course only a couple of compilers actually implemented it. Read in depth information at Inform IT article on export

Select count(*) from multiple tables

JOIN with different tables

SELECT COUNT(*) FROM (  
SELECT DISTINCT table_a.ID  FROM table_a JOIN table_c ON table_a.ID  = table_c.ID   );

Is there any kind of hash code function in JavaScript?

If you truly want set behavior (I'm going by Java knowledge), then you will be hard pressed to find a solution in JavaScript. Most developers will recommend a unique key to represent each object, but this is unlike set, in that you can get two identical objects each with a unique key. The Java API does the work of checking for duplicate values by comparing hash code values, not keys, and since there is no hash code value representation of objects in JavaScript, it becomes almost impossible to do the same. Even the Prototype JS library admits this shortcoming, when it says:

"Hash can be thought of as an associative array, binding unique keys to values (which are not necessarily unique)..."

http://www.prototypejs.org/api/hash

Convert NSDate to NSString

If you are on Mac OS X you can write:

NSString* s = [[NSDate date] descriptionWithCalendarFormat:@"%Y_%m_%d_%H_%M_%S" timeZone:nil locale:nil];

However this is not available on iOS.

Detecting when user scrolls to bottom of div with jQuery

$(window).on("scroll", function() {
    //get height of the (browser) window aka viewport
    var scrollHeight = $(document).height();
    // get height of the document 
    var scrollPosition = $(window).height() + $(window).scrollTop();
    if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
        // code to run when scroll to bottom of the page
    }
});

This is the code on github.

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

How to read request body in an asp.net core webapi controller?

To be able to rewind the request body, @Jean's answer helped me come up with a solution that seems to work well. I currently use this for Global Exception Handler Middleware but the principle is the same.

I created a middleware that basically enables the rewind on the request body (instead of a decorator).

using Microsoft.AspNetCore.Http.Internal;
[...]
public class EnableRequestRewindMiddleware
{
    private readonly RequestDelegate _next;

    public EnableRequestRewindMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        context.Request.EnableRewind();
        await _next(context);
    }
}

public static class EnableRequestRewindExtension
{
    public static IApplicationBuilder UseEnableRequestRewind(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<EnableRequestRewindMiddleware>();
    }
}

This can then be used in your Startup.cs like so:

[...]
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    [...]
    app.UseEnableRequestRewind();
    [...]
}

Using this approach, I have been able to rewind the request body stream successfully.

Pandas index column title or name

df.index.name should do the trick.

Python has a dir function that let's you query object attributes. dir(df.index) was helpful here.

Anaconda site-packages

At least with Miniconda (I assume it's the same for Anaconda), within the environment folder, the packages are installed in a folder called \conda-meta.

i.e.

C:\Users\username\Miniconda3\envs\environmentname\conda-meta

If you install on the base environment, the location is:

C:\Users\username\Miniconda3\pkgs

How to convert Strings to and from UTF8 byte arrays in Java

I can't comment but don't want to start a new thread. But this isn't working. A simple round trip:

byte[] b = new byte[]{ 0, 0, 0, -127 };  // 0x00000081
String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000,  0x0000, 0xfffd
b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081

I'd need b[] the same array before and after encoding which it isn't (this referrers to the first answer).

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

I know its been a while since the question was asked but I was able to find a solution:

int sockfd;
int option = 1;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));

This set the socket able to be reused immediately.

I apologize if this is "wrong". I'm not very experienced with sockets

Running Java Program from Command Line Linux

Guys let's understand the syntax of it.

  1. If class file is present in the Current Dir.

    java -cp . fileName

  2. If class file is present within the Dir. Go to the Parent Dir and enter below cmd.

    java -cp . dir1.dir2.dir3.fileName

  3. If there is a dependency on external jars then,

    java -cp .:./jarName1:./jarName2 fileName

    Hope this helps.

jQuery - passing value from one input to another

It's simpler if you modify your HTML a little bit:

<label for="first_name">First Name</label>
<input type="text" id="name" name="name" />

<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" />

<label for="firstname">Firstname</label>
<input type="text" id="firstname" name="firstname" disabled="disabled" />

then it's relatively simple

$(document).ready(function() { 
    $('#name').change(function() {
      $('#firstname').val($('#name').val());
    });
});

How Exactly Does @param Work - Java

@param is a special format comment used by javadoc to generate documentation. it is used to denote a description of the parameter (or parameters) a method can receive. there's also @return and @see used to describe return values and related information, respectively:

http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#format

has, among other things, this:

/**
 * Returns an Image object that can then be painted on the screen. 
 * The url argument must specify an absolute {@link URL}. The name
 * argument is a specifier that is relative to the url argument. 
 * <p>
 * This method always returns immediately, whether or not the 
 * image exists. When this applet attempts to draw the image on
 * the screen, the data will be loaded. The graphics primitives 
 * that draw the image will incrementally paint on the screen. 
 *
 * @param  url  an absolute URL giving the base location of the image
 * @param  name the location of the image, relative to the url argument
 * @return      the image at the specified URL
 * @see         Image
 */
 public Image getImage(URL url, String name) {

What is the difference between YAML and JSON?

GIT and YAML

The other answers are good. Read those first. But I'll add one other reason to use YAML sometimes: git.

Increasingly, many programming projects use git repositories for distribution and archival. And, while a git repo's history can equally store JSON and YAML files, the "diff" method used for tracking and displaying changes to a file is line-oriented. Since YAML is forced to be line-oriented, any small changes in a YAML file are easier to see by a human.

It is true, of course, that JSON files can be "made pretty" by sorting the strings/keys and adding indentation. But this is not the default and I'm lazy.

Personally, I generally use JSON for system-to-system interaction. I often use YAML for config files, static files, and tracked files. (I also generally avoid adding YAML relational anchors. Life is too short to hunt down loops.)

Also, if speed and space are really a concern, I don't use either. You might want to look at BSON.

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it!

WebSocket with SSL

You can't use WebSockets over HTTPS, but you can use WebSockets over TLS (HTTPS is HTTP over TLS). Just use "wss://" in the URI.

I believe recent version of Firefox won't let you use non-TLS WebSockets from an HTTPS page, but the reverse shouldn't be a problem.

What is Model in ModelAndView from Spring MVC?

Well, WelcomeMessage is just a variable name for message (actual model with data). Basically, you are binding the model with the welcomePage here. The Model (message) will be available in welcomePage.jsp as WelcomeMessage. Here is a simpler example:

ModelAndView("hello","myVar", "Hello World!");

In this case, my model is a simple string (In applications this will be a POJO with data fetched for DB or other sources.). I am assigning it to myVar and my view is hello.jsp. Now, myVar is available for me in hello.jsp and I can use it for display.

In the view, you can access the data though:

${myVar}

Similarly, You will be able to access the model through WelcomeMessage variable.

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

You have to add THEN

IF EXISTS(SELECT * FROM component_psar WHERE tbl_id = '2' AND row_nr = '1') 
THEN
UPDATE component_psar SET col_1 = '1', col_2 = '1', col_3 = '1', col_4 = '1', col_5 = '1', col_6 = '1', unit = '1', add_info = '1', fsar_lock = '1' WHERE tbl_id = '2' AND row_nr = '1' 
ELSE 
INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock) VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')

Changing font size and direction of axes text in ggplot2

Using "fill" attribute helps in cases like this. You can remove the text from axis using element_blank()and show multi color bar chart with a legend. I am plotting a part removal frequency in a repair shop as below

ggplot(data=df_subset,aes(x=Part,y=Removal_Frequency,fill=Part))+geom_bar(stat="identity")+theme(axis.text.x  = element_blank())

I went for this solution in my case as I had many bars in bar chart and I was not able to find a suitable font size which is both readable and also small enough not to overlap each other.

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

Make sure to check dynamic web app in "other section" i.e File>New>Other>Web or type in "dynamic web app" in your wizard filter. If dynamic web app is not there then follow following steps:

  1. On Eclipse Menu Select HELP > INSTALL NEW SOFTWARE
  2. In work with test box simply type in your eclipse version, which is oxygen in my case
  3. Once you type in yur version something like this "Oxygen - http://download.eclipse.org/releases/oxygen"will be recommended to you in drop down
  4. If you do not get any recommendation then simply copy " http://download.eclipse.org/releases/your-version" and paste it. Make sure to edit your-version.
  5. After you Enter the address and press enter bunch of new softwares will be listed just ubderneath work with text box.
  6. Scroll, find and Expand WEB, XML, Java EE .... tab
  7. Select only these three options: Eclipse Java EE Developer Tools, Eclipse Java Web Developer Tools,Eclipse Web Developer Tools
  8. Next, next and finish!

Android Firebase, simply get one child object's data

just fetch specific node data and its working perfect for me

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});

How to delete last character in a string in C#?

Personally I would go with Rob's suggestion, but if you want to remove one (or more) specific trailing character(s) you can use TrimEnd. E.g.

paramstr = paramstr.TrimEnd('&');

How to drop SQL default constraint without knowing its name?

Useful for some columns that had multiple default constraints or check constraints created:

Modified https://stackoverflow.com/a/16359095/206730 script

Note: this script is for sys.check_constraints

declare @table_name nvarchar(128)
declare @column_name nvarchar(128)
declare @constraint_name nvarchar(128)
declare @constraint_definition nvarchar(512)

declare @df_name nvarchar(128)
declare @cmd nvarchar(128) 

PRINT 'DROP CONSTRAINT [Roles2016.UsersCRM].Estado'

declare constraints cursor for 
 select t.name TableName, c.name ColumnName, d.name ConstraintName, d.definition ConstraintDefinition
 from sys.tables t   
 join sys.check_constraints d  on d.parent_object_id = t.object_id  
 join sys.columns c  on c.object_id = t.object_id      
 and c.column_id = d.parent_column_id
 where t.name = N'Roles2016.UsersCRM' and c.name = N'Estado'

open constraints
fetch next from constraints into @table_name , @column_name, @constraint_name, @constraint_definition
while @@fetch_status = 0
BEGIN
    print 'CONSTRAINT: ' + @constraint_name
    select @cmd = 'ALTER TABLE [' + @table_name +  '] DROP CONSTRAINT [' +  @constraint_name + ']'
    print @cmd
    EXEC sp_executeSQL @cmd;

  fetch next from constraints into @table_name , @column_name, @constraint_name, @constraint_definition
END

close constraints 
deallocate constraints

Remove all occurrences of a value from a list?

hello =  ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
#chech every item for a match
for item in range(len(hello)-1):
     if hello[item] == ' ': 
#if there is a match, rebuild the list with the list before the item + the list after the item
         hello = hello[:item] + hello [item + 1:]
print hello

['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

Resolving IP Address from hostname with PowerShell

Use Resolve-DnsName cmdlet.

Resolve-DnsName computername | FT Name, IPAddress -HideTableHeaders | Out-File -Append c:\filename.txt

PS C:\> Resolve-DnsName stackoverflow.com

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
stackoverflow.com                              A      130   Answer     151.101.65.69
stackoverflow.com                              A      130   Answer     151.101.129.69
stackoverflow.com                              A      130   Answer     151.101.193.69
stackoverflow.com                              A      130   Answer     151.101.1.69

PS C:\> Resolve-DnsName stackoverflow.com | Format-Table Name, IPAddress -HideTableHeaders

stackoverflow.com 151.101.65.69
stackoverflow.com 151.101.1.69
stackoverflow.com 151.101.193.69
stackoverflow.com 151.101.129.69

PS C:\> Resolve-DnsName -Type A google.com

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
google.com                                     A      16    Answer     216.58.193.78


PS C:\> Resolve-DnsName -Type AAAA google.com

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
google.com                                     AAAA   223   Answer     2607:f8b0:400e:c04::64

Can Flask have optional URL parameters?

Since Flask 0.10 you can`t add multiple routes to one endpoint. But you can add fake endpoint

@user.route('/<userId>')
def show(userId):
   return show_with_username(userId)

@user.route('/<userId>/<username>')
def show_with_username(userId,username=None):
   pass

When and why do I need to use cin.ignore() in C++?

It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.

How can I find the method that called the current method?

We can improve on Mr Assad's code (the current accepted answer) just a little bit by instantiating only the frame we actually need rather than the entire stack:

new StackFrame(1).GetMethod().Name;

This might perform a little better, though in all likelihood it still has to use the full stack to create that single frame. Also, it still has the same caveats that Alex Lyman pointed out (optimizer/native code might corrupt the results). Finally, you might want to check to be sure that new StackFrame(1) or .GetFrame(1) don't return null, as unlikely as that possibility might seem.

See this related question: Can you use reflection to find the name of the currently executing method?

How to get All input of POST in Laravel

Try this :

use Illuminate\Support\Facades\Request;
public function add_question(Request $request)
{
    return $request->all();
}

T-SQL split string

All the functions for string splitting that use some kind of Loop-ing (iterations) have bad performance. They should be replaced with set-based solution.

This code executes excellent.

CREATE FUNCTION dbo.SplitStrings
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN 
   (  
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM 
      ( 
        SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)
   );
GO

How to get PID of process by specifying process name and store it in a variable to use further?

If you want to kill -9 based on a string (you might want to try kill first) you can do something like this:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}'

This will show you what you're about to kill (very, very important) and just pipe it to sh when the time comes to execute:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}' | sh

RecyclerView onClick

Check out a similar question @CommonsWare's comment links to this, which implements the OnClickListener interface in the viewHolder.

Here's a simple example of the ViewHolder:

    TextView textView;//declare global with in adapter class

public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

      private ViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
            textView = (TextView)view.findViewById(android.R.id.text1);

      }

      @Override
      public void onClick(View view) {
            Toast.makeText(view.getContext(), "position = " + getLayoutPosition(), Toast.LENGTH_SHORT).show();

         //go through each item if you have few items within recycler view
        if(getLayoutPosition()==0){
           //Do whatever you want here

        }else if(getLayoutPosition()==1){ 
           //Do whatever you want here         

        }else if(getLayoutPosition()==2){

        }else if(getLayoutPosition()==3){

        }else if(getLayoutPosition()==4){

        }else if(getLayoutPosition()==5){

        }

        //or you can use For loop if you have long list of items. Use its length or size of the list as 
        for(int i = 0; i<exampleList.size(); i++){

        }


      }
  }

The Adapter then looks like this:

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view =LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);

        return new ViewHolder(view);
    }

Unsupported operation :not writeable python

You open the variable "file" as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the 'w' flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

How do you Programmatically Download a Webpage in Java

Here's some tested code using Java's URL class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.

public static void main(String[] args) {
    URL url;
    InputStream is = null;
    BufferedReader br;
    String line;

    try {
        url = new URL("http://stackoverflow.com/");
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException mue) {
         mue.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
}

MySQL - ERROR 1045 - Access denied

If you actually have set a root password and you've just lost/forgotten it:

  1. Stop MySQL
  2. Restart it manually with the skip-grant-tables option: mysqld_safe --skip-grant-tables

  3. Now, open a new terminal window and run the MySQL client: mysql -u root

  4. Reset the root password manually with this MySQL command: UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; If you are using MySQL 5.7 (check using mysql --version in the Terminal) then the command is:

    UPDATE mysql.user SET authentication_string=PASSWORD('password')  WHERE  User='root';
    
  5. Flush the privileges with this MySQL command: FLUSH PRIVILEGES;

From http://www.tech-faq.com/reset-mysql-password.shtml

(Maybe this isn't what you need, Abs, but I figure it could be useful for people stumbling across this question in the future)

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

It's more than likely because you've used Console in the namespace. For example like this:

namespace XYZApplication.Console
{
    class Program
    {
        static void Main(string[] args)
       {
            //Some code;             
       }
    }
}

Try removing it from the namespace or use the full namespace instead i.e.

   System.Console.Writeline("abc");

Is there a sleep function in JavaScript?

If you are looking to block the execution of code with call to sleep, then no, there is no method for that in JavaScript.

JavaScript does have setTimeout method. setTimeout will let you defer execution of a function for x milliseconds.

setTimeout(myFunction, 3000);

// if you have defined a function named myFunction 
// it will run after 3 seconds (3000 milliseconds)

Remember, this is completely different from how sleep method, if it existed, would behave.

function test1()
{    
    // let's say JavaScript did have a sleep function..
    // sleep for 3 seconds
    sleep(3000);

    alert('hi'); 
}

If you run the above function, you will have to wait for 3 seconds (sleep method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep function like that in JavaScript.

function test2()
{
    // defer the execution of anonymous function for 
    // 3 seconds and go to next line of code.
    setTimeout(function(){ 

        alert('hello');
    }, 3000);  

    alert('hi');
}

If you run test2, you will see 'hi' right away (setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'.

How to add headers to OkHttp request interceptor?

If you are using Retrofit library then you can directly pass header to api request using @Header annotation without use of Interceptor. Here is example that shows how to add header to Retrofit api request.

@POST(apiURL)
void methodName(
        @Header(HeadersContract.HEADER_AUTHONRIZATION) String token,
        @Header(HeadersContract.HEADER_CLIENT_ID) String token,
        @Body TypedInput body,
        Callback<String> callback);

Hope it helps!

Java 8 Streams: multiple filters vs. complex condition

This is the result of the 6 different combinations of the sample test shared by @Hank D It's evident that predicate of form u -> exp1 && exp2 is highly performant in all the cases.

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=3372, min=31, average=33.720000, max=47}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9150, min=85, average=91.500000, max=118}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9046, min=81, average=90.460000, max=150}

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8336, min=77, average=83.360000, max=189}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9094, min=84, average=90.940000, max=176}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10501, min=99, average=105.010000, max=136}

two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=11117, min=98, average=111.170000, max=238}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8346, min=77, average=83.460000, max=113}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9089, min=81, average=90.890000, max=137}

two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10434, min=98, average=104.340000, max=132}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9113, min=81, average=91.130000, max=179}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8258, min=77, average=82.580000, max=100}

one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9131, min=81, average=91.310000, max=139}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10265, min=97, average=102.650000, max=131}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8442, min=77, average=84.420000, max=156}

one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8553, min=81, average=85.530000, max=125}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8219, min=77, average=82.190000, max=142}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10305, min=97, average=103.050000, max=132}

CreateProcess: No such file or directory

Although post is old I had the same problem with mingw32 vers 4.8.1 on 2015/02/13. Compiling using Eclipse CDT failed with this message. Trying from command line with -v option also failed. I was also missing the cc1plus executable.

The cause: I downloaded the command line and graphical installer from the mingw32 site. I used this to do my initial install of mingw32. Using the GUI I selected the base tools, selecting both the c and c++ compilers.

This installer did an incomplete install of the 32 bit c++ compiler. I had the g++ and cpp files but not the cc1plus executable. Trying to do an 'update' failed because the installer assumed I had everything installed.

To fix I found these sites: http://mingw-w64.sourceforge.net/ http://sourceforge.net/projects/mingw-w64/ I downloaded and ran this 'online install'. Sure enough this one contained the missing files. I modified my PATH variable and pointed to the 'bin' folder containing the g++ executable. Rebooted. Installed 64 bit Eclipse. Opened Eclipse and the 'Hello World' c++ program compiled, executed, and debugged properly.

Note: the 64bit installer seems to default to UNIX settings. Why can't an installer determine the OS??? Make sure to change them.

I spent an entire evening dealing with this. Hope this helps someone.

C# "as" cast vs classic cast

With the "classic" method, if the cast fails, an InvalidCastException is thrown. With the as method, it results in null, which can be checked for, and avoid an exception being thrown.

Also, you can only use as with reference types, so if you are typecasting to a value type, you must still use the "classic" method.

Note:

The as method can only be used for types that can be assigned a null value. That use to only mean reference types, but when .NET 2.0 came out, it introduced the concept of a nullable value type. Since these types can be assigned a null value, they are valid to use with the as operator.

How to exclude particular class name in CSS selector?

In modern browsers you can do:

.reMode_hover:not(.reMode_selected):hover{}

Consult http://caniuse.com/css-sel3 for compatibility information.

addEventListener in Internet Explorer

I would use these polyfill https://github.com/WebReflection/ie8

<!--[if IE 8]><script
  src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->

How to check Spark Version

According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.

Using continue in a switch statement

This might be a megabit to late but you can use continue 2.

Some php builds / configs will output this warning:

PHP Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

For example:

$i = 1;

while ($i <= 10) {
    $mod = $i % 4;
    echo "\r\n out $i";
    $i++;
    switch($mod)
    {
        case 0:
            break;
        case 2:
            continue;
            break;
        default:
            continue 2;
            break;
    }
    echo " is even";
}

This will output:

out 1
out 2 is even
out 3
out 4 is even
out 5
out 6 is even
out 7
out 8 is even
out 9
out 10 is even

Tested with PHP 5.5 and higher.

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

I did encounter this problem. This is due to you computer architecture and the database architecture you are using.

If you're using 32 bits operating system then everything works well because you can only install 32 bits software. Problem comes when you're using the 64 bits operating system.

In order to solve this problem is simple - I took long time to discover this issue.

  1. Knowing your Operating System is 64 bits but your Microsoft Office is 32 bits.
  2. So in order for you to access your database using NetBean IDE (assuming you're using this), you need to install 32 bits JDK. If you have installed 64 bits, you have to uninstall it and install the 32 bits.

You're unable to access your database because your 64 bits JVM is not the same as 32 bit JVM.

To add your database into your system 1. Control Panel 2. Administrator Tools 3. Data Source (ODBC) right click on it change the target to \sysWOW64\odbcad32.exe change the start in to r%\SysWOW64

Then you should be able to run. Inform me if you have any problem with this.

Thank you!

Pythonic way to check if a list is sorted or not

As noted by @aaronsterling the following solution is the shortest and seems fastest when the array is sorted and not too small: def is_sorted(lst): return (sorted(lst) == lst)

If most of the time the array is not sorted, it would be desirable to use a solution that does not scan the entire array and returns False as soon as an unsorted prefix is discovered. Following is the fastest solution I could find, it is not particularly elegant:

def is_sorted(lst):
    it = iter(lst)
    try:
        prev = it.next()
    except StopIteration:
        return True
    for x in it:
        if prev > x:
            return False
        prev = x
    return True

Using Nathan Farrington's benchmark, this achieves better runtime than using sorted(lst) in all cases except when running on the large sorted list.

Here are the benchmark results on my computer.

sorted(lst)==lst solution

  • L1: 1.23838591576
  • L2: 4.19063091278
  • L3: 1.17996287346
  • L4: 4.68399500847

Second solution:

  • L1: 0.81095790863
  • L2: 0.802397012711
  • L3: 1.06135106087
  • L4: 8.82761001587

Setting public class variables

If you are going to follow the examples given (using getter/setter or setting it in the constructor) change it to private since those are ways to control what is set in the variable.

It doesn't make sense to keep the property public with all those things added to the class.

C# 30 Days From Todays Date

@Ed courtenay, @James, I have one stupid question. How to keep user away from this file?(File containing expiry date). If the user has installation rights, then obviously user has access to view files also. Changing the extension of file wont help. So, how to keep this file safe and away from users hands?

How do you make an element "flash" in jQuery

$("#someElement").fadeTo(3000, 0.3 ).fadeTo(3000, 1).fadeTo(3000, 0.3 ).fadeTo(3000, 1); 

3000 is 3 seconds

From opacity 1 it is faded to 0.3, then to 1 and so on.

You can stack more of these.

Only jQuery is needed. :)

Java ArrayList of Doubles

You are encountering a problem because you cannot construct the ArrayList and populate it at the same time. You either need to create it and then manually populate it as such:

ArrayList list = new ArrayList<Double>();
list.add(1.38);
...

Or, alternatively if it is more convenient for you, you can populate the ArrayList from a primitive array containing your values. For example:

Double[] array = {1.38, 2.56, 4.3};
ArrayList<Double> list = new ArrayList<Double>(Arrays.asList(array));

Creating a daemon in Linux

If your app is one of:

{
  ".sh": "bash",
  ".py": "python",
  ".rb": "ruby",
  ".coffee" : "coffee",
  ".php": "php",
  ".pl" : "perl",
  ".js" : "node"
}

and you don't mind a NodeJS dependency then install NodeJS and then:

npm install -g pm2

pm2 start yourapp.yourext --name "fred" # where .yourext is one of the above

pm2 start yourapp.yourext -i 0 --name "fred" # run your app on all cores

pm2 list

To keep all apps running on reboot (and daemonise pm2):

pm2 startup

pm2 save

Now you can:

service pm2 stop|restart|start|status

(also easily allows you to watch for code changes in your app directory and auto restart the app process when a code change happens)

Where is the application.properties file in a Spring Boot project?

You can create it manually but the default location of application.properties is here

enter image description here

C# Checking if button was clicked

These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.

if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
   //Do not reload the gridview.

}
else
{
   reload my gridview.
}

SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked

How to send data with angularjs $http.delete() request?

$http.delete method doesn't accept request body. You can try this workaround :

$http( angular.merge({}, config || {}, {
    method  : 'delete',
    url     : _url,
    data    : _data
}));

where in config you can pass config data like headers etc.

Reading binary file and looping over each byte

If you have a lot of binary data to read, you might want to consider the struct module. It is documented as converting "between C and Python types", but of course, bytes are bytes, and whether those were created as C types does not matter. For example, if your binary data contains two 2-byte integers and one 4-byte integer, you can read them as follows (example taken from struct documentation):

>>> struct.unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)

You might find this more convenient, faster, or both, than explicitly looping over the content of a file.

Using ADB to capture the screen

To start recording your device’s screen, run the following command:

adb shell screenrecord /sdcard/example.mp4

This command will start recording your device’s screen using the default settings and save the resulting video to a file at /sdcard/example.mp4 file on your device.

When you’re done recording, press Ctrl+C in the Command Prompt window to stop the screen recording. You can then find the screen recording file at the location you specified. Note that the screen recording is saved to your device’s internal storage, not to your computer.

The default settings are to use your device’s standard screen resolution, encode the video at a bitrate of 4Mbps, and set the maximum screen recording time to 180 seconds. For more information about the command-line options you can use, run the following command:

adb shell screenrecord --help

This works without rooting the device. Hope this helps.

Android: textview hyperlink

You could have two separate TextViews and you could align them accordingly in your layout if needed:

    Text1.setText(
        Html.fromHtml(
            "<a href=\"http://www.google.com\">google</a> "));
    Text1.setMovementMethod(LinkMovementMethod.getInstance());

    Text2.setText(
            Html.fromHtml(
                "<a href=\"http://www.stackoverflow.com\">stackoverflow</a> "));
    Text2.setMovementMethod(LinkMovementMethod.getInstance());

Then if you want to strip the "link underline". Create a class:

public class URLSpanNoUnderline extends URLSpan {
    public URLSpanNoUnderline(String url) {
        super(url);
    }
    @Override public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setUnderlineText(false);
        }
}

Then add this method in your main Activity class where you have the TextViews

private void stripUnderlines(TextView textView) {
    Spannable s = new SpannableString(textView.getText());
    URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
    for (URLSpan span: spans) {
        int start = s.getSpanStart(span);
        int end = s.getSpanEnd(span);
        s.removeSpan(span);
        span = new URLSpanNoUnderline(span.getURL());
        s.setSpan(span, start, end, 0);
    }
    textView.setText(s);
}

And then just call this after you initialised the TextViews (in your onCreate):

stripUnderlines(Text1);
stripUnderlines(Text2);

CSS: stretching background image to 100% width and height of screen?

The VH unit can be used to fill the background of the viewport, aka the browser window.

(height:100vh;)

html{
    height:100%;
    }
.body {
     background: url(image.jpg) no-repeat center top; 
     background-size: cover; 
     height:100vh;     
}

How to change the datetime format in pandas

The below code worked for me instead of the previous one - try it out !

df['DOB']=pd.to_datetime(df['DOB'].astype(str), format='%m/%d/%Y')

Turn off enclosing <p> tags in CKEditor 3.0

Found it!

ckeditor.js line #91 ... search for

B.config.enterMode==3?'div':'p'

change to

B.config.enterMode==3?'div':'' (NO P!)

Dump your cache and BAM!

WCF ServiceHost access rights

Open Visual Studio as an Administrator.. It will run.

How do I format currencies in a Vue component?

With vuejs 2, you could use vue2-filters which does have other goodies as well.

npm install vue2-filters


import Vue from 'vue'
import Vue2Filters from 'vue2-filters'

Vue.use(Vue2Filters)

Then use it like so:

{{ amount | currency }} // 12345 => $12,345.00

Ref: https://www.npmjs.com/package/vue2-filters

Commenting out a set of lines in a shell script

You can use a 'here' document with no command to send it to.

#!/bin/bash
echo "Say Something"
<<COMMENT1
    your comment 1
    comment 2
    blah
COMMENT1
echo "Do something else"

Wikipedia Reference

How can I store the result of a system command in a Perl variable?

The easiest way is to use the `` feature in Perl. This will execute what is inside and return what was printed to stdout:

 my $pid = 5892;
 my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`;
 print "not = $var\n";

This should do it.

Angular 1.6.0: "Possibly unhandled rejection" error

It may not be your speficic situation, but I had a similar problem.

In my case, I was using angular-i18n, and getting the locale dictionary asynchronously. The problem was that the json file it was getting was incorrectly indented (mixing spaces and tabs). The GET request didn't failed.

Correcting the indentation solved the problem.

REST API 404: Bad URI, or Missing Resource?

As with most things, "it depends". But to me, your practice is not bad and is not going against the HTTP spec per se. However, let's clear some things up.

First, URI's should be opaque. Even if they're not opaque to people, they are opaque to machines. In other words, the difference between http://mywebsite/api/user/13, http://mywebsite/restapi/user/13 is the same as the difference between http://mywebsite/api/user/13 and http://mywebsite/api/user/14 i.e. not the same is not the same period. So a 404 would be completely appropriate for http://mywebsite/api/user/14 (if there is no such user) but not necessarily the only appropriate response.

You could also return an empty 200 response or more explicitly a 204 (No Content) response. This would convey something else to the client. It would imply that the resource identified by http://mywebsite/api/user/14 has no content or is essentially nothing. It does mean that there is such a resource. However, it does not necessarily mean that you are claiming there is some user persisted in a data store with id 14. That's your private concern, not the concern of the client making the request. So, if it makes sense to model your resources that way, go ahead.

There are some security implications to giving your clients information that would make it easier for them to guess legitimate URI's. Returning a 200 on misses instead of a 404 may give the client a clue that at least the http://mywebsite/api/user part is correct. A malicious client could just keep trying different integers. But to me, a malicious client would be able to guess the http://mywebsite/api/user part anyway. A better remedy would be to use UUID's. i.e. http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66 is better than http://mywebsite/api/user/14. Doing that, you could use your technique of returning 200's without giving much away.

Asynchronous Process inside a javascript for loop

JavaScript code runs on a single thread, so you cannot principally block to wait for the first loop iteration to complete before beginning the next without seriously impacting page usability.

The solution depends on what you really need. If the example is close to exactly what you need, @Simon's suggestion to pass i to your async process is a good one.

How to use ArrayAdapter<myClass>

You could just add a toString() method to MyClass, per http://developer.android.com/reference/android/widget/ArrayAdapter.html:

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

class MyClass {

 @Override
 public String toString() {
  return "Hello, world.";
 }
}

Injecting @Autowired private field during testing

I believe in order to have auto-wiring work on your MyLauncher class (for myService), you will need to let Spring initialize it instead of calling the constructor, by auto-wiring myLauncher. Once that is being auto-wired (and myService is also getting auto-wired), Spring (1.4.0 and up) provides a @MockBean annotation you can put in your test. This will replace a matching single beans in context with a mock of that type. You can then further define what mocking you want, in a @Before method.

public class MyLauncherTest
    @MockBean
    private MyService myService;

    @Autowired
    private MyLauncher myLauncher;

    @Before
    private void setupMockBean() {
        doNothing().when(myService).someVoidMethod();
        doReturn("Some Value").when(myService).someStringMethod();
    }

    @Test
    public void someTest() {
        myLauncher.doSomething();
    }
}

Your MyLauncher class can then remain unmodified, and your MyService bean will be a mock whose methods return values as you defined:

@Component
public class MyLauncher {
    @Autowired
    MyService myService;

    public void doSomething() {
        myService.someVoidMethod();
        myService.someMethodThatCallsSomeStringMethod();
    }

    //other methods
}

A couple advantages of this over other methods mentioned is that:

  1. You don't need to manually inject myService.
  2. You don't need use the Mockito runner or rules.

difference between primary key and unique key

A primary key has the semantic of identifying the row of a database. Therefore there can be only one primary key for a given table, while there can be many unique keys.

Also for the same reason a primary key cannot be NULL (at least in Oracle, not sure about other databases)

Since it identifies the row it should never ever change. Changing primary keys are bound to cause serious pain and probably eternal damnation.

Therefor in most cases you want some artificial id for primary key which isn't used for anything but identifying single rows in the table.

Unique keys on the other hand may change as much as you want.

Move SQL data from one table to another

It will create a table and copy all the data from old table to new table

SELECT * INTO event_log_temp FROM event_log

And you can clear the old table data.

DELETE FROM event_log

How to change date format using jQuery?

var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

curr_year = curr_year.toString().substr(2,2);

document.write(curr_date+"-"+curr_month+"-"+curr_year);

You can change this as your need..

Why Git is not allowing me to commit even after configuration?

That’s a typo. You’ve accidently set user.mail with no e. Fix it by setting user.email in the global configuration with

git config --global user.email "[email protected]"

How to add a response header on nginx when using proxy_pass?

add_header works as well with proxy_pass as without. I just today set up a configuration where I've used exactly that directive. I have to admit though that I've struggled as well setting this up without exactly recalling the reason, though.

Right now I have a working configuration and it contains the following (among others):

server {
    server_name  .myserver.com
    location / {
        proxy_pass  http://mybackend;
        add_header  X-Upstream  $upstream_addr;
    }
}

Before nginx 1.7.5 add_header worked only on successful responses, in contrast to the HttpHeadersMoreModule mentioned by Sebastian Goodman in his answer.

Since nginx 1.7.5 you can use the keyword always to include custom headers even in error responses. For example:

add_header X-Upstream $upstream_addr always;

Limitation: You cannot override the server header value using add_header.

How to generate keyboard events?

regarding the recommended answer's code,

For my bot the recommended answer did not work. This is because I'm using Chrome which is requiring me to use KEYEVENTF_SCANCODE in my dwFlags.

To get his code to work I had to modify these code blocks:

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

    def __init__(self, *args, **kwds):
        super(KEYBDINPUT, self).__init__(*args, **kwds)
        # some programs use the scan code even if KEYEVENTF_SCANCODE
        # isn't set in dwFflags, so attempt to map the correct code.
        #if not self.dwFlags & KEYEVENTF_UNICODE:l
            #self.wScan = user32.MapVirtualKeyExW(self.wVk,
                                                 #MAPVK_VK_TO_VSC, 0)
            # ^MAKE SURE YOU COMMENT/REMOVE THIS CODE^

def PressKey(keyCode):
    input = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wScan=keyCode,
                            dwFlags=KEYEVENTF_SCANCODE))
    user32.SendInput(1, ctypes.byref(input), ctypes.sizeof(input))

def ReleaseKey(keyCode):
    input = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wScan=keyCode,
                            dwFlags=KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP))
    user32.SendInput(1, ctypes.byref(input), ctypes.sizeof(input))

time.sleep(5) # sleep to open browser tab
PressKey(0x26) # press right arrow key
time.sleep(2) # hold for 2 seconds
ReleaseKey(0x26) # release right arrow key

I hope this helps someone's headache!

How can I write a byte array to a file in Java?

No need for external libs to bloat things - especially when working with Android. Here is a native solution that does the trick. This is a pice of code from an app that stores a byte array as an image file.

    // Byte array with image data.
    final byte[] imageData = params[0];

    // Write bytes to tmp file.
    final File tmpImageFile = new File(ApplicationContext.getInstance().getCacheDir(), "scan.jpg");
    FileOutputStream tmpOutputStream = null;
    try {
        tmpOutputStream = new FileOutputStream(tmpImageFile);
        tmpOutputStream.write(imageData);
        Log.d(TAG, "File successfully written to tmp file");
    }
    catch (FileNotFoundException e) {
        Log.e(TAG, "FileNotFoundException: " + e);
        return null;
    }
    catch (IOException e) {
        Log.e(TAG, "IOException: " + e);
        return null;
    }
    finally {
        if(tmpOutputStream != null)
            try {
                tmpOutputStream.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e);
            }
    }

Best way to create a simple python web service

If you mean "web service" in SOAP/WSDL sense, you might want to look at Generating a WSDL using Python and SOAPpy

When to use Task.Delay, when to use Thread.Sleep?

I want to add something. Actually, Task.Delay is a timer based wait mechanism. If you look at the source you would find a reference to a Timer class which is responsible for the delay. On the other hand Thread.Sleep actually makes current thread to sleep, that way you are just blocking and wasting one thread. In async programming model you should always use Task.Delay() if you want something(continuation) happen after some delay.

Promise.all().then() resolve?

Your return data approach is correct, that's an example of promise chaining. If you return a promise from your .then() callback, JavaScript will resolve that promise and pass the data to the next then() callback.

Just be careful and make sure you handle errors with .catch(). Promise.all() rejects as soon as one of the promises in the array rejects.

What's the best way to loop through a set of elements in JavaScript?

I think using the first form is probably the way to go, since it's probably by far the most common loop structure in the known universe, and since I don't believe the reverse loop saves you any time in reality (still doing an increment/decrement and a comparison on each iteration).

Code that is recognizable and readable to others is definitely a good thing.

Python can't find module in the same folder

Change your import in test.py to:

from .hello import hello1

Should __init__() call the parent class's __init__()?

IMO, you should call it. If your superclass is object, you should not, but in other cases I think it is exceptional not to call it. As already answered by others, it is very convenient if your class doesn't even have to override __init__ itself, for example when it has no (additional) internal state to initialize.

How can I round down a number in Javascript?

Here is math.floor being used in a simple example. This might help a new developer to get an idea how to use it in a function and what it does. Hope it helps!

<script>

var marks = 0;

function getRandomNumbers(){    //  generate a random number between 1 & 10
    var number = Math.floor((Math.random() * 10) + 1);
    return number;
}

function getNew(){  
/*  
    This function can create a new problem by generating two random numbers. When the page is loading as the first time, this function is executed with the onload event and the onclick event of "new" button.
*/
document.getElementById("ans").focus();
var num1 = getRandomNumbers();
var num2 = getRandomNumbers();
document.getElementById("num1").value = num1;
document.getElementById("num2").value = num2;

document.getElementById("ans").value ="";
document.getElementById("resultBox").style.backgroundColor = "maroon"
document.getElementById("resultBox").innerHTML = "***"

}

function checkAns(){
/*
    After entering the answer, the entered answer will be compared with the correct answer. 
        If the answer is correct, the text of the result box should be "Correct" with a green background and 10 marks should be added to the total marks.
        If the answer is incorrect, the text of the result box should be "Incorrect" with a red background and 3 marks should be deducted from the total.
        The updated total marks should be always displayed at the total marks box.
*/

var num1 = eval(document.getElementById("num1").value);
var num2 = eval(document.getElementById("num2").value);
var answer = eval(document.getElementById("ans").value);

if(answer==(num1+num2)){
    marks = marks + 10;
    document.getElementById("resultBox").innerHTML = "Correct";
    document.getElementById("resultBox").style.backgroundColor = "green";
    document.getElementById("totalMarks").innerHTML= "Total marks : " + marks;

}

else{
    marks = marks - 3;
    document.getElementById("resultBox").innerHTML = "Wrong";
    document.getElementById("resultBox").style.backgroundColor = "red";
    document.getElementById("totalMarks").innerHTML = "Total Marks: " + marks ;
}




}

</script>
</head>

<body onLoad="getNew()">
    <div class="container">
        <h1>Let's add numbers</h1>
        <div class="sum">
            <input id="num1" type="text" readonly> + <input id="num2" type="text" readonly>
        </div>
        <h2>Enter the answer below and click 'Check'</h2>
        <div class="answer">
            <input id="ans" type="text" value="">
        </div>
        <input id="btnchk" onClick="checkAns()" type="button" value="Check" >
        <div id="resultBox">***</div>
        <input id="btnnew" onClick="getNew()" type="button" value="New">
        <div id="totalMarks">Total marks : 0</div>  
    </div>
</body>
</html>

What is the best IDE for C Development / Why use Emacs over an IDE?

Netbeans has great C and C++ support. Some people complain that it's bloated and slow, but I've been using it almost exclusively for personal projects and love it. The code assistance feature is one of the best I've seen.

how to call javascript function in html.actionlink in asp.net mvc?

For calling javascript in your action link you simply need to write actionlink like this:

@Html.ActionLink("Delete", "Your-Action", new { id = item.id },
                 new { onclick="return confirm('Are you sure?');"})

Don't get confused between route values and the html attributes.

Table with fixed header and fixed column on pure css

Pure CSS Example:

<div id="cntnr">
    <div class="tableHeader">
        <table class="table-header table table-striped table-bordered">
            <thead>
                <tr>
                    <th>this</th>
                    <th>transmission</th>
                    <th>is</th>
                    <th>coming</th>
                    <th>to</th>
                    <th>you</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>we've got it...</td>
                    <td>alright you are go</td>
                    <td>uh, we see the Earth now</td>
                    <td>we've got it...</td>
                    <td>alright you are go</td>
                    <td>uh, we see the Earth now</td>
                </tr>
            </tbody>
        </table>
    </div>


    <div class="tableBody">
        <table class="table-body table table-striped table-bordered">
            <thead>
                <tr>
                    <th>this</th>
                    <th>transmission</th>
                    <th>is</th>
                    <th>coming</th>
                    <th>to</th>
                    <th>you</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>we've got it...</td>
                    <td>alright you are go</td>
                    <td>uh, we see the Earth now</td>
                    <td>we've got it...</td>
                    <td>alright you are go</td>
                    <td>uh, we see the Earth now</td>
                </tr>
            </tbody>
        </table>
    </div>

</div>

#cntnr {
    width: auto;
    height: 200px;
    border: solid 1px #444;
    overflow: auto;
}

.tableHeader {
    position: fixed;
    height: 40px;
    overflow: hidden;
    margin-right: 18px;
    background: white;
}

.table-header tbody {
    height: 0;
    visibility: hidden;
}

.table-body thead {
    height: 0;
    visibility: hidden;
}

http://jsfiddle.net/cCarlson/L98m854d/

Drawback: The fixed header structure/logic is fairly dependent upon specific dimensions, so abstraction is probably not a viable option.

Parse RSS with jQuery

Use Google AJAX Feed API unless your RSS data is private. It's fast, of course.

https://developers.google.com/feed/

Set database from SINGLE USER mode to MULTI USER

This worked fine for me.

Step 1. Right click on database engine, click on activity monitor and see which process is having connection. Kill that particular user and execute the query Immediately.

Step 2.

USE [master];
GO
ALTER DATABASE [YourDatabaseNameHere] SET MULTI_USER WITH NO_WAIT;
GO  

and refresh the database.

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

How to get javax.comm API?

Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html

Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html

Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm

Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html

In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).

How do I make a C++ macro behave like a function?

If you're willing to adopt the practice of always using curly braces in your if statements,

Your macro would simply be missing the last semicolon:

#define MACRO(X,Y)                       \
cout << "1st arg is:" << (X) << endl;    \
cout << "2nd arg is:" << (Y) << endl;    \
cout << "Sum is:" << ((X)+(Y)) << endl

Example 1: (compiles)

if (x > y) {
    MACRO(x, y);
}
do_something();

Example 2: (compiles)

if (x > y) {
    MACRO(x, y);
} else {
    MACRO(y - x, x - y);
}

Example 3: (doesn't compile)

do_something();
MACRO(x, y)
do_something();

How to find the highest value of a column in a data frame in R?

Here's a dplyr solution:

library(dplyr)

# find max for each column
summarise_each(ozone, funs(max(., na.rm=TRUE)))

# sort by Solar.R, descending
arrange(ozone, desc(Solar.R))

UPDATE: summarise_each() has been deprecated in favour of a more featureful family of functions: mutate_all(), mutate_at(), mutate_if(), summarise_all(), summarise_at(), summarise_if()

Here is how you could do:

# find max for each column
ozone %>%
         summarise_if(is.numeric, funs(max(., na.rm=TRUE)))%>%
         arrange(Ozone)

or

ozone %>%
         summarise_at(vars(1:6), funs(max(., na.rm=TRUE)))%>%
         arrange(Ozone)

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

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

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

in stead of

ModelState.AddRuleViolations(dinner.GetRuleViolations());

How can I run a windows batch file but hide the command window?

Create a shortcut to your bat file by using the right-click and selecting Create shortcut. Right-click on the shortcut you created and click on properties. Click on the Run drop-down box and select Minimized.

How to add new activity to existing project in Android Studio?

In Android Studio, go to app -> src -> main -> java -> com.example.username.projectname

Right click on com.example.username.projectname -> Activity -> ActivityType

Fill in the details of the New Android Activity and click Finish.

Viola! new activity added to the existing project.

Oracle client ORA-12541: TNS:no listener

According to oracle online documentation

ORA-12541: TNS:no listener

Cause: The connection request could not be completed because the listener is not running.

Action: Ensure that the supplied destination address matches one of the addresses used by 
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or  
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on 
the remote machine.

Is there a C++ decompiler?

I haven't seen any decompilers that generate C++ code. I've seen a few experimental ones that make a reasonable attempt at generating C code, but they tended to be dependent on matching the code-generation patterns of a particular compiler (that may have changed, it's been awhile since I last looked into this). Of course any symbolic information will be gone. Google for "decompiler".

How to activate virtualenv?

Here is my workflow after creating a folder and cd'ing into it:

$ virtualenv venv --distribute
New python executable in venv/bin/python
Installing distribute.........done.
Installing pip................done.
$ source venv/bin/activate
(venv)$ python

Onclick CSS button effect

You should apply the following styles:

#button:active {
    vertical-align: top;
    padding: 8px 13px 6px;
}

This will give you the necessary effect, demo here.

How to Set AllowOverride all

On Linux, in order to relax access to the document root, you should edit the following file:

/etc/httpd/conf/httpd.conf

And depending on what directory level you want to relax access to, you have to change the directive

AllowOverride None

to

AllowOverride All

So, assuming you want to allow access to files on the /var/www/html directory, you should change the following lines from:

<Directory "/var/www/html">
 AllowOverride None
</Directory>

to

<Directory "/var/www/html">
 AllowOverride All
</Directory>

ToList().ForEach in Linq

you want this?

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

How to check in Javascript if one element is contained within another

Another solution that wasn't mentioned:

Example Here

var parent = document.querySelector('.parent');

if (parent.querySelector('.child') !== null) {
    // .. it's a child
}

It doesn't matter whether the element is a direct child, it will work at any depth.


Alternatively, using the .contains() method:

Example Here

var parent = document.querySelector('.parent'),
    child = document.querySelector('.child');

if (parent.contains(child)) {
    // .. it's a child
}

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The JAX-WS dependency library “jaxws-rt.jar” is missing.

Go here http://jax-ws.java.net/. Download JAX-WS RI distribution. Unzip it and copy “jaxws-rt.jar” to Tomcat library folder “{$TOMCAT}/lib“. Restart Tomcat.

What is the difference between signed and unsigned int

As you are probably aware, ints are stored internally in binary. Typically an int contains 32 bits, but in some environments might contain 16 or 64 bits (or even a different number, usually but not necessarily a power of two).

But for this example, let's look at 4-bit integers. Tiny, but useful for illustration purposes.

Since there are four bits in such an integer, it can assume one of 16 values; 16 is two to the fourth power, or 2 times 2 times 2 times 2. What are those values? The answer depends on whether this integer is a signed int or an unsigned int. With an unsigned int, the value is never negative; there is no sign associated with the value. Here are the 16 possible values of a four-bit unsigned int:

bits  value
0000    0
0001    1
0010    2
0011    3
0100    4
0101    5
0110    6
0111    7
1000    8
1001    9
1010   10
1011   11
1100   12
1101   13
1110   14
1111   15

... and Here are the 16 possible values of a four-bit signed int:

bits  value
0000    0
0001    1
0010    2
0011    3
0100    4
0101    5
0110    6
0111    7
1000   -8
1001   -7
1010   -6
1011   -5
1100   -4
1101   -3
1110   -2
1111   -1

As you can see, for signed ints the most significant bit is 1 if and only if the number is negative. That is why, for signed ints, this bit is known as the "sign bit".

How to use pull to refresh in Swift?

I suggest to make an Extension of pull To Refresh to use in every class.

1) Make an empty swift file : File - New - File - Swift File.

2) Add the Following

    //  AppExtensions.swift

    import Foundation
    import UIKit    

    var tableRefreshControl:UIRefreshControl = UIRefreshControl()    

    //MARK:- VIEWCONTROLLER EXTENSION METHODS
    public extension UIViewController
    {
        func makePullToRefreshToTableView(tableName: UITableView,triggerToMethodName: String){

            tableRefreshControl.attributedTitle = NSAttributedString(string: "TEST: Pull to refresh")
            tableRefreshControl.backgroundColor = UIColor.whiteColor()
            tableRefreshControl.addTarget(self, action: Selector(triggerToMethodName), forControlEvents: UIControlEvents.ValueChanged)
            tableName.addSubview(tableRefreshControl)
        }
        func makePullToRefreshEndRefreshing (tableName: String)
        {
            tableRefreshControl.endRefreshing()
//additional codes

        }
    }    

3) In Your View Controller call these methods as :

  override func viewWillAppear(animated: Bool) {

self.makePullToRefreshToTableView(bidderListTable, triggerToMethodName: "pullToRefreshBidderTable")
}

4) At some point you wanted to end refreshing:

  func pullToRefreshBidderTable() {
self.makePullToRefreshEndRefreshing("bidderListTable")    
//Code What to do here.
}
OR    
self.makePullToRefreshEndRefreshing("bidderListTable")

Overlay with spinner

use a css3 class "spinner". It's more beautiful and you don't need .gif

enter image description here

.spinner {
   position: absolute;
   left: 50%;
   top: 50%;
   height:60px;
   width:60px;
   margin:0px auto;
   -webkit-animation: rotation .6s infinite linear;
   -moz-animation: rotation .6s infinite linear;
   -o-animation: rotation .6s infinite linear;
   animation: rotation .6s infinite linear;
   border-left:6px solid rgba(0,174,239,.15);
   border-right:6px solid rgba(0,174,239,.15);
   border-bottom:6px solid rgba(0,174,239,.15);
   border-top:6px solid rgba(0,174,239,.8);
   border-radius:100%;
}

@-webkit-keyframes rotation {
   from {-webkit-transform: rotate(0deg);}
   to {-webkit-transform: rotate(359deg);}
}
@-moz-keyframes rotation {
   from {-moz-transform: rotate(0deg);}
   to {-moz-transform: rotate(359deg);}
}
@-o-keyframes rotation {
   from {-o-transform: rotate(0deg);}
   to {-o-transform: rotate(359deg);}
}
@keyframes rotation {
   from {transform: rotate(0deg);}
   to {transform: rotate(359deg);}
}

Exemple of what is looks like : http://jsbin.com/roqakuxebo/1/edit

You can find a lot of css spinners like this here : http://cssload.net/en/spinners/

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Passing an array as an argument to a function in C

You are passing the value of the memory location of the first member of the array.

Therefore when you start modifying the array inside the function, you are modifying the original array.

Remember that a[1] is *(a+1).

VirtualBox Cannot register the hard disk already exists

In some cases first your need to Release, then Remove and Re-add via Virtual Media Manager

I need to convert an int variable to double

You have to cast one (or both) of the arguments to the division operator to double:

double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);

Since you are performing the same calculation twice I'd recommend refactoring your code:

double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;

This works in the same way, but now there is an implicit cast to double. This conversion from int to double is an example of a widening primitive conversion.

How do I remove a submodule?

To summarize, this is what you should do :

Set path_to_submodule var (no trailing slash):

path_to_submodule=path/to/submodule

Delete the relevant line from the .gitmodules file:

git config -f .gitmodules --remove-section submodule.$path_to_submodule

Delete the relevant section from .git/config

git config -f .git/config --remove-section submodule.$path_to_submodule

Unstage and remove $path_to_submodule only from the index (to prevent losing information)

git rm --cached $path_to_submodule

Track changes made to .gitmodules

git add .gitmodules

Commit the superproject

git commit -m "Remove submodule submodule_name"

Delete the now untracked submodule files

rm -rf $path_to_submodule

rm -rf .git/modules/$path_to_submodule

See also : Alternative guide lines