Programs & Examples On #Key management

'Conda' is not recognized as internal or external command

I have just launched anaconda-navigator and run the conda commands from there.

How to POST request using RestSharp

This way works fine for me:

var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
                .AddBody(BODY);

var response = Client.Execute(request);

// Handle response errors
HandleResponseErrors(response);

if (Errors.Length == 0)
{ }
else
{ }

Hope this helps! (Although it is a bit late)

How do I show the changes which have been staged?

For Staging Area vs Repository(last commit) comparison use

 $git diff --staged

The command compares your staged($ git add fileName) changes to your last commit. If you want to see what you’ve staged that will go into your next commit, you can use git diff --staged. This command compares your staged changes to your last commit.

For Working vs Staging comparison use

$ git diff 

The command compares what is in your working directory with what is in your staging area. It’s important to note that git diff by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. If you’ve staged all of your changes($ git add fileName), git diff will give you no output.

Also, if you stage a file($ git add fileName) and then edit it, you can use git diff to see the changes in the file that are staged and the changes that are unstaged.

Scale an equation to fit exact page width

\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

or

\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

Working with huge files in VIM

emacs works very well with files into the 100's of megabytes, I've used it on log files without too much trouble.

But generally when I have some kind of analysis task, I find writing a perl script a better choice.

Android Recyclerview GridLayoutManager column spacing

There is only one easy solution, that you can remember and implement wherever needed. No bugs, no crazy calculations. Put margin to the card / item layout and put the same size as padding to the RecyclerView:

item_layout.xml

<CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:margin="10dp">

activity_layout.xml

<RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"/>

UPDATE: enter image description here

In MVC, how do I return a string result?

public JsonResult GetAjaxValue() 
{
  return Json("string value", JsonRequetBehaviour.Allowget); 
}

Error: [ng:areq] from angular controller

I experienced this error once. The problem was I had defined angular.module() in two places with different arguments.

Eg:

var MyApp = angular.module('MyApp', []);

in other place,

var MyApp2 = angular.module('MyApp', ['ngAnimate']);

Split string into array of characters?

the problem is that there is no built in method (or at least none of us could find one) to do this in vb. However, there is one to split a string on the spaces, so I just rebuild the string and added in spaces....

Private Function characterArray(ByVal my_string As String) As String()
  'create a temporary string to store a new string of the same characters with spaces
  Dim tempString As String = ""
  'cycle through the characters and rebuild my_string as a string with spaces 
  'and assign the result to tempString.  
  For Each c In my_string
     tempString &= c & " "
  Next
  'return return tempString as a character array.  
  Return tempString.Split()
End Function

Selecting empty text input using jQuery

This will select empty text inputs with an id that starts with "txt":

$(':text[value=""][id^=txt]')

Are string.Equals() and == operator really same?

An object is defined by an OBJECT_ID, which is unique. If A and B are objects and A == B is true, then they are the very same object, they have the same data and methods, but, this is also true:

A.OBJECT_ID == B.OBJECT_ID

if A.Equals(B) is true, that means that the two objects are in the same state, but this doesn't mean that A is the very same as B.

Strings are objects.

Note that the == and Equals operators are reflexive, simetric, tranzitive, so they are equivalentic relations (to use relational algebraic terms)

What this means: If A, B and C are objects, then:

(1) A == A is always true; A.Equals(A) is always true (reflexivity)

(2) if A == B then B == A; If A.Equals(B) then B.Equals(A) (simetry)

(3) if A == B and B == C, then A == C; if A.Equals(B) and B.Equals(C) then A.Equals(C) (tranzitivity)

Also, you can note that this is also true:

(A == B) => (A.Equals(B)), but the inverse is not true.

A B =>
0 0 1
0 1 1
1 0 0
1 1 1

Example of real life: Two Hamburgers of the same type have the same properties: they are objects of the Hamburger class, their properties are exactly the same, but they are different entities. If you buy these two Hamburgers and eat one, the other one won't be eaten. So, the difference between Equals and ==: You have hamburger1 and hamburger2. They are exactly in the same state (the same weight, the same temperature, the same taste), so hamburger1.Equals(hamburger2) is true. But hamburger1 == hamburger2 is false, because if the state of hamburger1 changes, the state of hamburger2 not necessarily change and vice versa.

If you and a friend get a Hamburger, which is yours and his in the same time, then you must decide to split the Hamburger into two parts, because you.getHamburger() == friend.getHamburger() is true and if this happens: friend.eatHamburger(), then your Hamburger will be eaten too.

I could write other nuances about Equals and ==, but I'm getting hungry, so I have to go.

Best regards, Lajos Arpad.

How to randomize (shuffle) a JavaScript array?

With ES2015 you can use this one:

Array.prototype.shuffle = function() {
  let m = this.length, i;
  while (m) {
    i = (Math.random() * m--) >>> 0;
    [this[m], this[i]] = [this[i], this[m]]
  }
  return this;
}

Usage:

[1, 2, 3, 4, 5, 6, 7].shuffle();

How can I trigger a JavaScript event click

UPDATE

This was an old answer. Nowadays you should just use click. For more advanced event firing, use dispatchEvent.

_x000D_
_x000D_
const body = document.body;_x000D_
_x000D_
body.addEventListener('click', e => {_x000D_
  console.log('clicked body');_x000D_
});_x000D_
_x000D_
console.log('Using click()');_x000D_
body.click();_x000D_
_x000D_
console.log('Using dispatchEvent');_x000D_
body.dispatchEvent(new Event('click'));
_x000D_
_x000D_
_x000D_

Original Answer

Here is what I use: http://jsfiddle.net/mendesjuan/rHMCy/4/

Updated to work with IE9+

/**
 * Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
 * by testing for a 'synthetic=true' property on the event object
 * @param {HTMLNode} node The node to fire the event handler on.
 * @param {String} eventName The name of the event without the "on" (e.g., "focus")
 */
function fireEvent(node, eventName) {
    // Make sure we use the ownerDocument from the provided node to avoid cross-window problems
    var doc;
    if (node.ownerDocument) {
        doc = node.ownerDocument;
    } else if (node.nodeType == 9){
        // the node may be the document itself, nodeType 9 = DOCUMENT_NODE
        doc = node;
    } else {
        throw new Error("Invalid node passed to fireEvent: " + node.id);
    }

     if (node.dispatchEvent) {
        // Gecko-style approach (now the standard) takes more work
        var eventClass = "";

        // Different events have different event classes.
        // If this switch statement can't map an eventName to an eventClass,
        // the event firing is going to fail.
        switch (eventName) {
            case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
            case "mousedown":
            case "mouseup":
                eventClass = "MouseEvents";
                break;

            case "focus":
            case "change":
            case "blur":
            case "select":
                eventClass = "HTMLEvents";
                break;

            default:
                throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
                break;
        }
        var event = doc.createEvent(eventClass);
        event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.

        event.synthetic = true; // allow detection of synthetic events
        // The second parameter says go ahead with the default action
        node.dispatchEvent(event, true);
    } else  if (node.fireEvent) {
        // IE-old school style, you can drop this if you don't need to support IE8 and lower
        var event = doc.createEventObject();
        event.synthetic = true; // allow detection of synthetic events
        node.fireEvent("on" + eventName, event);
    }
};

Note that calling fireEvent(inputField, 'change'); does not mean it will actually change the input field. The typical use case for firing a change event is when you set a field programmatically and you want event handlers to be called since calling input.value="Something" won't trigger a change event.

How to close an iframe within iframe itself

its kind of hacky but it works well-ish

 function close_frame(){
    if(!window.should_close){
        window.should_close=1;
    }else if(window.should_close==1){
        location.reload();
        //or iframe hide or whatever
    }
 }

 <iframe src="iframe_index.php" onload="close_frame()"></iframe>

then inside the frame

$('#close_modal_main').click(function(){
        window.location = 'iframe_index.php?close=1';
});

and if you want to get fancy through a

if(isset($_GET['close'])){
  die;
}

at the top of your frame page to make that reload unnoticeable

so basically the first time the frame loads it doesnt hide itself but the next time it loads itll call the onload function and the parent will have a the window var causing the frame to close

Redirect on select option in select box

    {{-- dynamic select/dropdown --}}
    <select class="form-control m-bot15" name="district_id" 
        onchange ="location = this.options[this.selectedIndex].value;"
        >
          <option value="">--Select--</option>
          <option value="?">All</option>

            @foreach($location as $district)
                <option  value="?district_id={{ $district->district_id }}" >
                  {{ $district->district }}
                </option> 
            @endforeach   

    </select>

Can't access Tomcat using IP address

New versions of application servers removed the ability of binding to your entire network interface and limited it just to the local interface (localhost). The reason being was for security. From what I know, Tomcat and JBoss implement the same security measures.

If you want to bind it to another IP you can explicitly set it in your connector string:

  • Tomcat: address="192.168.1.100"
  • JBoss: you pass in a -b 192.168.1.100 as a command line.

Just remember that binding 0.0.0.0 allows anyone access to your box to access that server. It will bind to all addresses. If that is what you want, then use 0.0.0.0, if it isn't then specify the address you would like to explicitly bind instead.

Just make sure you understand the consequences binding to all addresses (0.0.0.0)

Namenode not getting started

If you facing this issue after rebooting the system, Then below steps will work fine

For workaround.

1) format the namenode: bin/hadoop namenode -format

2) start all processes again:bin/start-all.sh

For Perm fix: -

1) go to /conf/core-site.xml change fs.default.name to your custom one.

2) format the namenode: bin/hadoop namenode -format

3) start all processes again:bin/start-all.sh

Can I set an unlimited length for maxJsonLength in web.config?

For those who are having issues with in MVC3 with JSON that's automatically being deserialized for a model binder and is too large, here is a solution.

  1. Copy the code for the JsonValueProviderFactory class from the MVC3 source code into a new class.
  2. Add a line to change the maximum JSON length before the object is deserialized.
  3. Replace the JsonValueProviderFactory class with your new, modified class.

Thanks to http://blog.naver.com/techshare/100145191355 and https://gist.github.com/DalSoft/1588818 for pointing me in the right direction for how to do this. The last link on the first site contains full source code for the solution.

How do I change the hover over color for a hover over table in Bootstrap?

This worked for me:

.table tbody tr:hover td, .table tbody tr:hover th {
    background-color: #eeeeea;
}

The name 'controlname' does not exist in the current context

Solution option #2 offered above works for windows forms applications and not web aspx application. I got similar error in web application, I resolved this by deleting a file where I had a user control by the same name, this aspx file was actually a backup file and was not referenced anywhere in the process, but still it caused the error because the name of user control registered on the backup file was named exactly same on the aspx file which was referenced in process flow. So I deleted the backup file and built solution, build succeeded.

Hope this helps some one in similar scenario.

Vijaya Laxmi.

Max retries exceeded with URL in requests

What happened here is that itunes server refuses your connection (you're sending too many requests from same ip address in short period of time)

Max retries exceeded with url: /in/app/adobe-reader/id469337564?mt=8

error trace is misleading it should be something like "No connection could be made because the target machine actively refused it".

There is an issue at about python.requests lib at Github, check it out here

To overcome this issue (not so much an issue as it is misleading debug trace) you should catch connection related exceptions like so:

try:
    page1 = requests.get(ap)
except requests.exceptions.ConnectionError:
    r.status_code = "Connection refused"

Another way to overcome this problem is if you use enough time gap to send requests to server this can be achieved by sleep(timeinsec) function in python (don't forget to import sleep)

from time import sleep

All in all requests is awesome python lib, hope that solves your problem.

Declare multiple module.exports in Node.js

module.js:

const foo = function(<params>) { ... }
const bar = function(<params>) { ... } 

//export modules
module.exports = {
    foo,
    bar 
}

main.js:

// import modules
var { foo, bar } = require('module');

// pass your parameters
var f1 = foo(<params>);
var f2 = bar(<params>);

Cannot call getSupportFragmentManager() from activity

Your activity doesn't extend FragmentActivity from the support library, therefore the method is not present in the superclass

If you are targeting api 11 or above, you could use Activity.getFragmentManager instead.

Android Debug Bridge (adb) device - no permissions

Had the same issue. It was a problem with udev rules. Tried a few of the rules mentioned above but didnot fix the issue. Found a set of rules here, https://github.com/M0Rf30/android-udev-rules. Followed the guide there and, voila, fixed.

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

How to list all the available keyspaces in Cassandra?

desc keyspaces will do it for you.

Change the Value of h1 Element within a Form with JavaScript

You can use this: document.getElementById('h1_id').innerHTML = 'the new text';

How can I remove or replace SVG content?

If you want to get rid of all children,

svg.selectAll("*").remove();

will remove all content associated with the svg.

Using success/error/finally/catch with Promises in AngularJS

Promises are an abstraction over statements that allow us to express ourselves synchronously with asynchronous code. They represent a execution of a one time task.

They also provide exception handling, just like normal code, you can return from a promise or you can throw.

What you'd want in synchronous code is:

try{
  try{
      var res = $http.getSync("url");
      res = someProcessingOf(res);
  } catch (e) {
      console.log("Got an error!",e);
      throw e; // rethrow to not marked as handled
  }
  // do more stuff with res
} catch (e){
     // handle errors in processing or in error.
}

The promisified version is very similar:

$http.get("url").
then(someProcessingOf).
catch(function(e){
   console.log("got an error in initial processing",e);
   throw e; // rethrow to not marked as handled, 
            // in $q it's better to `return $q.reject(e)` here
}).then(function(res){
    // do more stuff
}).catch(function(e){
    // handle errors in processing or in error.
});

Is it possible to decompile a compiled .pyc file into a .py file?

Yes, you can get it with unpyclib that can be found on pypi.

$ pip install unpyclib

Than you can decompile your .pyc file

$ python -m unpyclib.application -Dq path/to/file.pyc

How to determine a user's IP address in node

_x000D_
_x000D_
function getCallerIP(request) {_x000D_
    var ip = request.headers['x-forwarded-for'] ||_x000D_
        request.connection.remoteAddress ||_x000D_
        request.socket.remoteAddress ||_x000D_
        request.connection.socket.remoteAddress;_x000D_
    ip = ip.split(',')[0];_x000D_
    ip = ip.split(':').slice(-1); //in case the ip returned in a format: "::ffff:146.xxx.xxx.xxx"_x000D_
    return ip;_x000D_
}
_x000D_
_x000D_
_x000D_

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

Ctrl + . shows the menu. I find this easier to type than the alternative, Alt + Shift + F10.

This can be re-bound to something more familiar by going to Tools > Options > Environment > Keyboard > Visual C# > View.QuickActions

Winforms TableLayoutPanel adding rows programmatically

Create a table layout panel with two columns in your form and name it tlpFields.

Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).

tlpFields.RowStyles.Clear();  //first you must clear rowStyles

for (int ii = 0; ii < 5; ii++)
{
    Label l1= new Label();
    TextBox t1 = new TextBox();

    l1.Text = "field : ";

    tlpFields.Controls.Add(l1, 0, ii);  // add label in column0
    tlpFields.Controls.Add(t1, 1, ii);  // add textbox in column1

    tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}

Finally, run the code.

How to get the selected date value while using Bootstrap Datepicker?

If you wan't the date in full text string format you can do it like this:

$('#your-datepicker').data().datepicker.viewDate

How can I time a code segment for testing performance with Pythons timeit?

I see the question has already been answered, but still want to add my 2 cents for the same.

I have also faced similar scenario in which I have to test the execution times for several approaches and hence written a small script, which calls timeit on all functions written in it.

The script is also available as github gist here.

Hope it will help you and others.

from random import random
import types

def list_without_comprehension():
    l = []
    for i in xrange(1000):
        l.append(int(random()*100 % 100))
    return l

def list_with_comprehension():
    # 1K random numbers between 0 to 100
    l = [int(random()*100 % 100) for _ in xrange(1000)]
    return l


# operations on list_without_comprehension
def sort_list_without_comprehension():
    list_without_comprehension().sort()

def reverse_sort_list_without_comprehension():
    list_without_comprehension().sort(reverse=True)

def sorted_list_without_comprehension():
    sorted(list_without_comprehension())


# operations on list_with_comprehension
def sort_list_with_comprehension():
    list_with_comprehension().sort()

def reverse_sort_list_with_comprehension():
    list_with_comprehension().sort(reverse=True)

def sorted_list_with_comprehension():
    sorted(list_with_comprehension())


def main():
    objs = globals()
    funcs = []
    f = open("timeit_demo.sh", "w+")

    for objname in objs:
        if objname != 'main' and type(objs[objname]) == types.FunctionType:
            funcs.append(objname)
    funcs.sort()
    for func in funcs:
        f.write('''echo "Timing: %(funcname)s"
python -m timeit "import timeit_demo; timeit_demo.%(funcname)s();"\n\n
echo "------------------------------------------------------------"
''' % dict(
                funcname = func,
                )
            )

    f.close()

if __name__ == "__main__":
    main()

    from os import system

    #Works only for *nix platforms
    system("/bin/bash timeit_demo.sh")

    #un-comment below for windows
    #system("cmd timeit_demo.sh")

Add URL link in CSS Background Image?

You can not add links from CSS, you will have to do so from the HTML code explicitly. For example, something like this:

<a href="whatever.html"><li id="header"></li></a>

Substring with reverse index

var str = "xxx_456";
var str_sub = str.substr(str.lastIndexOf("_")+1);

If it is not always three digits at the end (and seperated by an underscore). If the end delimiter is not always an underscore, then you could use regex:

var pat = /([0-9]{1,})$/;
var m = str.match(pat);

Send cookies with curl

.example.com TRUE / FALSE 1560211200 MY_VARIABLE MY_VALUE

The cookies file format apparently consists of a line per cookie and each line consists of the following seven tab-delimited fields:

  • domain - The domain that created AND that can read the variable.
  • flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.
  • path - The path within the domain that the variable is valid for.
  • secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
  • expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.
  • name - The name of the variable.
  • value - The value of the variable.

From http://www.cookiecentral.com/faq/#3.5

Got a NumberFormatException while trying to parse a text file for objects

I changed Scanner fin = new Scanner(file); to Scanner fin = new Scanner(new File(file)); and it works perfectly now. I didn't think the difference mattered but there you go.

Iterating over all the keys of a map

Is there a way to get a list of all the keys in a Go language map?

ks := reflect.ValueOf(m).MapKeys()

how do I iterate over all the keys?

Use the accepted answer:

for k, _ := range m { ... }

How to convert a byte to its binary string representation

Use Integer#toBinaryString():

byte b1 = (byte) 129;
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
System.out.println(s1); // 10000001

byte b2 = (byte) 2;
String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
System.out.println(s2); // 00000010

DEMO.

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

You could compile and link in one command:

gcc file1.c file2.c -o myprogram

And run with:

./myprogram

But to answer the question as asked, simply pass the object files to gcc:

gcc file1.o file2.o -o myprogram

How do I add Git version control (Bitbucket) to an existing source code folder?

User johannes told you how to do add existing files to a Git repository in a general situation. Because you talk about Bitbucket, I suggest you do the following:

  1. Create a new repository on Bitbucket (you can see a Create button on the top of your profile page) and you will go to this page:

    Create repository on Bitbucket

  2. Fill in the form, click next and then you automatically go to this page:

    Create repository from scratch or add existing files

  3. Choose to add existing files and you go to this page:

    Enter image description here

  4. You use those commands and you upload the existing files to Bitbucket. After that, the files are online.

Exception thrown inside catch block - will it be caught again?

No, since the catches all refer to the same try block, so throwing from within a catch block would be caught by an enclosing try block (probably in the method that called this one)

Java creating .jar file

Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.

jQuery check if <input> exists and has a value

Just for the heck of it, I tracked this down in the jQuery code. The .val() function currently starts at line 165 of attributes.js. Here's the relevant section, with my annotations:

val: function( value ) {
    var hooks, ret, isFunction,
        elem = this[0];

        /// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
    if ( !arguments.length ) {

        /// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
        if ( elem ) {
            hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

            if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                return ret;
            }

            ret = elem.value;

            /// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
            return typeof ret === "string" ?
                // handle most common string cases
                ret.replace(rreturn, "") :
                // handle cases where value is null/undef or number
                ret == null ? "" : ret;
        }

        return;
    }

So, you'll either get undefined or "" or null -- all of which evaluate as false in if statements.

Move view with keyboard using Swift

Easiest way that doesn't even require any code:

  1. Download KeyboardLayoutConstraint.swift and add (drag & drop) the file into your project, if you're not using the Spring animation framework already.
  2. In your storyboard, create a bottom constraint for the View or Textfield, select the constraint (double-click it) and in the Identity Inspector, change its class from NSLayoutConstraint to KeyboardLayoutConstraint.
  3. Done!

The object will auto-move up with the keyboard, in sync.

Downloading a picture via urllib and python

Using requests

import requests
import shutil,os

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
currentDir = os.getcwd()
path = os.path.join(currentDir,'Images')#saving images to Images folder

def ImageDl(url):
    attempts = 0
    while attempts < 5:#retry 5 times
        try:
            filename = url.split('/')[-1]
            r = requests.get(url,headers=headers,stream=True,timeout=5)
            if r.status_code == 200:
                with open(os.path.join(path,filename),'wb') as f:
                    r.raw.decode_content = True
                    shutil.copyfileobj(r.raw,f)
            print(filename)
            break
        except Exception as e:
            attempts+=1
            print(e)

if __name__ == '__main__':
    ImageDl(url)

Angular update object in object array

You can try this also to replace existing object

toDoTaskList = [
                {id:'abcd', name:'test'},
                {id:'abcdc', name:'test'},
                {id:'abcdtr', name:'test'}
              ];

newRecordToUpdate = {id:'abcdc', name:'xyz'};
this.toDoTaskList.map((todo, i) => {
         if (todo.id == newRecordToUpdate .id){
            this.toDoTaskList[i] = updatedVal;
          }
        });

How to add a ListView to a Column in Flutter?

Here is a very simple method. There are a different ways to do it, like you can get it by Expanded, Sizedbox or Container and it should be used according to needs.

  1. Use Expanded : A widget that expands a child of a Row, Column, or Flex so that the child fills the available space.

    Expanded(
        child: ListView(scrollDirection: Axis.horizontal,
            children: <Widget>[
              OutlineButton(onPressed: null,
                  child: Text("Facebook")),
              Padding(padding: EdgeInsets.all(5.00)),
              OutlineButton(onPressed: null,
                  child: Text("Google")),
              Padding(padding: EdgeInsets.all(5.00)),
              OutlineButton(onPressed: null,
                  child: Text("Twitter"))
            ]),
      ),
    

Using an Expanded widget makes a child of a Row, Column, or Flex expand to fill the available space along the main axis (e.g., horizontally for a Row or vertically for a Column).

  1. Use SizedBox : A box with a specified size.

    SizedBox(
        height: 100,
        child: ListView(scrollDirection: Axis.horizontal,
            children: <Widget>[
              OutlineButton(
                  color: Colors.white,
                  onPressed: null,
                  child: Text("Amazon")
              ),
              Padding(padding: EdgeInsets.all(5.00)),
              OutlineButton(onPressed: null,
                  child: Text("Instagram")),
              Padding(padding: EdgeInsets.all(5.00)),
              OutlineButton(onPressed: null,
                  child: Text("SoundCloud"))
            ]),
     ),
    

If given a child, this widget forces its child to have a specific width and/or height (assuming values are permitted by this widget's parent).

  1. Use Container : A convenience widget that combines common painting, positioning, and sizing widgets.

     Container(
        height: 80.0,
        child: ListView(scrollDirection: Axis.horizontal,
            children: <Widget>[
              OutlineButton(onPressed: null,
                  child: Text("Shopify")),
              Padding(padding: EdgeInsets.all(5.00)),
              OutlineButton(onPressed: null,
                  child: Text("Yahoo")),
              Padding(padding: EdgeInsets.all(5.00)),
              OutlineButton(onPressed: null,
                  child: Text("LinkedIn"))
            ]),
      ),
    

The output to all three would be something like this

enter image description here

How do I add PHP code/file to HTML(.html) files?

By default you can't use PHP in HTML pages.

To do that, modify your .htacccess file with the following:

AddType application/x-httpd-php .html

Create an array with same element repeated multiple times

I discovered this today while trying to make a 2D array without using loops. In retrospect, joining a new array is neat; I tried mapping a new array, which doesn't work as map skips empty slots.

"#".repeat(5).split('').map(x => 0)

The "#" char can be any valid single character. The 5 would be a variable for the number of elements you want. The 7 would be the value you want to fill your array with.

The new fill method is better, and when I coded this I didn't know it existed, nor did I know repeat is es6; I'm going to write a blog post about using this trick in tandem with reduce to do cool things.

http://jburger.us.to/2016/07/14/functionally-create-a-2d-array/

How to pick a new color for each plotted line within a figure in matplotlib?

prop_cycle

color_cycle was deprecated in 1.5 in favor of this generalization: http://matplotlib.org/users/whats_new.html#added-axes-prop-cycle-key-to-rcparams

# cycler is a separate package extracted from matplotlib.
from cycler import cycler
import matplotlib.pyplot as plt

plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b'])))
plt.plot([1, 2])
plt.plot([2, 3])
plt.plot([3, 4])
plt.plot([4, 5])
plt.plot([5, 6])
plt.show()

Also shown in the (now badly named) example: http://matplotlib.org/1.5.1/examples/color/color_cycle_demo.html mentioned at: https://stackoverflow.com/a/4971431/895245

Tested in matplotlib 1.5.1.

Remove leading or trailing spaces in an entire column of data

If you would like to use a formula, the TRIM function will do exactly what you're looking for:

+----+------------+---------------------+
|    |     A      |           B         |
+----+------------+---------------------+
| 1  | =TRIM(B1)  |  value to trim here |
+----+------------+---------------------+

So to do the whole column...
1) Insert a column
2) Insert TRIM function pointed at cell you are trying to correct.
3) Copy formula down the page
4) Copy inserted column
5) Paste as "Values"

Should be good to go from there...

How to detect IE11?

var ua = navigator.userAgent.toString().toLowerCase();
var match = /(trident)(?:.*rv:([\w.]+))?/.exec(ua) ||/(msie) ([\w.]+)/.exec(ua)||['',null,-1];
var rv = match[2];
return rv;

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

How to delete a folder with files using Java

Using Apache Commons-IO, it is following one-liner:

import org.apache.commons.io.FileUtils;

FileUtils.forceDelete(new File(destination));

This is (slightly) more performant than FileUtils.deleteDirectory.

JavaScript replace \n with <br />

You need the /g for global matching

replace(/\n/g, "<br />");

This works for me for \n - see this answer if you might have \r\n

NOTE: The dupe is the most complete answer for any combination of \r\n, \r or \n

_x000D_
_x000D_
var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");_x000D_
console.log(messagetoSend);
_x000D_
<textarea id="x" rows="9">_x000D_
    Line 1_x000D_
    _x000D_
    _x000D_
    Line 2_x000D_
    _x000D_
    _x000D_
    _x000D_
    _x000D_
    Line 3_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

UPDATE

It seems some visitors of this question have text with the breaklines escaped as

some text\r\nover more than one line"

In that case you need to escape the slashes:

replace(/\\r\\n/g, "<br />");

NOTE: All browsers will ignore \r in a string when rendering.

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

  • It did not work so i switched to oracle sql developer and it worked with no problems (making connection under 1 minute).
  • This link gave me an idea connect to MS Access so i created a user in oracle sql developer and the tried to connect to it in Toad and it worked.

Or second solution

you can try to connect using Direct not TNS by providing host and port in the connect screen of Toad

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

You need to specify the std:: namespace:

std::cout << .... << std::endl;;

Alternatively, you can use a using directive:

using std::cout;
using std::endl;

cout << .... << endl;

I should add that you should avoid these using directives in headers, since code including these will also have the symbols brought into the global namespace. Restrict using directives to small scopes, for example

#include <iostream>

inline void foo()
{
  using std::cout;
  using std::endl;
  cout << "Hello world" << endl;
}

Here, the using directive only applies to the scope of foo().

The ScriptManager must appear before any controls that need it

The ScriptManager is a control that needs to be added to the page you have created.

Take a look at this Sample AJAX Application.

<body>
    <form runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        ...
    </form>
</body>

Serializing class instance to JSON

Using jsonpickle

import jsonpickle

object = YourClass()
json_object = jsonpickle.encode(object)

How can I generate a list of consecutive numbers?

You can use itertools.count() to generate unbounded sequences. (itertools is in the Python standard library). Docs here:
https://docs.python.org/3/library/itertools.html#itertools.count

Given the lat/long coordinates, how can we find out the city/country?

Please check the below answer. It works for me

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position){

        initialize(position.coords.latitude,position.coords.longitude);
    }); 
}

function initialize(lat,lng) {
    //directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    //directionsService = new google.maps.DirectionsService();
    var latlng = new google.maps.LatLng(lat, lng);

    //alert(latlng);
    getLocation(latlng);
}

function getLocation(latlng){

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': latlng}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var loc = getCountry(results);
                    alert("location is::"+loc);
                }
            }
        });

}

function getCountry(results)
{
    for (var i = 0; i < results[0].address_components.length; i++)
    {
        var shortname = results[0].address_components[i].short_name;
        var longname = results[0].address_components[i].long_name;
        var type = results[0].address_components[i].types;
        if (type.indexOf("country") != -1)
        {
            if (!isNullOrWhitespace(shortname))
            {
                return shortname;
            }
            else
            {
                return longname;
            }
        }
    }

}

function isNullOrWhitespace(text) {
    if (text == null) {
        return true;
    }
    return text.replace(/\s/gi, '').length < 1;
}

Why are Python lambdas useful?

I find lambda useful for a list of functions that do the same, but for different circumstances.

Like the Mozilla plural rules:

plural_rules = [
    lambda n: 'all',
    lambda n: 'singular' if n == 1 else 'plural',
    lambda n: 'singular' if 0 <= n <= 1 else 'plural',
    ...
]
# Call plural rule #1 with argument 4 to find out which sentence form to use.
plural_rule[1](4) # returns 'plural'

If you'd have to define a function for all of those you'd go mad by the end of it.
Also, it wouldn't be nice with function names like plural_rule_1, plural_rule_2, etc. And you'd need to eval() it when you're depending on a variable function id.

Is it possible to install another version of Python to Virtualenv?

No, but you can install an isolated Python build (such as ActivePython) under your $HOME directory.

This approach is the fastest, and doesn't require you to compile Python yourself.

(as a bonus, you also get to use ActiveState's binary package manager)

splitting a string into an array in C++ without using vector

#include <iostream>
#include <sstream>
#include <iterator>
#include <string>

using namespace std;

template <size_t N>
void splitString(string (&arr)[N], string str)
{
    int n = 0;
    istringstream iss(str);
    for (auto it = istream_iterator<string>(iss); it != istream_iterator<string>() && n < N; ++it, ++n)
        arr[n] = *it;
}

int main()
{
    string line = "test one two three.";
    string arr[4];

    splitString(arr, line);

    for (int i = 0; i < 4; i++)
       cout << arr[i] << endl;
}

PHP Pass by reference in foreach

Because on the second loop, $v is still a reference to the last array item, so it's overwritten each time.

You can see it like that:

$a = array ('zero','one','two', 'three');

foreach ($a as &$v) {

}

foreach ($a as $v) {
  echo $v.'-'.$a[3].PHP_EOL;
}

As you can see, the last array item takes the current loop value: 'zero', 'one', 'two', and then it's just 'two'... : )

Change Active Menu Item on Page Scroll?

Just to complement @Marcus Ekwall 's answer. Doing like this will get only anchor links. And you aren't going to have problems if you have a mix of anchor links and regular ones.

jQuery(document).ready(function(jQuery) {            
            var topMenu = jQuery("#top-menu"),
                offset = 40,
                topMenuHeight = topMenu.outerHeight()+offset,
                // All list items
                menuItems =  topMenu.find('a[href*="#"]'),
                // Anchors corresponding to menu items
                scrollItems = menuItems.map(function(){
                  var href = jQuery(this).attr("href"),
                  id = href.substring(href.indexOf('#')),
                  item = jQuery(id);
                  //console.log(item)
                  if (item.length) { return item; }
                });

            // so we can get a fancy scroll animation
            menuItems.click(function(e){
              var href = jQuery(this).attr("href"),
                id = href.substring(href.indexOf('#'));
                  offsetTop = href === "#" ? 0 : jQuery(id).offset().top-topMenuHeight+1;
              jQuery('html, body').stop().animate({ 
                  scrollTop: offsetTop
              }, 300);
              e.preventDefault();
            });

            // Bind to scroll
            jQuery(window).scroll(function(){
               // Get container scroll position
               var fromTop = jQuery(this).scrollTop()+topMenuHeight;

               // Get id of current scroll item
               var cur = scrollItems.map(function(){
                 if (jQuery(this).offset().top < fromTop)
                   return this;
               });

               // Get the id of the current element
               cur = cur[cur.length-1];
               var id = cur && cur.length ? cur[0].id : "";               

               menuItems.parent().removeClass("active");
               if(id){
                    menuItems.parent().end().filter("[href*='#"+id+"']").parent().addClass("active");
               }

            })
        })

Basically i replaced

menuItems = topMenu.find("a"),

by

menuItems =  topMenu.find('a[href*="#"]'),

To match all links with anchor somewhere, and changed all that what was necessary to make it work with this

See it in action on jsfiddle

Best way to specify whitespace in a String.Split operation

If repeating the same code is the issue, write an extension method on the String class that encapsulates the splitting logic.

PSEXEC, access denied errors

I just added "-?" parameter. It makes Psexec copy executable to remote machine. So it works without access errors.

Get the selected value in a dropdown using jQuery.

The above solutions didn't work for me. Here is what I finally came up with:

$( "#ddl" ).find( "option:selected" ).text();           // Text
$( "#ddl" ).find( "option:selected" ).prop("value");    // Value

Using Postman to access OAuth 2.0 Google APIs

The current answer is outdated. Here's the up-to-date flow:

The approach outlined here still works (10.12.2020) as confirmed by alexwhan.

We will use the YouTube Data API for our example. Make changes accordingly.

Make sure you have enabled your desired API for your project.

Create the OAuth 2.0 Client

  1. Visit https://console.cloud.google.com/apis/credentials
  2. Click on CREATE CREDENTIALS
  3. Select OAuth client ID
  4. For Application Type choose Web Application
  5. Add a name
  6. Add following URI for Authorized redirect URIs
https://oauth.pstmn.io/v1/callback
  1. Click Save
  2. Click on the OAuth client you just generated
  3. In the Topbar click on DOWNLOAD JSON and save the file somewhere on your machine.

We will use the file later to authenticate Postman.

Authorize Postman via OAuth 2.0 Client

  1. In the Auth tab under TYPE choose OAuth 2.0
  2. For Access Token enter the Access Token found inside the client_secret_[YourClientID].json file we downloaded in step 9
  3. Click on Get New Access Token
  4. Make sure your settings are as follows:

Click here to see the settings

You can find everything else you need in your .json file.

  1. Click on Request Token
  2. A new browser tab/window will open
  3. Once the browser tab opens, login via the appropriate Google account
  4. Accept the consent screen
  5. Done

Ignore the browser message "Not safe" etc. This will be shown until your app has been screened by Google officials. In this case it will always be shown since Postman is the app.

Javascript how to split newline

Just

var ks = $('#keywords').val().split(/\r\n|\n|\r/);

will work perfectly.

Be sure \r\n is placed at the leading of the RegExp string, cause it will be tried first.

Bad Request - Invalid Hostname IIS7

Double check the exact URL you're providing. I saw this error when I missed off the route prefix defined in ASP.NET so it didn't know where to route the request.

refresh leaflet map: map container is already initialized

When you just remove a map, it destroys the div id reference, so, after remove() you need to build again the div where the map will be displayed, in order to avoid the "Uncaught Error: Map container not found".

if(map != undefined || map != null){
    map.remove();
   $("#map").html("");
   $("#preMap").empty();
   $( "<div id=\"map\" style=\"height: 500px;\"></div>" ).appendTo("#preMap");
}

How can I limit the visible options in an HTML <select> dropdown?

I used this code and it worked for me on Chrome, Firefox and IE.

_x000D_
_x000D_
<select  onmousedown="if(this.options.length>5){this.size=5;}" onchange="this.blur()"  onblur="this.size=0;">_x000D_
<option>option1</option>_x000D_
<option>option2</option>_x000D_
<option>option3</option>_x000D_
<option>option4</option>_x000D_
<option>option5</option>_x000D_
<option>option6</option>_x000D_
<option>option7</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Opening a folder in explorer and selecting a file

Use "/select,c:\file.txt"

Notice there should be a comma after /select instead of space..

Is there a format code shortcut for Visual Studio?

To align the text in the proper format -

  • Ctrl + K + D for front end pages like .aspx or .cshtml

  • Ctrl + K + F for a .cs page

But observe to press all buttons in sequence...

How to ensure that there is a delay before a service is started in systemd?

Combining the answers from @Ortomala Lokni and @rogerdpack, another alternative is to have the dependent service monitor when the first one has started / done the thing you're waiting for.

For example, here's how I am making the fail2ban service wait for Docker to open port 443 (so that fail2ban's iptables entries take priority over Docker's):

[Service]
ExecStartPre=/bin/bash -c '(while ! nc -z -v -w1 localhost 443 > /dev/null; do echo "Waiting for port 443 to open..."; sleep 2; done); sleep 2'

Simply replace nc -z -v -w1 localhost 443 with a command that fails (non-zero exit code) while the first service is starting and succeeds once it is up.

For the Cassandra case, the ideal would be a command that only returns 0 when the cluster is available.

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

For the record, as far as I can tell, you had two problems:

  1. You weren't passing a "jsonp" type specifier to your $.get, so it was using an ordinary XMLHttpRequest. However, your browser supported CORS (Cross-Origin Resource Sharing) to allow cross-domain XMLHttpRequest if the server OKed it. That's where the Access-Control-Allow-Origin header came in.

  2. I believe you mentioned you were running it from a file:// URL. There are two ways for CORS headers to signal that a cross-domain XHR is OK. One is to send Access-Control-Allow-Origin: * (which, if you were reaching Flickr via $.get, they must have been doing) while the other was to echo back the contents of the Origin header. However, file:// URLs produce a null Origin which can't be authorized via echo-back.

The first was solved in a roundabout way by Darin's suggestion to use $.getJSON. It does a little magic to change the request type from its default of "json" to "jsonp" if it sees the substring callback=? in the URL.

That solved the second by no longer trying to perform a CORS request from a file:// URL.

To clarify for other people, here are the simple troubleshooting instructions:

  1. If you're trying to use JSONP, make sure one of the following is the case:
    • You're using $.get and set dataType to jsonp.
    • You're using $.getJSON and included callback=? in the URL.
  2. If you're trying to do a cross-domain XMLHttpRequest via CORS...
    1. Make sure you're testing via http://. Scripts running via file:// have limited support for CORS.
    2. Make sure the browser actually supports CORS. (Opera and Internet Explorer are late to the party)

How to print all session variables currently set?

echo '<pre>';
var_dump($_SESSION);
echo '</pre>';

Or you can use print_r if you don't care about types. If you use print_r, you can make the second argument TRUE so it will return instead of echo, useful for...

echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';

SQL Server JOIN missing NULL values

Use Left Outer Join instead of Inner Join to include rows with NULLS.

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 LEFT OUTER JOIN 
    Table2 ON Table1.Col1 = Table2.Col1 
    AND Table1.Col2 = Table2.Col2

For more information, see here: http://technet.microsoft.com/en-us/library/ms190409(v=sql.105).aspx

How to use an arraylist as a prepared statement parameter

You may want to use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Sample Code:

PreparedStatement pstmt = 
                conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", new Object[]{"1", "2","3"});
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

Printing Python version in output

Try

python --version 

or

python -V

This will return a current python version in terminal.

RuntimeError: module compiled against API version a but this version of numpy is 9

Check the path

import numpy
print numpy.__path__

For me this was /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy So I moved it to a temporary place

sudo mv /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy \
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy_old

and then the next time I imported numpy the path was /Library/Python/2.7/site-packages/numpy/init.pyc and all was well.

MySQL Fire Trigger for both Insert and Update

You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.

How to send email from Terminal?

If you want to attach a file on Linux

echo 'mail content' | mailx -s 'email subject' -a attachment.txt [email protected]

How to use the 'replace' feature for custom AngularJS directives?

When you have replace: true you get the following piece of DOM:

<div ng-controller="Ctrl" class="ng-scope">
    <div class="ng-binding">hello</div>
</div>

whereas, with replace: false you get this:

<div ng-controller="Ctrl" class="ng-scope">
    <my-dir>
        <div class="ng-binding">hello</div>
    </my-dir>
</div>

So the replace property in directives refer to whether the element to which the directive is being applied (<my-dir> in that case) should remain (replace: false) and the directive's template should be appended as its child,

OR

the element to which the directive is being applied should be replaced (replace: true) by the directive's template.

In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:

.directive('myDir', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div>{{title}}<div ng-transclude></div></div>'
    };
});

In that case if in the directive's template you have an element (or elements) with attribute ng-transclude, its content will be replaced by the element's (to which the directive is being applied) original content.

See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

See this to read more about translusion.

Storyboard doesn't contain a view controller with identifier

Just had this issue after adding a new VC to the storyboard but only on the device, not on the simulator. Turns out it was due to having multiple storyboard localizations - the VC was only added to the primary one. I tried removing the other localizations (one of which is the one my iPhone uses) but still had the error. In the end I had to recreate the other localizations with the new VC in each of them.

The 'packages' element is not declared

Oh ok - now I get it. You can ignore this one - the XML for this is just not correct - the packages-element is indeed not declared (there is no reference to a schema or whatever). I think this is a known minor bug that won't do a thing because only NuGet will use this.

See this similar question also.

How to apply CSS page-break to print a table with lots of rows?

You should use

<tbody> 
  <tr>
  first page content here 
  </tr>
  <tr>
  ..
  </tr>
</tbody>
<tbody>
  next page content...
</tbody>

And CSS:

tbody { display: block; page-break-before: avoid; }
tbody { display: block; page-break-after: always; }

Hidden Features of Xcode

?` to properly format (reindent) your code

EDIT: Apparently re-indent feature (Edit > Format > Reindent) has no default shortcut. I guess I assigned one (in Preferences > Key bindings) a long time ago and don't even remember about that. Sorry for misleading you.

How to fix 'Notice: Undefined index:' in PHP form action

enctype="multipart/form-data"

Check your enctype in the form before submitting

How can I generate a tsconfig.json file?

You need to have typescript library installed and then you can use

npx tsc --init 

If the response is error TS5023: Unknown compiler option 'init'. that means the library is not installed

yarn add --dev typescript

and run npx command again

How to quietly remove a directory with content in PowerShell

To delete content without a folder you can use the following:

Remove-Item "foldertodelete\*" -Force -Recurse

Regex - Should hyphens be escaped?

Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z] or [0-9-]), OR escape it (e.g. [a-z\-0-9]) in order to add "hyphen" to your class.

It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.

(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)

Great question!

How to draw a circle with text in the middle?

For me, only this solution worked for multiline text:

.circle-multiline {
    display: table-cell;
    height: 200px;
    width: 200px;
    text-align: center;
    vertical-align: middle;
    border-radius: 50%;
    background: yellow;
}

Google maps Places API V3 autocomplete - select first option on enter

How about this?

$("input").keypress(function(event) {
  var firstValue = null;
  if (event.keyCode == 13 || event.keyCode == 9) {
    $(event.target).blur();
    if ($(".pac-container .pac-item:first span:eq(3)").text() == "") {
      firstValue = $(".pac-container .pac-item:first .pac-item-query").text();
    } else {
      firstValue = $(".pac-container .pac-item:first .pac-item-query").text() + ", " + $(".pac-container .pac-item:first span:eq(3)").text();
    }
    event.target.value = firstValue;
  } else
    return true;
});

How to set the matplotlib figure default size in ipython notebook?

Just for completeness, this also works

from IPython.core.pylabtools import figsize
figsize(14, 7)

It is a wrapper aroung the rcParams solution

Html.Textbox VS Html.TextboxFor

The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

Get Client Machine Name in PHP

PHP Manual says:

gethostname (PHP >= 5.3.0) gethostname — Gets the host name

Look:

<?php
echo gethostname(); // may output e.g,: sandie
// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>

http://php.net/manual/en/function.gethostname.php

Enjoy

Moving average or running mean

Another solution just using a standard library and deque:

from collections import deque
import itertools

def moving_average(iterable, n=3):
    # http://en.wikipedia.org/wiki/Moving_average
    it = iter(iterable) 
    # create an iterable object from input argument
    d = deque(itertools.islice(it, n-1))  
    # create deque object by slicing iterable
    d.appendleft(0)
    s = sum(d)
    for elem in it:
        s += elem - d.popleft()
        d.append(elem)
        yield s / n

# example on how to use it
for i in  moving_average([40, 30, 50, 46, 39, 44]):
    print(i)

# 40.0
# 42.0
# 45.0
# 43.0

How to select the first element with a specific attribute using XPath

Use the index to get desired node if xpath is complicated or more than one node present with same xpath.

Ex :

(//bookstore[@location = 'US'])[index]

You can give the number which node you want.

UIView Infinite 360 degree rotation animation?

Swift 4.0

func rotateImageView()
{
    UIView.animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: {() -> Void in
        self.imageView.transform = self.imageView.transform.rotated(by: .pi / 2)
    }, completion: {(_ finished: Bool) -> Void in
        if finished {
            rotateImageView()
        }
    })
}

Getting ssh to execute a command in the background on target machine

If you don't/can't keep the connection open you could use screen, if you have the rights to install it.

user@localhost $ screen -t remote-command
user@localhost $ ssh user@target # now inside of a screen session
user@remotehost $ cd /some/directory; program-to-execute &

To detach the screen session: ctrl-a d

To list screen sessions:

screen -ls

To reattach a session:

screen -d -r remote-command

Note that screen can also create multiple shells within each session. A similar effect can be achieved with tmux.

user@localhost $ tmux
user@localhost $ ssh user@target # now inside of a tmux session
user@remotehost $ cd /some/directory; program-to-execute &

To detach the tmux session: ctrl-b d

To list screen sessions:

tmux list-sessions

To reattach a session:

tmux attach <session number>

The default tmux control key, 'ctrl-b', is somewhat difficult to use but there are several example tmux configs that ship with tmux that you can try.

How to commit a change with both "message" and "description" from the command line?

Use the git commit command without any flags. The configured editor will open (Vim in this case):

enter image description here

To start typing press the INSERT key on your keyboard, then in insert mode create a better commit with description how do you want. For example:

enter image description here

Once you have written all that you need, to returns to git, first you should exit insert mode, for that press ESC. Now close the Vim editor with save changes by typing on the keyboard :wq (w - write, q - quit):

enter image description here

and press ENTER.

On GitHub this commit will looks like this:

enter image description here

As a commit editor you can use VS Code:

git config --global core.editor "code --wait"

From VS Code docs website: VS Code as Git editor

Gif demonstration: enter image description here

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

This worked for me:

  1. Delete the originally created site.
  2. Recreate the site in IIS
  3. Clean solution
  4. Build solution

Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.

source of historical stock data

A data set of every symbol on the NASDAQ and NYSE on a second or minute interval is going to be massive.

Let's say there are a total of 4000 companies listed on both exchanges (this is probably on the very low side since there are over 3200 companies listed on the NASDAQ). For data at a second interval, assuming there are 6.5 trading hours in a day, that would give you 23400 data points per day per company, or about 93,600,000 data points in total for that one day. Assuming 200 trading days in a year, thats about 18,720,000,000 data points for just one year.

Maybe you want to start with a smaller set first?

Get HTML inside iframe using jQuery

$(editFrame).contents().find("html").html();

How to rename with prefix/suffix?

You could use the rename(1) command:

rename 's/(.*)$/new.$1/' original.filename

Edit: If rename isn't available and you have to rename more than one file, shell scripting can really be short and simple for this. For example, to rename all *.jpg to prefix_*.jpg in the current directory:

for filename in *.jpg; do mv "$filename" "prefix_$filename"; done;

How to automatically generate N "distinct" colors?

This OpenCV function uses the HSV color model to generate n evenly distributed colors around the 0<=H<=360º with maximum S=1.0 and V=1.0. The function outputs the BGR colors in bgr_mat:

void distributed_colors (int n, cv::Mat_<cv::Vec3f> & bgr_mat) {
  cv::Mat_<cv::Vec3f> hsv_mat(n,CV_32F,cv::Vec3f(0.0,1.0,1.0));
  double step = 360.0/n;
  double h= 0.0;
  cv::Vec3f value;
  for (int i=0;i<n;i++,h+=step) {
    value = hsv_mat.at<cv::Vec3f>(i);
    hsv_mat.at<cv::Vec3f>(i)[0] = h;
  }
  cv::cvtColor(hsv_mat, bgr_mat, CV_HSV2BGR);
  bgr_mat *= 255;
}

Convert datetime to valid JavaScript date

You can use get methods:

_x000D_
_x000D_
var fullDate = new Date();_x000D_
console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
    twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
    twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
_x000D_
_x000D_

How to create a DB link between two oracle instances

After creating the DB link, if the two instances are present in two different databases, then you need to setup a TNS entry on the A machine so that it resolve B. check out here

How to get the list of all installed color schemes in Vim?

Here is a small function I wrote to try all the colorschemes in $VIMRUNTIME/colors directory.

Add the below function to your vimrc, then open your source file and call the function from command.

function! DisplayColorSchemes()
   let currDir = getcwd()
   exec "cd $VIMRUNTIME/colors"
   for myCol in split(glob("*"), '\n')
      if myCol =~ '\.vim'
         let mycol = substitute(myCol, '\.vim', '', '')
         exec "colorscheme " . mycol
         exec "redraw!"
         echo "colorscheme = ". myCol
         sleep 2
      endif
   endfor
   exec "cd " . currDir
endfunction

Ansible: Store command's stdout in new variable?

A slight modification beyond @udondan's answer. I like to reuse the registered variable names with the set_fact to help keep the clutter to a minimum.

So if I were to register using the variable, psk, I'd use that same variable name with creating the set_fact.

Example

- name: generate PSK
  shell: openssl rand -base64 48
  register: psk
  delegate_to: 127.0.0.1
  run_once: true

- set_fact: 
    psk={{ psk.stdout }}

- debug: var=psk
  run_once: true

Then when I run it:

$ ansible-playbook -i inventory setup_ipsec.yml

 PLAY                                                                                                                                                                                [all] *************************************************************************************************************************************************************************

 TASK [Gathering                                                                                                                                                                     Facts] *************************************************************************************************************************************************************
 ok: [hostc.mydom.com]
 ok: [hostb.mydom.com]
 ok: [hosta.mydom.com]

 TASK [libreswan : generate                                                                                                                                                          PSK] ****************************************************************************************************************************************************
 changed: [hosta.mydom.com -> 127.0.0.1]

 TASK [libreswan :                                                                                                                                                                   set_fact] ********************************************************************************************************************************************************
 ok: [hosta.mydom.com]
 ok: [hostb.mydom.com]
 ok: [hostc.mydom.com]

 TASK [libreswan :                                                                                                                                                                   debug] ***********************************************************************************************************************************************************
 ok: [hosta.mydom.com] => {
     "psk": "6Tx/4CPBa1xmQ9A6yKi7ifONgoYAXfbo50WXPc1kGcird7u/pVso/vQtz+WdBIvo"
 }

 PLAY                                                                                                                                                                                RECAP *************************************************************************************************************************************************************************
 hosta.mydom.com    : ok=4    changed=1    unreachable=0    failed=0
 hostb.mydom.com    : ok=2    changed=0    unreachable=0    failed=0
 hostc.mydom.com    : ok=2    changed=0    unreachable=0    failed=0

Use of *args and **kwargs

Here's an example that uses 3 different types of parameters.

def func(required_arg, *args, **kwargs):
    # required_arg is a positional-only parameter.
    print required_arg

    # args is a tuple of positional arguments,
    # because the parameter name has * prepended.
    if args: # If args is not empty.
        print args

    # kwargs is a dictionary of keyword arguments,
    # because the parameter name has ** prepended.
    if kwargs: # If kwargs is not empty.
        print kwargs

>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() takes at least 1 argument (0 given)

>>> func("required argument")
required argument

>>> func("required argument", 1, 2, '3')
required argument
(1, 2, '3')

>>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo")
required argument
(1, 2, '3')
{'keyword2': 'foo', 'keyword1': 4}

jQuery selector for id starts with specific text

Let me offer a more extensive answer considering things that you haven't mentioned as yet but will find useful.

For your current problem the answer is

$("div[id^='editDialog']");

The caret (^) is taken from regular expressions and means starts with.

Solution 1

// Select elems where 'attribute' ends with 'Dialog'
$("[attribute$='Dialog']"); 

// Selects all divs where attribute is NOT equal to value    
$("div[attribute!='value']"); 

// Select all elements that have an attribute whose value is like
$("[attribute*='value']"); 

// Select all elements that have an attribute whose value has the word foobar
$("[attribute~='foobar']"); 

// Select all elements that have an attribute whose value starts with 'foo' and ends
//  with 'bar'
$("[attribute^='foo'][attribute$='bar']");

attribute in the code above can be changed to any attribute that an element may have, such as href, name, id or src.

Solution 2

Use classes

// Matches all items that have the class 'classname'
$(".className");

// Matches all divs that have the class 'classname'
$("div.className");

Solution 3

List them (also noted in previous answers)

$("#id1,#id2,#id3");

Solution 4

For when you improve, regular expression (Never actually used these, solution one has always been sufficient, but you never know!

// Matches all elements whose id takes the form editDialog-{one_or_more_integers}
$('div').filter(function () {this.id.match(/editDialog\-\d+/)});

Psql could not connect to server: No such file or directory, 5432 error?

Open your database manager and execute this script

update pg_database set datallowconn = 'true' where datname = 'your_database_name';

Simple parse JSON from URL on Android and display in listview

I would suggest using the JSONParser class. It's very easy to use.

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) throws IOException {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (Exception ex) {
        Log.d("Networking", ex.getLocalizedMessage());
        throw new IOException("Error connecting");
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

Then in your application, create an instance of this class. You may want to pass the constructor 'GET' or 'POST' if desired.

public JSONParser jsonParser = new JSONParser();

try {

    // Building Parameters ( you can pass as many parameters as you want)
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair("name", name));
    params.add(new BasicNameValuePair("age", 25));

    // Getting JSON Object
    JSONObject json = jsonParser.makeHttpRequest(YOUR_URL, "POST", params);
} catch (JSONException e) {
    e.printStackTrace();
}

Logging in Scala

Quick and easy forms.

Scala 2.10 and older:

import com.typesafe.scalalogging.slf4j.Logger
import org.slf4j.LoggerFactory
val logger = Logger(LoggerFactory.getLogger("TheLoggerName"))
logger.debug("Useful message....")

And build.sbt:

libraryDependencies += "com.typesafe" %% "scalalogging-slf4j" % "1.1.0"

Scala 2.11+ and newer:

import import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory
val logger = Logger(LoggerFactory.getLogger("TheLoggerName"))
logger.debug("Useful message....")

And build.sbt:

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.1.0"

Variable's memory size in Python

Use sys.getsizeof to get the size of an object, in bytes.

>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
12
>>> a = 2**1000
>>> getsizeof(a)
146
>>>

Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.

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

In case anyone else is running in to the same problem, the only solution I could find that satisfied me was to have the canvas cover everything and then to raise the Z-index of all clickable elements. You can't draw on them, but at least they are clickable...

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

How to convert UTC timestamp to device local time in android

I have do something like this to get date in local device timezone from UTC time stamp.

private long UTC_TIMEZONE=1470960000;
private String OUTPUT_DATE_FORMATE="dd-MM-yyyy - hh:mm a"

getDateFromUTCTimestamp(UTC_TIMEZONE,OUTPUT_DATE_FORMATE);

Here is the function

 public String getDateFromUTCTimestamp(long mTimestamp, String mDateFormate) {
        String date = null;
        try {
            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            cal.setTimeInMillis(mTimestamp * 1000L);
            date = DateFormat.format(mDateFormate, cal.getTimeInMillis()).toString();

            SimpleDateFormat formatter = new SimpleDateFormat(mDateFormate);
            formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date value = formatter.parse(date);

            SimpleDateFormat dateFormatter = new SimpleDateFormat(mDateFormate);
            dateFormatter.setTimeZone(TimeZone.getDefault());
            date = dateFormatter.format(value);
            return date;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

Result :

12-08-2016 - 04:30 PM 

Hope this will work for others.

What does the ">" (greater-than sign) CSS selector mean?

It matches p elements with class some_class that are directly under a div.

View markdown files offline

From now I use http://marxi.co/. Marxi.co has online and offline version.

Go to "next" iteration in JavaScript forEach loop

just return true inside your if statement

var myArr = [1,2,3,4];

myArr.forEach(function(elem){
  if (elem === 3) {

      return true;

    // Go to "next" iteration. Or "continue" to next iteration...
  }

  console.log(elem);
});

Get full path of a file with FileUpload Control

Convert.ToString(FileUpload1.PostedFile.FileName);

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Use of exit() function

Include stdlib.h in your header, and then call abort(); in any place you want to exit your program. Like this:

switch(varName)
{
    case 1: 
     blah blah;
    case 2:
     blah blah;
    case 3:
     abort();
}

When the user enters the switch accepts this and give it to the case 3 where you call the abort function. It will exit your screen immediately after hitting enter key.

How do I execute a stored procedure in a SQL Agent job?

As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.

Export a list into a CSV or TXT file in R

I export lists into YAML format with CPAN YAML package.

l <- list(a="1", b=1, c=list(a="1", b=1))
yaml::write_yaml(l, "list.yaml")

Bonus of YAML that it's a human readable text format so it's easy to read/share/import/etc

$ cat list.yaml
a: '1'
b: 1.0
c:
  a: '1'
  b: 1.0

Home does not contain an export named Home

I just ran into this error message (after upgrading to nextjs 9 some transpiled imports started giving this error). I managed to fix them using syntax like this:

import * as Home from './layouts/Home';

How do I Alter Table Column datatype on more than 1 column?

ALTER TABLE can do multiple table alterations in one statement, but MODIFY COLUMN can only work on one column at a time, so you need to specify MODIFY COLUMN for each column you want to change:

ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100);

Also, note this warning from the manual:

When you use CHANGE or MODIFY, column_definition must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.

ASP.NET Identity reset password

Or how can I reset without knowing the current one (user forgot password)?

If you want to change a password using the UserManager but you do not want to supply the user's current password, you can generate a password reset token and then use it immediately instead.

string resetToken = await UserManager.GeneratePasswordResetTokenAsync(model.Id);
IdentityResult passwordChangeResult = await UserManager.ResetPasswordAsync(model.Id, resetToken, model.NewPassword);

How can I delete multiple lines in vi?

Press the Esc key to make sure your are not in an edit mode. Place the cursor on the first line to be deleted. Enter :5dd. The current line, and the next four lines should be deleted.

Alternately, if you have line numbering turned on...

Press the Esc key to make sure your are not in an edit mode. Enter :#,#d where '#' stands for the beginning and ending line numbers to be deleted.

Adding a directory to the PATH environment variable in Windows

Option 1

After you change PATH with the GUI, close and re-open the console window.

This works because only programs started after the change will see the new PATH.

Option 2

Execute this command in the command window you have open:

set PATH=%PATH%;C:\your\path\here\

This command appends C:\your\path\here\ to the current PATH.

Breaking it down:

  • set – A command that changes cmd's environment variables only for the current cmd session; other programs and the system are unaffected.
  • PATH= – Signifies that PATH is the environment variable to be temporarily changed.
  • %PATH%;C:\your\path\here\ – The %PATH% part expands to the current value of PATH, and ;C:\your\path\here\ is then concatenated to it. This becomes the new PATH.

Codeigniter displays a blank page instead of error messages

please check either error folder is in application folder of not in my case i replace error folder in application folder

Change the Blank Cells to "NA"

You can use gsub to replace multiple mutations of empty, like "" or a space, to be NA:

data= data.frame(cats=c('', ' ', 'meow'), dogs=c("woof", " ", NA))
apply(data, 2, function(x) gsub("^$|^ $", NA, x))

MySQL TEXT vs BLOB vs CLOB

TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

Why is my CSS style not being applied?

For me, it was the local overrides in Sources -> Overrides. A file gets saved locally whenever you change the styling of a page and chrome uses that file to override the server's css.

Markdown and including multiple files

In fact you can use \input{filename} and \include{filename} which are latex commands, directly in Pandoc, because it supports nearly all html and latex syntax.

But beware, the included file will be treated as latex file. But you can compile your markdown to latex with Pandox easily.

How to convert NSNumber to NSString

In Swift you can do like this

let number : NSNumber = 95
let str : String = number.stringValue

Expected response code 220 but got code "", with message "" in Laravel

I did as per sid saying my env after updating is

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<mygmailaddress>
MAIL_PASSWORD=<gmailpassword>
MAIL_ENCRYPTION=tls

this did work without 2 step verification. with 2 step verification enabled it did not work for me.

List all devices, partitions and volumes in Powershell

We have multiple volumes per drive (some are mounted on subdirectories on the drive). This code shows a list of the mount points and volume labels. Obviously you can also extract free space and so on:

gwmi win32_volume|where-object {$_.filesystem -match "ntfs"}|sort {$_.name} |foreach-object {
  echo "$(echo $_.name) [$(echo $_.label)]"
}

Android: Unable to add window. Permission denied for this window type

I guess you should differentiate the target (before and after Oreo)

int LAYOUT_FLAG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
    LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
}

params = new WindowManager.LayoutParams(
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.WRAP_CONTENT,
    LAYOUT_FLAG,
    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
    PixelFormat.TRANSLUCENT);

grep exclude multiple strings

egrep -v "Nopaging the limit is|keyword to remove is"

How to force the browser to reload cached CSS and JavaScript files

Don’t use foo.css?version=1!

Browsers aren't supposed to cache URLs with GET variables. According to http://www.thinkvitamin.com/features/webapps/serving-javascript-fast, though Internet Explorer and Firefox ignore this, Opera and Safari don't! Instead, use foo.v1234.css, and use rewrite rules to strip out the version number.

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

The ENABLEDELAYEDEXPANSION part is REQUIRED in certain programs that use delayed expansion, that is, that takes the value of variables that were modified inside IF or FOR commands by enclosing their names in exclamation-marks.

If you enable this expansion in a script that does not require it, the script behaves different only if it contains names enclosed in exclamation-marks !LIKE! !THESE!. Usually the name is just erased, but if a variable with the same name exist by chance, then the result is unpredictable and depends on the value of such variable and the place where it appears.

The SETLOCAL part is REQUIRED in just a few specialized (recursive) programs, but is commonly used when you want to be sure to not modify any existent variable with the same name by chance or if you want to automatically delete all the variables used in your program. However, because there is not a separate command to enable the delayed expansion, programs that require this must also include the SETLOCAL part.

Spring Data: "delete by" is supported?

2 ways:-

1st one Custom Query

@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);

2nd one JPA Query by method

List<User> deleteByLastname(String lastname);

When you go with query by method (2nd way) it will first do a get call

select * from user where last_name = :firstName

Then it will load it in a List Then it will call delete id one by one

delete from user where id = 18
delete from user where id = 19

First fetch list of object, then for loop to delete id one by one

But, the 1st option (custom query),

It's just a single query It will delete wherever the value exists.

Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby

How can I use grep to find a word inside a folder?

  1. grep -r "yourstring" * Will find "yourstring" in any files and folders

Now if you want to look for two different strings at the same time you can always use option E and add words for the search. example after the break

  1. grep -rE "yourstring|yourotherstring|$" * will search for list locations where yourstring or yourotherstring matches

How to create a QR code reader in a HTML5 website?

Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.

However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.

Happy coding.

Reload .profile in bash shell script (in unix)?

Try this to reload your current shell:

source ~/.profile

Android: How to bind spinner to custom object list?

You can look at this answer. You can also go with a custom adapter, but the solution below is fine for simple cases.

Here's a re-post:

So if you came here because you want to have both labels and values in the Spinner - here's how I did it:

  1. Just create your Spinner the usual way
  2. Define 2 equal size arrays in your array.xml file -- one array for labels, one array for values
  3. Set your Spinner with android:entries="@array/labels"
  4. When you need a value, do something like this (no, you don't have to chain it):

      String selectedVal = getResources().getStringArray(R.array.values)[spinner.getSelectedItemPosition()];
    

c# .net change label text

If I understand correctly you may be experiencing the problem because in order to be able to set the labels "text" property you actually have to use the "content" property.

so instead of:

  Label output = null;
        output = Label1;
        output.Text = "hello";

try:

Label output = null;
            output = Label1;
            output.Content = "hello";

How to send cookies in a post request with the Python Requests library?

The latest release of Requests will build CookieJars for you from simple dictionaries.

import requests

cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}

r = requests.post('http://wikipedia.org', cookies=cookies)

Enjoy :)

Best way to create a simple python web service

Have a look at werkzeug. Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules.

It includes lots of cool tools to work with http and has the advantage that you can use it with wsgi in different environments (cgi, fcgi, apache/mod_wsgi or with a plain simple python server for debugging).

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

Sorting a tab delimited file

Lars Haugseth answer only worked from the command line for me where it gives this error if executed from a shell script:

sort: multi-character tab ‘$\t’

The solution if it's coded in a shell script if anyone's looking is

sort -t'    '

the tab character is in between the quote.

What does -XX:MaxPermSize do?

-XX:PermSize -XX:MaxPermSize are used to set size for Permanent Generation.

Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.

Generate a unique id

We can do something like this

string TransactionID = "BTRF"+DateTime.Now.Ticks.ToString().Substring(0, 10);

Unicode (UTF-8) reading and writing to files in Python

So, I've found a solution for what I'm looking for, which is:

print open('f2').read().decode('string-escape').decode("utf-8")

There are some unusual codecs that are useful here. This particular reading allows one to take UTF-8 representations from within Python, copy them into an ASCII file, and have them be read in to Unicode. Under the "string-escape" decode, the slashes won't be doubled.

This allows for the sort of round trip that I was imagining.

Why isn't this code to plot a histogram on a continuous value Pandas column working?

Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing

#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()

Git Checkout warning: unable to unlink files, permission denied

Make sure that any associated processes or threads are not running and perform end task or force quit as necessary.

Make sure you change the ownership permission.

ModalPopupExtender OK Button click event not firing?

Put into the Button-Control the Attribute "UseSubmitBehavior=false".

Meaning of 'const' last in a function declaration of a class?

The const keyword used with the function declaration specifies that it is a const member function and it will not be able to change the data members of the object.

Open mvc view in new window from controller

I've seen where you can do something like this, assuming "NewWindow.cshtml" is in your "Home" folder:

string url = "/Home/NewWindow";
return JavaScript(string.Format("window.open('{0}', '_blank', 'left=100,top=100,width=500,height=500,toolbar=no,resizable=no,scrollable=yes');", url));

or

return Content("/Home/NewWindow");

If you just want to open views in tabs, you could use JavaScript click events to render your partial views. This would be your controller method for NewWindow.cshtml:

public ActionResult DisplayNewWindow(NewWindowModel nwm) {
    // build model list based on its properties & values
    nwm.Name = "John Doe";
    nwm.Address = "123 Main Street";
    return PartialView("NewWindow", nwm);
}

Your markup on your page this is calling it would go like this:

<input type="button" id="btnNewWin" value="Open Window" />
<div id="newWinResults" />

And the JavaScript (requires jQuery):

var url = '@Url.Action("NewWindow", "Home")';
$('btnNewWin').on('click', function() {
    var model = "{ 'Name': 'Jane Doe', 'Address': '555 Main Street' }"; // you must build your JSON you intend to pass into the "NewWindowModel" manually
    $('#newWinResults').load(url, model); // may need to do JSON.stringify(model)
});

Note that this JSON would overwrite what is in that C# function above. I had it there for demonstration purposes on how you could hard-code values, only.

(Adapted from Rendering partial view on button click in ASP.NET MVC)

IF formula to compare a date with current date and return result

You can enter the following formula in the cell where you want to see the Overdue or Not due result:

=IF(ISBLANK(O10),"",IF(O10<TODAY(),"Overdue","Not due"))

This formula first tests if the source cell is blank. If it is, then the result cell will be filled with the empty string. If the source is not blank, then the formula tests if the date in the source cell is before the current day. If it is, then the value is set to Overdue, otherwise it is set to Not due.

What does O(log n) mean exactly?

What's logb(n)?

It is the number of times you can cut a log of length n repeatedly into b equal parts before reaching a section of size 1.

How to delete duplicates on a MySQL table?

I find Werner's solution above to be the most convenient because it works regardless of the presence of a primary key, doesn't mess with tables, uses future-proof plain sql, is very understandable.

As I stated in my comment, that solution hasn't been properly explained though. So this is mine, based on it.

1) add a new boolean column

alter table mytable add tokeep boolean;

2) add a constraint on the duplicated columns AND the new column

alter table mytable add constraint preventdupe unique (mycol1, mycol2, tokeep);

3) set the boolean column to true. This will succeed only on one of the duplicated rows because of the new constraint

update ignore mytable set tokeep = true;

4) delete rows that have not been marked as tokeep

delete from mytable where tokeep is null;

5) drop the added column

alter table mytable drop tokeep;

I suggest that you keep the constraint you added, so that new duplicates are prevented in the future.

Undefined index error PHP

This is happening because your PHP code is getting executed before the form gets posted.

To avoid this wrap your PHP code in following if statement and it will handle the rest no need to set if statements for each variables

       if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST))
        {
             //process PHP Code
        }
        else
        {
             //do nothing
         }

SVN Commit failed, access forbidden

As a new user to these two software packages, I experienced the exact same problem. As was also discovered above, my solution was to use the same case letters as is in the Repository path.

Here's a tip that I find helpful: In VisualSVN, you can right click on the path, then click "Copy URL to Clipboard" for pasting in Tortoise to be sure that the path is the identical case.

How to validate a form with multiple checkboxes to have atleast one checked

How about this

$.validate.addMethod(cb_selectone,
                   function(value,element){
                           if(element.length>0){
                               for(var i=0;i<element.length;i++){
                                if($(element[i]).val('checked')) return true;
                               }
                           return false;
                           }
                            return false;
                  },
                  'Please select a least one')

Now you ca do

$.validate({rules:{checklist:"cb_selectone"}});

You can even go further a specify the minimum number to select with a third param in the callback function.I have not tested it yet so tell me if it works.

How can I convert an integer to a hexadecimal string in C?

To convert an integer to a string also involves char array or memory management.

To handle that part for such short arrays, code could use a compound literal, since C99, to create array space, on the fly. The string is valid until the end of the block.

#define UNS_HEX_STR_SIZE ((sizeof (unsigned)*CHAR_BIT + 3)/4 + 1)
//                         compound literal v--------------------------v
#define U2HS(x) unsigned_to_hex_string((x), (char[UNS_HEX_STR_SIZE]) {0}, UNS_HEX_STR_SIZE)

char *unsigned_to_hex_string(unsigned x, char *dest, size_t size) {
  snprintf(dest, size, "%X", x);
  return dest;
}

int main(void) {
  // 3 array are formed v               v        v
  printf("%s %s %s\n", U2HS(UINT_MAX), U2HS(0), U2HS(0x12345678));
  char *hs = U2HS(rand());
  puts(hs);
  // `hs` is valid until the end of the block
}

Output

FFFFFFFF 0 12345678
5851F42D

Node.js: Difference between req.query[] and req.params

I want to mention one important note regarding req.query , because currently I am working on pagination functionality based on req.query and I have one interesting example to demonstrate to you...

Example:

// Fetching patients from the database
exports.getPatients = (req, res, next) => {

const pageSize = +req.query.pageSize;
const currentPage = +req.query.currentPage;

const patientQuery = Patient.find();
let fetchedPatients;

// If pageSize and currentPage are not undefined (if they are both set and contain valid values)
if(pageSize && currentPage) {
    /**
     * Construct two different queries 
     * - Fetch all patients 
     * - Adjusted one to only fetch a selected slice of patients for a given page
     */
    patientQuery
        /**
         * This means I will not retrieve all patients I find, but I will skip the first "n" patients
         * For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
         * 
         * Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
         * so I want to skip (7 * (2 - 1)) => 7 items
         */
        .skip(pageSize * (currentPage - 1))

        /**
         * Narrow dont the amound documents I retreive for the current page
         * Limits the amount of returned documents
         * 
         * For example: If I got 7 items per page, then I want to limit the query to only
         * return 7 items. 
         */
        .limit(pageSize);
}
patientQuery.then(documents => {
    res.status(200).json({
        message: 'Patients fetched successfully',
        patients: documents
    });
  });
};

You will noticed + sign in front of req.query.pageSize and req.query.currentPage

Why? If you delete + in this case, you will get an error, and that error will be thrown because we will use invalid type (with error message 'limit' field must be numeric).

Important: By default if you extracting something from these query parameters, it will always be a string, because it's coming the URL and it's treated as a text.

If we need to work with numbers, and convert query statements from text to number, we can simply add a plus sign in front of statement.

PHP header() redirect with POST variables

If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.

// form.php

<?php

    if (!empty($_POST['submit'])) {
        // validate

        if ($allGood) {
            // put data into database or whatever needs to be done

            header('Location: nextpage.php');
            exit;
        }
    }

?>

<form action="form.php">
    <input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
    ...
</form>

This can be made more elegant, but you get the idea...

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

android:drawableLeft margin and/or padding

If the size of drawable resouce is fixed, you can do like this:

<Button
    android:background="@drawable/rounded_button_green"
    style="?android:attr/selectableItemBackground"
    android:layout_height="wrap_content"
    app:layout_widthPercent="70%"
    android:drawableRight="@drawable/ic_clear_black_24dp"
    android:paddingRight="10dp"
    android:paddingLeft="34dp"
    tools:text="example" />

The key here is that:

    android:drawableRight="@drawable/ic_clear_black_24dp"
    android:paddingRight="10dp"
    android:paddingLeft="34dp"

That is, the size of drawable resource plus paddingRight is the paddingLeft.

You can see the result in this example

Read a text file in R line by line

Here is the solution with a for loop. Importantly, it takes the one call to readLines out of the for loop so that it is not improperly called again and again. Here it is:

fileName <- "up_down.txt"
conn <- file(fileName,open="r")
linn <-readLines(conn)
for (i in 1:length(linn)){
   print(linn[i])
}
close(conn)

Why doesn't the height of a container element increase if it contains floated elements?

you can use overflow property to the container div if you don't have any div to show over the container eg:

<div class="cointainer">
    <div class="one">Content One</div>
    <div class="two">Content Two</div>
</div>

Here is the following css:

.container{
    width:100%;/* As per your requirment */
    height:auto;
    float:left;
    overflow:hidden;
}
.one{
    width:200px;/* As per your requirment */
    height:auto;
    float:left;
}

.two{
    width:200px;/* As per your requirment */
    height:auto;
    float:left;
}

-----------------------OR------------------------------

    <div class="cointainer">
        <div class="one">Content One</div>
        <div class="two">Content Two</div>
        <div class="clearfix"></div>
    </div>

Here is the following css:

    .container{
        width:100%;/* As per your requirment */
        height:auto;
        float:left;
        overflow:hidden;
    }
    .one{
        width:200px;/* As per your requirment */
        height:auto;
        float:left;
    }

    .two{
        width:200px;/* As per your requirment */
        height:auto;
        float:left;
    }
    .clearfix:before,
    .clearfix:after{
        display: table;
        content: " ";
    }
    .clearfix:after{
        clear: both;
    }

Deprecated: mysql_connect()

mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.

Use mysqli_* function or pdo

Read Oracle Converting to MySQLi

Grep only the first match and stop

My grep-a-like program ack has a -1 option that stops at the first match found anywhere. It supports the -m 1 that @mvp refers to as well. I put it in there because if I'm searching a big tree of source code to find something that I know exists in only one file, it's unnecessary to find it and have to hit Ctrl-C.

using wildcards in LDAP search filters/queries

Your best bet would be to anticipate prefixes, so:

"(|(displayName=SEARCHKEY*)(displayName=ITSM - SEARCHKEY*)(displayName=alt prefix - SEARCHKEY*))"

Clunky, but I'm doing a similar thing within my organization.

Create an Oracle function that returns a table

I think you want a pipelined table function.

Something like this:

CREATE OR REPLACE PACKAGE test AS

    TYPE measure_record IS RECORD(
       l4_id VARCHAR2(50), 
       l6_id VARCHAR2(50), 
       l8_id VARCHAR2(50), 
       year NUMBER, 
       period NUMBER,
       VALUE NUMBER);

    TYPE measure_table IS TABLE OF measure_record;

    FUNCTION get_ups(foo NUMBER)
        RETURN measure_table
        PIPELINED;
END;

CREATE OR REPLACE PACKAGE BODY test AS

    FUNCTION get_ups(foo number)
        RETURN measure_table
        PIPELINED IS

        rec            measure_record;

    BEGIN
        SELECT 'foo', 'bar', 'baz', 2010, 5, 13
          INTO rec
          FROM DUAL;

        -- you would usually have a cursor and a loop here   
        PIPE ROW (rec);

        RETURN;
    END get_ups;
END;

For simplicity I removed your parameters and didn't implement a loop in the function, but you can see the principle.

Usage:

SELECT *
  FROM table(test.get_ups(0));



L4_ID L6_ID L8_ID       YEAR     PERIOD      VALUE
----- ----- ----- ---------- ---------- ----------
foo   bar   baz         2010          5         13
1 row selected.

Adding values to Arraylist

There's a faster and easy way in Java 9 without involving much of code: Using Collection Factory methods:

List<String> list = List.of("first", "second", "third");

Uncaught Typeerror: cannot read property 'innerHTML' of null

I had a similar problem, but I had the existing id, and as egiray said, I was calling DOM before it loaded and Javascript console was showing the same error, so I tried:

window.onload = (function(){myfuncname()});

and it starts working.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Take a look at DATEDIFF, this should be what you're looking for. It takes the two dates you're comparing, and the date unit you want the difference in (days, months, seconds...)

Hashing a string with Sha256

In the PHP version you can send 'true' in the last parameter, but the default is 'false'. The following algorithm is equivalent to the default PHP's hash function when passing 'sha256' as the first parameter:

public static string GetSha256FromString(string strData)
    {
        var message = Encoding.ASCII.GetBytes(strData);
        SHA256Managed hashString = new SHA256Managed();
        string hex = "";

        var hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

Truncate with condition

As a response to your question: "i want to reset all the data and keep last 30 days inside the table."

you can create an event. Check https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html

For example:

CREATE EVENT DeleteExpiredLog
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM log WHERE date < DATE_SUB(NOW(), INTERVAL 30 DAY);

Will run a daily cleanup in your table, keeping the last 30 days data available

How to check if a table contains an element in Lua?

I can't think of another way to compare values, but if you use the element of the set as the key, you can set the value to anything other than nil. Then you get fast lookups without having to search the entire table.

Why can I not push_back a unique_ptr into a vector?

You need to move the unique_ptr:

vec.push_back(std::move(ptr2x));

unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it.

Note, however, that your current use of unique_ptr is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:

std::unique_ptr<int> ptr(new int(1));

In C++14 we have an even better way to do so:

make_unique<int>(5);

How do I center this form in css?

Another way

_x000D_
_x000D_
body {_x000D_
    text-align: center;_x000D_
}_x000D_
form {_x000D_
    display: inline-block;_x000D_
}
_x000D_
<body>_x000D_
  <form>_x000D_
    <input type="text" value="abc">_x000D_
  </form>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to pass a view's onClick event to its parent on Android?

Declare your TextView not clickable / focusable by using android:clickable="false" and android:focusable="false" or v.setClickable(false) and v.setFocusable(false). The click events should be dispatched to the TextView's parent now.

Note:

In order to achieve this, you have to add click to its direct parent. or set android:clickable="false" and android:focusable="false" to its direct parent to pass listener to further parent.

Verify ImageMagick installation

Try this one-shot solution that should figure out where ImageMagick is, if you have access to it...

This found all versions on my Godaddy hosting.

Upload this file to your server and call it ImageMagick.php or something then run it. You will get all the info you need... hopefully...

Good luck.

<?
/*
// This file will run a test on your server to determine the location and versions of ImageMagick. 
//It will look in the most commonly found locations. The last two are where most popular hosts (including "Godaddy") install ImageMagick.
//
// Upload this script to your server and run it for a breakdown of where ImageMagick is.
//
*/
echo '<h2>Test for versions and locations of ImageMagick</h2>';
echo '<b>Path: </b> convert<br>';

function alist ($array) {  //This function prints a text array as an html list.
    $alist = "<ul>";
    for ($i = 0; $i < sizeof($array); $i++) {
        $alist .= "<li>$array[$i]";
    }
    $alist .= "</ul>";
    return $alist;
}

exec("convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"
echo '<br>';
echo '<b>This should test for ImageMagick version 5.x</b><br>';
echo '<b>Path: </b> /usr/bin/convert<br>';

exec("/usr/bin/convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"

echo '<br>';
echo '<b>This should test for ImageMagick version 6.x</b><br>';
echo '<b>Path: </b> /usr/local/bin/convert<br>';

exec("/usr/local/bin/convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version";

?>

Add new field to every document in a MongoDB collection

Since MongoDB version 3.2 you can use updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})