Programs & Examples On #Silverlight.fx

how to make a new line in a jupyter markdown cell

The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:

#### 1.1 My Subtitle  \

1.1 My Subtitle
    Next paragraph text.

An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).

### My Subtitle


1.1 My Subtitle

Next paragraph text.

java.lang.IllegalStateException: Fragment not attached to Activity

This error happens due to the combined effect of two factors:

  • The HTTP request, when complete, invokes either onResponse() or onError() (which work on the main thread) without knowing whether the Activity is still in the foreground or not. If the Activity is gone (the user navigated elsewhere), getActivity() returns null.
  • The Volley Response is expressed as an anonymous inner class, which implicitly holds a strong reference to the outer Activity class. This results in a classic memory leak.

To solve this problem, you should always do:

Activity activity = getActivity();
if(activity != null){

    // etc ...

}

and also, use isAdded() in the onError() method as well:

@Override
public void onError(VolleyError error) {

    Activity activity = getActivity(); 
    if(activity != null && isAdded())
        mProgressDialog.setVisibility(View.GONE);
        if (error instanceof NoConnectionError) {
           String errormsg = getResources().getString(R.string.no_internet_error_msg);
           Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
        }
    }
}

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank() will also check for null, whereas this:

String foo = getvalue("foo");
if (foo.isEmpty())

will throw a NullPointerException if foo is null.

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   
</form>

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

What Does 'zoom' do in CSS?

CSS zoom property is widely supported now > 86% of total browser population.

See: http://caniuse.com/#search=zoom

_x000D_
_x000D_
document.querySelector('#sel-jsz').style.zoom = 4;
_x000D_
#sel-001 {_x000D_
  zoom: 2.5;_x000D_
}_x000D_
#sel-002 {_x000D_
  zoom: 5;_x000D_
}_x000D_
#sel-003 {_x000D_
  zoom: 300%;_x000D_
}
_x000D_
<div id="sel-000">IMG - Default</div>_x000D_
_x000D_
<div id="sel-001">IMG - 1X</div>_x000D_
_x000D_
<div id="sel-002">IMG - 5X</div>_x000D_
_x000D_
<div id="sel-003">IMG - 3X</div>_x000D_
_x000D_
_x000D_
<div id="sel-jsz">JS Zoom - 4x</div>
_x000D_
_x000D_
_x000D_

Browser Support: caniuse

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

I think @tsatiz's answer is mostly right (programming to an interface rather than an implementation). However, by programming to the interface you won't lose any functionality. Let me explain.

If you declare your variable as a List<type> list = new ArrayList<type> you do not actually lose any functionality of the ArrayList. All you need to do is to cast your list down to an ArrayList. Here's an example:

List<String> list = new ArrayList<String>();
((ArrayList<String>) list).ensureCapacity(19);

Ultimately I think tsatiz is correct as once you cast to an ArrayList you're no longer coding to an interface. However, it's still a good practice to initially code to an interface and, if it later becomes necessary, code to an implementation if you must.

Hope that helps!

What is the simplest way to convert array to vector?

Pointers can be used like any other iterators:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + 3);
test(v)

Center Div inside another (100% width) div

The key is the margin: 0 auto; on the inner div. A proof-of-concept example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body>
    <div style="background-color: blue; width: 100%;">
        <div style="background-color: yellow; width: 940px; margin: 0 auto;">
            Test
        </div>
    </div>
</body>
</html>

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

In my case these steps solved my problem:

  1. terminating npm process (CTRL + C)
  2. deleting entire folder
  3. creating new one
  4. running npm again

MySQL the right syntax to use near '' at line 1 error

the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.

Either put it on one line or append on each line :o)

Sqlyog must be trimming white spaces on each line which explains why its working.

Example:

$qr2="INSERT INTO wp_bp_activity
      (
            user_id,
 (this stuff)component,
     (is)      `type`,
    (a)        `action`,
  (problem)  content,
             primary_link,
             item_id,....

How is Pythons glob.glob ordered?

At least in Python3 you also can do this:

import os, re, glob

path = '/home/my/path'
files = glob.glob(os.path.join(path, '*.png'))
files.sort(key=lambda x:[int(c) if c.isdigit() else c for c in re.split(r'(\d+)', x)])
for infile in files:
    print(infile)

This should lexicographically order your input array of strings (e.g. respect numbers in strings while ordering).

Duplicate / Copy records in the same MySQL table

Your approach is good but the problem is that you use "*" instead enlisting fields names. If you put all the columns names excep primary key your script will work like charm on one or many records.

INSERT INTO invoices (iv.field_name, iv.field_name,iv.field_name
) SELECT iv.field_name, iv.field_name,iv.field_name FROM invoices AS iv     
WHERE iv.ID=XXXXX

How to declare a variable in a template in Angular

Here is a directive I wrote that expands on the use of the exportAs decorator parameter, and allows you to use a dictionary as a local variable.

import { Directive, Input } from "@angular/core";
@Directive({
    selector:"[localVariables]",
    exportAs:"localVariables"
})
export class LocalVariables {
    @Input("localVariables") set localVariables( struct: any ) {
        if ( typeof struct === "object" ) {
            for( var variableName in struct ) {
                this[variableName] = struct[variableName];
            }
        }
    }
    constructor( ) {
    }
}

You can use it as follows in a template:

<div #local="localVariables" [localVariables]="{a: 1, b: 2, c: 3+2}">
   <span>a = {{local.a}}</span>
   <span>b = {{local.b}}</span>
   <span>c = {{local.c}}</span>
</div>

Of course #local can be any valid local variable name.

FileNotFoundError: [Errno 2] No such file or directory

Use the exact path.

import csv


with open('C:\\path\\address.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Can lambda functions be templated?

C++11 lambdas can't be templated as stated in other answers but decltype() seems to help when using a lambda within a templated class or function.

#include <iostream>
#include <string>

using namespace std;

template<typename T>
void boring_template_fn(T t){
    auto identity = [](decltype(t) t){ return t;};
    std::cout << identity(t) << std::endl;
}

int main(int argc, char *argv[]) {
    std::string s("My string");
    boring_template_fn(s);
    boring_template_fn(1024);
    boring_template_fn(true);
}

Prints:

My string
1024
1

I've found this technique is helps when working with templated code but realize it still means lambdas themselves can't be templated.

Concatenating variables and strings in React

you can simply do this..

 <img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>

Adding a caption to an equation in LaTeX

The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:

\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}

The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:

\[ E = m c^2 \]
\captionof{figure}{A famous equation}

This will also produce an entry for the \listoffigures, if your document has one.

To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...

How to get current route

WAY 1: Using Angular: this.router.url

import { Component } from '@angular/core';

// Step 1: import the router 
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    //Step 2: Declare the same in the constructure.
    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        // Do comparision here.....
        ///////////////////////////
        console.log(this.router.url);
    }
}

WAY 2 Window.location as we do in the Javascript, If you don't want to use the router

this.href= window.location.href;

Warning: Found conflicts between different versions of the same dependent assembly

I had the same problem with one of my projects, however, none of the above helped to solve the warning. I checked the detailed build logfile, I used AsmSpy to verify that I used the correct versions for each project in the affected solution, I double checked the actual entries in each project file - nothing helped.

Eventually it turned out that the problem was a nested dependency of one of the references I had in one project. This reference (A) in turn required a different version of (B) which was referenced directly from all other projects in my solution. Updating the reference in the referenced project solved it.

Solution A
+--Project A
   +--Reference A (version 1.1.0.0)
   +--Reference B
+--Project B
   +--Reference A (version 1.1.0.0)
   +--Reference B
   +--Reference C
+--Project C
   +--Reference X (this indirectly references Reference A, but with e.g. version 1.1.1.0)

Solution B
+--Project A
   +--Reference A (version 1.1.1.0)

I hope the above shows what I mean, took my a couple of hours to find out, so hopefully someone else will benefit as well.

How to load Spring Application Context

package com.dataload;

    public class insertCSV 
    {
        public static void main(String args[])
        {
            ApplicationContext context =
        new ClassPathXmlApplicationContext("applicationcontext.xml");


            // retrieve configured instance
            JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
            Job job = context.getBean("job", Job.class);
            JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
        }
    }

How to parse dates in multiple formats using SimpleDateFormat

Implemented the same in scala, Please help urself with converting to Java, the core logic and functions used stays the same.

import java.text.SimpleDateFormat
import org.apache.commons.lang.time.DateUtils

object MultiDataFormat {
  def main(args: Array[String]) {

val dates =Array("2015-10-31","26/12/2015","19-10-2016")

val possibleDateFormats:Array[String] = Array("yyyy-MM-dd","dd/MM/yyyy","dd-MM-yyyy")

val sdf =  new SimpleDateFormat("yyyy-MM-dd") //change it as per the requirement
  for (date<-dates) {
    val outputDate = DateUtils.parseDateStrictly(date, possibleDateFormats)
    System.out.println("inputDate ==> " + date + ", outputDate ==> " +outputDate + " " + sdf.format(outputDate) )
  }
}

}

Downloading a large file using curl

<?php
set_time_limit(0);
//This is the file where we save the    information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch); 
curl_close($ch);
fclose($fp);
?>

Where is `%p` useful with printf?

You cannot depend on %p displaying a 0x prefix. On Visual C++, it does not. Use %#p to be portable.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Enable Hibernate logging

Hibernate logging has to be also enabled in hibernate configuration.

Add lines

hibernate.show_sql=true
hibernate.format_sql=true

either to

server\default\deployers\ejb3.deployer\META-INF\jpa-deployers-jboss-beans.xml

or to application's persistence.xml in <persistence-unit><properties> tag.

Anyway hibernate logging won't include (in useful form) info on actual prepared statements' parameters.

There is an alternative way of using log4jdbc for any kind of sql logging.

The above answer assumes that you run the code that uses hibernate on JBoss, not in IDE. In this case you should configure logging also on JBoss in server\default\deploy\jboss-logging.xml, not in local IDE classpath.

Note that JBoss 6 doesn't use log4j by default. So adding log4j.properties to ear won't help. Just try to add to jboss-logging.xml:

   <logger category="org.hibernate">
     <level name="DEBUG"/>
   </logger>

Then change threshold for root logger. See SLF4J logger.debug() does not get logged in JBoss 6.

If you manage to debug hibernate queries right from IDE (without deployment), then you should have log4j.properties, log4j, slf4j-api and slf4j-log4j12 jars on classpath. See http://www.mkyong.com/hibernate/how-to-configure-log4j-in-hibernate-project/.

How to change option menu icon in the action bar?

1) Declare menu in your class.

private Menu menu;

2) In onCreateOptionsMenu do the following :

public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
    getMenuInflater().inflate(R.menu.menu_orders_screen, menu);
    return true;
}   

3) In onOptionsItemSelected, get the item and do the changes as required(icon, text, colour, background)

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_search) {
        return true;
    }
    if (id == R.id.ventor_status) {
        return true;
    }
    if (id == R.id.action_settings_online) {
        menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.history_converted));
        menu.getItem(1).setTitle("Online");
        return true;
    }
    if (id == R.id.action_settings_offline) {
        menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.cross));
        menu.getItem(1).setTitle("Offline");
        return true;
    }

    return super.onOptionsItemSelected(item);
}

Note:
If you have 3 menu items :
menu.getItem(0) = 1 item,
menu.getItem(1) = 2 iteam,
menu.getItem(2) = 3 item

Based on this make the changes accordingly as per your requirement.

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

[^\s-]

should work and so will

[^-\s]
  • [] : The char class
  • ^ : Inside the char class ^ is the negator when it appears in the beginning.
  • \s : short for a white space
  • - : a literal hyphen. A hyphen is a meta char inside a char class but not when it appears in the beginning or at the end.

Swift: print() vs println() vs NSLog()

If you're using Swift 2, now you can only use print() to write something to the output.

Apple has combined both println() and print() functions into one.

Updated to iOS 9

By default, the function terminates the line it prints by adding a line break.

print("Hello Swift")

Terminator

To print a value without a line break after it, pass an empty string as the terminator

print("Hello Swift", terminator: "")

Separator

You now can use separator to concatenate multiple items

print("Hello", "Swift", 2, separator:" ")

Both

Or you could combine using in this way

print("Hello", "Swift", 2, separator:" ", terminator:".")

python: iterate a specific range in a list

You want to use slicing.

for item in listOfStuff[1:3]:
    print item

Writing to a TextBox from another thread?

or you can do like

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        new Thread( SampleFunction ).Start();
    }

    void SampleFunction()
    {
        // Gets executed on a seperate thread and 
        // doesn't block the UI while sleeping
        for ( int i = 0; i < 5; i++ )
        {
            this.Invoke( ( MethodInvoker )delegate()
            {
                textBox1.Text += "hi";
            } );
            Thread.Sleep( 1000 );
        }
    }
}

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

Recyclerview inside ScrollView not scrolling smoothly

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent">

            <android.support.constraint.ConstraintLayout
                android:id="@+id/constraintlayout_main"
                android:layout_width="match_parent"
                android:layout_height="@dimen/layout_width_height_fortyfive"
                android:layout_marginLeft="@dimen/padding_margin_sixteen"
                android:layout_marginRight="@dimen/padding_margin_sixteen"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent">

                <TextView
                    android:id="@+id/textview_settings"
                    style="@style/textviewHeaderMain"
                    android:gravity="start"
                    android:text="@string/app_name"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent" />

            </android.support.constraint.ConstraintLayout>

            <android.support.constraint.ConstraintLayout
                android:id="@+id/constraintlayout_recyclerview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/padding_margin_zero"
                android:layout_marginTop="@dimen/padding_margin_zero"
                android:layout_marginEnd="@dimen/padding_margin_zero"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/constraintlayout_main">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recyclerview_list"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:nestedScrollingEnabled="false"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent" />

            </android.support.constraint.ConstraintLayout>

        </android.support.constraint.ConstraintLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.constraint.ConstraintLayout>

This code is working for in ConstraintLayout android

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Renaming part of a filename

You'll need to learn how to use sed http://unixhelp.ed.ac.uk/CGI/man-cgi?sed

And also to use for so you can loop through your file entries http://www.cyberciti.biz/faq/bash-for-loop/

Your command will look something like this, I don't have a term beside me so I can't check

for i in `dir` do mv $i `echo $i | sed '/orig/new/g'`

Import error: No module name urllib2

For a script working with Python 2 (tested versions 2.7.3 and 2.6.8) and Python 3 (3.2.3 and 3.3.2+) try:

#! /usr/bin/env python

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

html = urlopen("http://www.google.com/")
print(html.read())

Laravel Blade html image

In Laravel 5.x, you can also do like this .

<img class="img-responsive" src="{{URL::to('/')}}/img/stuvi-logo.png" alt=""/>

Convert an int to ASCII character

This will only work for int-digits 0-9, but your question seems to suggest that might be enough.

It works by adding the ASCII value of char '0' to the integer digit.

int i=6;
char c = '0'+i;  // now c is '6'

For example:

'0'+0 = '0'
'0'+1 = '1'
'0'+2 = '2'
'0'+3 = '3'

Edit

It is unclear what you mean, "work for alphabets"? If you want the 5th letter of the alphabet:

int i=5;
char c = 'A'-1 + i; // c is now 'E', the 5th letter.

Note that because in C/Ascii, A is considered the 0th letter of the alphabet, I do a minus-1 to compensate for the normally understood meaning of 5th letter.

Adjust as appropriate for your specific situation.
(and test-test-test! any code you write)

Work on a remote project with Eclipse via SSH

My solution is similar to the SAMBA one except using sshfs. Mount my remote server with sshfs, open my makefile project on the remote machine. Go from there.

It seems I can run a GUI frontend to mercurial this way as well.

Building my remote code is as simple as: ssh address remote_make_command

I am looking for a decent way to debug though. Possibly via gdbserver?

jQuery - Redirect with post data

Here's a simple small function that can be applied anywhere as long as you're using jQuery.

var redirect = 'http://www.website.com/page?id=23231';
$.redirectPost(redirect, {x: 'example', y: 'abc'});

// jquery extend function
$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {
            form += '<input type="hidden" name="'+key+'" value="'+value+'">';
        });
        $('<form action="'+location+'" method="POST">'+form+'</form>').appendTo('body').submit();
    }
});

Per the comments, I have expanded upon my answer:

// jquery extend function
$.extend(
{
    redirectPost: function(location, args)
    {
        var form = $('<form></form>');
        form.attr("method", "post");
        form.attr("action", location);

        $.each( args, function( key, value ) {
            var field = $('<input></input>');

            field.attr("type", "hidden");
            field.attr("name", key);
            field.attr("value", value);

            form.append(field);
        });
        $(form).appendTo('body').submit();
    }
});

How can I build for release/distribution on the Xcode 4?

I have a large app that was having problems uploading to the AppStore using the archive method you will find in XCode 4. The activity indicator kept spinning for hours whether I was trying to validate or distribute, so I created a support ticket to Apple. During that process, I found out you could right click on the .app in your Products folder inside the Project Navigator of XCode, and compress the app to submit using the Application Loader 2.5.1. (aka the old method). Only the Debug - iphoneos folder is accessible this way (for now) and once Apple responded, this is what they had to say:

I'm glad to hear that Application Loader has provided you a viable workaround. Discussing this situation internally, we're not sure that submitting the Debug build will pose too much of a problem (so long as it was signed with the App Store distribution profile, as you mentioned it was). The app will likely be slower as the debug switches are turned on and optimizations are turned off for the Debug configuration, though it will still run. App Review will ultimately determine whether or not that's ok, as I'm not sure that's something they check for. You could try reaching out directly to App Review to confirm this, if you wish. However, since App Loader is working for you, I do recommend rebuilding the app with your Release configuration and resubmitting to play it safe. To find your Release build in Xcode 4.x, control-click on the Application Archive on the Archives tab in the organizer, and choose "Show in Finder." Then, control-click on the .xcarchive file in Finder and choose "Show Package Contents." The release built .app file should be located within the /Products/Applications folder.

This was very helpful information for developers who are having problems with the archive method, and my app is now uploading successfully without any concern that it won't run to the best of it's ability.

Postgresql - select something where date = "01/01/11"

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

Android Studio - No JVM Installation found

Had the same problem after upgrading my machine from 7 to 10 had to reinstall the JDK all overgain and took me only a few seconds. Here are the steps I followed.

Go to this link http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Agree to oracle contact agreement.Then pick your windows version in my case is 64 bit after that its ..Next..Next,,once compete you can relaunch your Android studio without any problem. Hope this helps

How to solve maven 2.6 resource plugin dependency?

This issue is happening due to change of protocol from http to https for central repository. please refer following link for more details. https://support.sonatype.com/hc/en-us/articles/360041287334-Central-501-HTTPS-Required 

In order to fix the problem, copy following into your pom.ml file. This will set the repository url to use https.

<repositories>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </pluginRepository>
    </pluginRepositories>

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

How to enter a multi-line command

In most C-like languages I am deliberate about placing my braces where I think they make the code easiest to read.

PowerShell's parser recognizes when a statement clearly isn't complete, and looks to the next line. For example, imagine a cmdlet that takes an optional script block parameter:

    Get-Foo { ............ }

if the script block is very long, you might want to write:

    Get-Foo
    {
        ...............
        ...............
        ...............
    }

But this won't work: the parser will see two statements. The first is Get-Foo and the second is a script block. Instead, I write:

    Get-Foo {
        ...............
        ...............
        ...............
    }

I could use the line-continuation character (`) but that makes for hard-to-read code, and invites bugs.

Because this case requires the open brace to be on the previous line, I follow that pattern everywhere:

    if (condition) {
        .....
    }

Note that if statements require a script block in the language grammar, so the parser will look on the next line for the script block, but for consistency, I keep the open brace on the same line.

Simlarly, in the case of long pipelines, I break after the pipe character (|):

    $project.Items | 
        ? { $_.Key -eq "ProjectFile" } | 
        % { $_.Value } | 
        % { $_.EvaluatedInclude } |
        % {
            .........
        }

unable to start mongodb local server

I had the same problem were I tried to open a new instance of mongod and it said it was already running.

I checked the docs and it said to type

mongo
use admin
db.shutdownServer()

IF statement: how to leave cell blank if condition is false ("" does not work)

You could try this.

=IF(A1=1,B1,TRIM(" "))

If you put this formula in cell C1, then you could test if this cell is blank in another cells

=ISBLANK(C1)

You should see TRUE. I've tried on Microsoft Excel 2013. Hope this helps.

How to convert list of numpy arrays into single numpy array?

I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.

Timing:

|------------|----------------|-------------------|
|            | shape (10000)  |  shape (1,10000)  |
|------------|----------------|-------------------|
| np.concat  |    0.18280     |      0.17960      |
|------------|----------------|-------------------|
|  np.stack  |    0.21501     |      0.16465      |
|------------|----------------|-------------------|
| np.vstack  |    0.21501     |      0.17181      |
|------------|----------------|-------------------|
|  np.array  |    0.21656     |      0.16833      |
|------------|----------------|-------------------|

As you can see I tried 2 experiments - using np.random.rand(10000) and np.random.rand(1, 10000) And if we use 2d arrays than np.stack and np.array create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.

Code:

from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
    new_np = np.random.rand(10000)
    l.append(new_np)



start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')

start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')

start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')

start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')

PHP: Return all dates between two dates in an array

To make Mostafa's answer complete, this is definietly the simplest and most efficient way to do it:

function getDatesFromRange($start_date, $end_date, $date_format = 'Y-m-d')
   {
      $dates_array = array();
      for ($x = strtotime($start_date); $x <= strtotime($end_date); $x += 86400) {
         array_push($dates_array, date($date_format, $x));
      }

      return $dates_array;
   }

   // see the dates in the array
   print_r( getDatesFromRange('2017-02-09', '2017-02-19') );

You can even change the default output date format if you add a third parameter when you call the function, otherwise it will use the default format that's been set as 'Y-m-d'.

I hope it helps :)

Webfont Smoothing and Antialiasing in Firefox and Opera

When the color of text is dark, in Safari and Chrome, I have better result with the text-stroke css property.

-webkit-text-stroke: 0.5px #000;

How do I implement JQuery.noConflict() ?

It's typically used if you are using another library that uses $.

In order to still use the $ symbol for jQuery, I typically use:

jQuery.noConflict()(function($){
  // jQuery code here
});

Why can I not switch branches?

I got this message when updating new files from remote and index got out of whack. Tried to fix the index, but resolving via Xcode 4.5, GitHub.app (103), and GitX.app (0.7.1) failed. So, I did this:

git commit -a -m "your commit message here"

which worked in bypassing the git index.

Two blog posts that helped me understand about Git and Xcode are:

  • Ray Wenderlich on Xcode 4.5 and
  • Oliver Steele from 2008

  • EPPlus - Read Excel Table

    There is no native but what if you use what I put in this post:

    How to parse excel rows back to types using EPPlus

    If you want to point it at a table only it will need to be modified. Something like this should do it:

    public static IEnumerable<T> ConvertTableToObjects<T>(this ExcelTable table) where T : new()
    {
        //DateTime Conversion
        var convertDateTime = new Func<double, DateTime>(excelDate =>
        {
            if (excelDate < 1)
                throw new ArgumentException("Excel dates cannot be smaller than 0.");
    
            var dateOfReference = new DateTime(1900, 1, 1);
    
            if (excelDate > 60d)
                excelDate = excelDate - 2;
            else
                excelDate = excelDate - 1;
            return dateOfReference.AddDays(excelDate);
        });
    
        //Get the properties of T
        var tprops = (new T())
            .GetType()
            .GetProperties()
            .ToList();
    
        //Get the cells based on the table address
        var start = table.Address.Start;
        var end = table.Address.End;
        var cells = new List<ExcelRangeBase>();
    
        //Have to use for loops insteadof worksheet.Cells to protect against empties
        for (var r = start.Row; r <= end.Row; r++)
            for (var c = start.Column; c <= end.Column; c++)
                cells.Add(table.WorkSheet.Cells[r, c]);
    
        var groups = cells
            .GroupBy(cell => cell.Start.Row)
            .ToList();
    
        //Assume the second row represents column data types (big assumption!)
        var types = groups
            .Skip(1)
            .First()
            .Select(rcell => rcell.Value.GetType())
            .ToList();
    
        //Assume first row has the column names
        var colnames = groups
            .First()
            .Select((hcell, idx) => new { Name = hcell.Value.ToString(), index = idx })
            .Where(o => tprops.Select(p => p.Name).Contains(o.Name))
            .ToList();
    
        //Everything after the header is data
        var rowvalues = groups
            .Skip(1) //Exclude header
            .Select(cg => cg.Select(c => c.Value).ToList());
    
        //Create the collection container
        var collection = rowvalues
            .Select(row =>
            {
                var tnew = new T();
                colnames.ForEach(colname =>
                {
                    //This is the real wrinkle to using reflection - Excel stores all numbers as double including int
                    var val = row[colname.index];
                    var type = types[colname.index];
                    var prop = tprops.First(p => p.Name == colname.Name);
    
                    //If it is numeric it is a double since that is how excel stores all numbers
                    if (type == typeof(double))
                    {
                        if (!string.IsNullOrWhiteSpace(val?.ToString()))
                        {
                            //Unbox it
                            var unboxedVal = (double)val;
    
                            //FAR FROM A COMPLETE LIST!!!
                            if (prop.PropertyType == typeof(Int32))
                                prop.SetValue(tnew, (int)unboxedVal);
                            else if (prop.PropertyType == typeof(double))
                                prop.SetValue(tnew, unboxedVal);
                            else if (prop.PropertyType == typeof(DateTime))
                                prop.SetValue(tnew, convertDateTime(unboxedVal));
                            else
                                throw new NotImplementedException(String.Format("Type '{0}' not implemented yet!", prop.PropertyType.Name));
                        }
                    }
                    else
                    {
                        //Its a string
                        prop.SetValue(tnew, val);
                    }
                });
    
                return tnew;
            });
    
    
        //Send it back
        return collection;
    }
    

    Here is a test method:

    [TestMethod]
    public void Table_To_Object_Test()
    {
        //Create a test file
        var fi = new FileInfo(@"c:\temp\Table_To_Object.xlsx");
    
        using (var package = new ExcelPackage(fi))
        {
            var workbook = package.Workbook;
            var worksheet = workbook.Worksheets.First();
            var ThatList = worksheet.Tables.First().ConvertTableToObjects<ExcelData>();
            foreach (var data in ThatList)
            {
                Console.WriteLine(data.Id + data.Name + data.Gender);
            }
    
            package.Save();
        }
    }
    

    Gave this in the console:

    1JohnMale
    2MariaFemale
    3DanielUnknown
    

    Just be careful if you Id field is an number or string in excel since the class is expecting a string.

    What Are Some Good .NET Profilers?

    I've been testing Telerik's JustTrace recently and although it is well away from a finished product the guys are going in the right direction.

    Await operator can only be used within an Async method

    You can only use await in an async method, and Main cannot be async.

    You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

    If you want a good intro, see my async/await intro post.

    Linking to a specific part of a web page

    First off target refers to the BlockID found in either HTML code or chromes developer tools that you are trying to link to. Each code is different and you will need to do some digging to find the ID you are trying to reference. It should look something like div class="page-container drawer-page-content" id"PageContainer"Note that this is the format for the whole referenced section, not an individual text or image. To do that you would need to find the same piece of code but relating to your target block. For example dv id="your-block-id" Anyways I was just reading over this thread and an idea came to my mind, if you are a Shopify user and want to do this it is pretty much the same thing as stated. But instead of

    > http://url.to.site/index.html#target
    

    You would put

    > http://storedomain.com/target
    

    For example, I am setting up a disclaimer page with links leading to a newsletter signup and shopping blocks on my home page so I insert https://mystore-classifier.com/#shopify-section-1528945200235 for my hyperlink. Please note that the -classifier is for my internal use and doesn't apply to you. This is just so I can keep track of my stores. If you want to link to something other than your homepage you would put

    > http://mystore-classifier.com/pagename/#BlockID
    

    I hope someone found this useful, if there is something wrong with my explanation please let me know as I am not an HTML programmer my language is C#!

    Bad File Descriptor with Linux Socket write() Bad File Descriptor C

    The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

    So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

    It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

    Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

    How to clear all data in a listBox?

    Try this:

     private void cleanlistbox(object sender, EventArgs e)
      {
         listBox1.DataSource = null;
         listBox1.Items.Clear();
      }
    

    What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

    Scope Identity: Identity of last record added within the stored procedure being executed.

    @@Identity: Identity of last record added within the query batch, or as a result of the query e.g. a procedure that performs an insert, the then fires a trigger that then inserts a record will return the identity of the inserted record from the trigger.

    IdentCurrent: The last identity allocated for the table.

    Find empty or NaN entry in Pandas Dataframe

    np.where(pd.isnull(df)) returns the row and column indices where the value is NaN:

    In [152]: import numpy as np
    In [153]: import pandas as pd
    In [154]: np.where(pd.isnull(df))
    Out[154]: (array([2, 5, 6, 6, 7, 7]), array([7, 7, 6, 7, 6, 7]))
    
    In [155]: df.iloc[2,7]
    Out[155]: nan
    
    In [160]: [df.iloc[i,j] for i,j in zip(*np.where(pd.isnull(df)))]
    Out[160]: [nan, nan, nan, nan, nan, nan]
    

    Finding values which are empty strings could be done with applymap:

    In [182]: np.where(df.applymap(lambda x: x == ''))
    Out[182]: (array([5]), array([7]))
    

    Note that using applymap requires calling a Python function once for each cell of the DataFrame. That could be slow for a large DataFrame, so it would be better if you could arrange for all the blank cells to contain NaN instead so you could use pd.isnull.

    How to pass command line arguments to a rake task

    Another commonly used option is to pass environment variables. In your code you read them via ENV['VAR'], and can pass them right before the rake command, like

    $ VAR=foo rake mytask
    

    Setup a Git server with msysgit on Windows

    Bonobo Git Server for Windows

    From the Bonobo Git Server web page:

    Bonobo Git Server for Windows is a web application you can install on your IIS and easily manage and connect to your git repositories.

    Bonobo Git Server is a open-source project and you can find the source on github.

    Features:

    • Secure and anonymous access to your git repositories
    • User friendly web interface for management
    • User and team based repository access management
    • Repository file browser
    • Commit browser
    • Localization

    Brad Kingsley has a nice tutorial for installing and configuring Bonobo Git Server.

    GitStack

    Git Stack is another option. Here is a description from their web site:

    GitStack is a software that lets you setup your own private Git server for Windows. This means that you create a leading edge versioning system without any prior Git knowledge. GitStack also makes it super easy to secure and keep your server up to date. GitStack is built on the top of the genuine Git for Windows and is compatible with any other Git clients. GitStack is completely free for small teams1.

    1 the basic edition is free for up to 2 users

    How to find top three highest salary in emp table in oracle?

    select top(3) min(Name),TotalSalary,ROW_NUMBER() OVER (Order by TotalSalary desc) AS RowNumber FROM tbl_EmployeeProfile group by TotalSalary

    select the TOP N rows from a table

    From SQL Server 2012 you can use a native pagination in order to have semplicity and best performance:

    https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15#using-offset-and-fetch-to-limit-the-rows-returned

    Your query become:

    SELECT * FROM Reflow  
    WHERE ReflowProcessID = somenumber
    ORDER BY ID DESC;
    OFFSET 20 ROWS  
    FETCH NEXT 20 ROWS ONLY;  
    

    rbenv not changing ruby version

    I fixed this by adding the following to my ~/.bash_profile:

    #PATH for rbenv
    export PATH="$HOME/.rbenv/shims:$PATH"
    

    This is what is documented at https://github.com/sstephenson/rbenv.

    From what I can tell there isn't ~/.rbenv/bin directory, which was mentioned in the post by @rodowi.

    How do I generate a SALT in Java for Salted-Hash?

    Inspired from this post and that post, I use this code to generate and verify hashed salted passwords. It only uses JDK provided classes, no external dependency.

    The process is:

    • you create a salt with getNextSalt
    • you ask the user his password and use the hash method to generate a salted and hashed password. The method returns a byte[] which you can save as is in a database with the salt
    • to authenticate a user, you ask his password, retrieve the salt and hashed password from the database and use the isExpectedPassword method to check that the details match
    /**
     * A utility class to hash passwords and check passwords vs hashed values. It uses a combination of hashing and unique
     * salt. The algorithm used is PBKDF2WithHmacSHA1 which, although not the best for hashing password (vs. bcrypt) is
     * still considered robust and <a href="https://security.stackexchange.com/a/6415/12614"> recommended by NIST </a>.
     * The hashed value has 256 bits.
     */
    public class Passwords {
    
      private static final Random RANDOM = new SecureRandom();
      private static final int ITERATIONS = 10000;
      private static final int KEY_LENGTH = 256;
    
      /**
       * static utility class
       */
      private Passwords() { }
    
      /**
       * Returns a random salt to be used to hash a password.
       *
       * @return a 16 bytes random salt
       */
      public static byte[] getNextSalt() {
        byte[] salt = new byte[16];
        RANDOM.nextBytes(salt);
        return salt;
      }
    
      /**
       * Returns a salted and hashed password using the provided hash.<br>
       * Note - side effect: the password is destroyed (the char[] is filled with zeros)
       *
       * @param password the password to be hashed
       * @param salt     a 16 bytes salt, ideally obtained with the getNextSalt method
       *
       * @return the hashed password with a pinch of salt
       */
      public static byte[] hash(char[] password, byte[] salt) {
        PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
        Arrays.fill(password, Character.MIN_VALUE);
        try {
          SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
          return skf.generateSecret(spec).getEncoded();
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
          throw new AssertionError("Error while hashing a password: " + e.getMessage(), e);
        } finally {
          spec.clearPassword();
        }
      }
    
      /**
       * Returns true if the given password and salt match the hashed value, false otherwise.<br>
       * Note - side effect: the password is destroyed (the char[] is filled with zeros)
       *
       * @param password     the password to check
       * @param salt         the salt used to hash the password
       * @param expectedHash the expected hashed value of the password
       *
       * @return true if the given password and salt match the hashed value, false otherwise
       */
      public static boolean isExpectedPassword(char[] password, byte[] salt, byte[] expectedHash) {
        byte[] pwdHash = hash(password, salt);
        Arrays.fill(password, Character.MIN_VALUE);
        if (pwdHash.length != expectedHash.length) return false;
        for (int i = 0; i < pwdHash.length; i++) {
          if (pwdHash[i] != expectedHash[i]) return false;
        }
        return true;
      }
    
      /**
       * Generates a random password of a given length, using letters and digits.
       *
       * @param length the length of the password
       *
       * @return a random password
       */
      public static String generateRandomPassword(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
          int c = RANDOM.nextInt(62);
          if (c <= 9) {
            sb.append(String.valueOf(c));
          } else if (c < 36) {
            sb.append((char) ('a' + c - 10));
          } else {
            sb.append((char) ('A' + c - 36));
          }
        }
        return sb.toString();
      }
    }
    

    Extract the first (or last) n characters of a string

    If you are coming from Microsoft Excel, the following functions will be similar to LEFT(), RIGHT(), and MID() functions.

    
    # This counts from the left and then extract n characters
    
    str_left <- function(string, n) {
      substr(string, 1, n)
    }
    
    
    
    # This counts from the right and then extract n characters
    
    str_right <- function(string, n) {
      substr(string, nchar(string) - (n - 1), nchar(string))
    }
    
    
    # This extract characters from the middle
    
    str_mid <- function(string, from = 2, to = 5){
      
      substr(string, from, to)
      }
    
    

    Examples:

    x <- "some text in a string"
    str_left(x, 4)
    [1] "some"
    
    str_right(x, 6)
    [1] "string"
    
    str_mid(x, 6, 9)
    [1] "text"
    
    

    Java : Convert formatted xml file to one line string

    //filename is filepath string
    BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
    String line;
    StringBuilder sb = new StringBuilder();
    
    while((line=br.readLine())!= null){
        sb.append(line.trim());
    }
    

    using StringBuilder is more efficient then concat http://kaioa.com/node/59

    How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

    If it helps anyone, I just appended the contents of the below output file to the existing org.apache.catalina.startup.TldConfig.jarsToSkip= entry.

    Note that /var/log/tomcat7/catalina.out is the location of your tomcat log.

    egrep "No TLD files were found in \[file:[^\]+\]" /var/log/tomcat7/catalina.out -o | egrep "[^]/]+.jar" -o | sort | uniq | sed -e 's/.jar/.jar,\\/g' > skips.txt
    

    Hope that helps.

    How can I get list of values from dict?

    Yes it's the exact same thing in Python 2:

    d.values()
    

    In Python 3 (where dict.values returns a view of the dictionary’s values instead):

    list(d.values())
    

    Shortcut for changing font size

    In the Macros explorer under samples/accessibility there is an IncreaseTextEditorFontSize and a DecreaseTextEditorFontSize. Bind those to some keyboard shortcuts.

    Xcode 10: A valid provisioning profile for this executable was not found

    It seems that Apple fixed this bug in Xcode 10.2 beta 2 Release.

    https://developer.apple.com/documentation/xcode_release_notes/xcode_10_2_beta_2_release_notes

    Signing and Distribution Resolved Issues

    When you’re building an archive of a macOS app and using a Developer ID signing certificate, Xcode includes a secure timestamp in the archive’s signature. As a result, you can now submit an archived app to Apple’s notary service with xcrun altool without first needing to re-sign it with a timestamp. (44952627)

    When you’re building an archive of a macOS app, Xcode no longer injects the com.apple.security.get-task-allow entitlement into the app’s signature. As a result, you can now submit an archived app to Apple’s notary service using xcrun altool without first needing to strip this entitlement. (44952574)

    Fixed an issue that caused the distribution workflow to report inaccurate or missing information about the signing certificate, provisioning profile, and entitlements used when exporting or uploading an app. (45761196)

    Fixed an issue where thinned .ipa files weren’t being signed when exported from the Organizer. (45761101)

    Xcode 10.2 beta 2 Release can be downloaded here: https://developer.apple.com/download/

    Background position, margin-top?

    #div-name
    
    {
    
      background-image: url('../images/background-art-main.jpg');
      background-position: top right 50px;
      background-repeat: no-repeat;
    }
    

    <div> cannot appear as a descendant of <p>

    If this error occurs while using Material UI <Typography> https://material-ui.com/api/typography/, then you can easily change the <p> to a <span> by changing the value of the component attribute of the <Typography> element :

    <Typography component={'span'} variant={'body2'}>
    

    According to the typography docs:

    component : The component used for the root node. Either a string to use a DOM element or a component. By default, it maps the variant to a good default headline component.

    So Typography is picking <p> as a sensible default, which you can change. May come with side effects ... worked for me.

    Overlapping elements in CSS

    You can use relative positioning to overlap your elements. However, the space they would normally occupy will still be reserved for the element:

    <div style="background-color:#f00;width:200px;height:100px;">
        DEFAULT POSITIONED
    </div>
    <div style="background-color:#0f0;width:200px;height:100px;position:relative;top:-50px;left:50px;">
        RELATIVE POSITIONED
    </div>
    <div style="background-color:#00f;width:200px;height:100px;">
        DEFAULT POSITIONED
    </div>
    

    In the example above, there will be a block of white space between the two 'DEFAULT POSITIONED' elements. This is caused, because the 'RELATIVE POSITIONED' element still has it's space reserved.

    If you use absolute positioning, your elements will not have any space reserved, so your element will actually overlap, without breaking your document:

    <div style="background-color:#f00;width:200px;height:100px;">
        DEFAULT POSITIONED
    </div>
    <div style="background-color:#0f0;width:200px;height:100px;position:absolute;top:50px;left:50px;">
        ABSOLUTE POSITIONED
    </div>
    <div style="background-color:#00f;width:200px;height:100px;">
        DEFAULT POSITIONED
    </div>
    

    Finally, you can control which elements are on top of the others by using z-index:

    <div style="z-index:10;background-color:#f00;width:200px;height:100px;">
        DEFAULT POSITIONED
    </div>
    <div style="z-index:5;background-color:#0f0;width:200px;height:100px;position:absolute;top:50px;left:50px;">
        ABSOLUTE POSITIONED
    </div>
    <div style="z-index:0;background-color:#00f;width:200px;height:100px;">
        DEFAULT POSITIONED
    </div>
    

    jQuery hyperlinks - href value?

    Wonder why nobody said it here earlier: to prevent <a href="#"> from scrolling document position to the top, simply use <a href="#/"> instead. That's mere HTML, no JQuery needed. Using event.preventDefault(); is just too much!

    Utilizing multi core for tar+gzip/bzip compression/decompression

    You can use pigz instead of gzip, which does gzip compression on multiple cores. Instead of using the -z option, you would pipe it through pigz:

    tar cf - paths-to-archive | pigz > archive.tar.gz
    

    By default, pigz uses the number of available cores, or eight if it could not query that. You can ask for more with -p n, e.g. -p 32. pigz has the same options as gzip, so you can request better compression with -9. E.g.

    tar cf - paths-to-archive | pigz -9 -p 32 > archive.tar.gz
    

    Export DataTable to Excel with Open Xml SDK in c#

    eburgos, I've modified your code slightly because when you have multiple datatables in your dataset it was just overwriting them in the spreadsheet so you were only left with one sheet in the workbook. I basically just moved the part where the workbook is created out of the loop. Here is the updated code.

    private void ExportDSToExcel(DataSet ds, string destination)
    {
        using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
        {
            var workbookPart = workbook.AddWorkbookPart();
            workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
            workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();
    
            uint sheetId = 1;
    
            foreach (DataTable table in ds.Tables)
            {
                var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
                var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
                sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);                
    
                DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
                string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
    
                if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
                {
                    sheetId =
                        sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                }
    
                DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
                sheets.Append(sheet);
    
                DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
    
                List<String> columns = new List<string>();
                foreach (DataColumn column in table.Columns)
                {
                    columns.Add(column.ColumnName);
    
                    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                    cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                    headerRow.AppendChild(cell);
                }
    
                sheetData.AppendChild(headerRow);
    
                foreach (DataRow dsrow in table.Rows)
                {
                    DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                    foreach (String col in columns)
                    {
                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                        newRow.AppendChild(cell);
                    }
    
                    sheetData.AppendChild(newRow);
                }
            }
        }
    }
    

    Comparing two byte arrays in .NET

    If you are looking for a very fast byte array equality comparer, I suggest you take a look at this STSdb Labs article: Byte array equality comparer. It features some of the fastest implementations for byte[] array equality comparing, which are presented, performance tested and summarized.

    You can also focus on these implementations:

    BigEndianByteArrayComparer - fast byte[] array comparer from left to right (BigEndian) BigEndianByteArrayEqualityComparer - - fast byte[] equality comparer from left to right (BigEndian) LittleEndianByteArrayComparer - fast byte[] array comparer from right to left (LittleEndian) LittleEndianByteArrayEqualityComparer - fast byte[] equality comparer from right to left (LittleEndian)

    Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

    An alternative that always exists for learning purpose is to build your custom collector through Collector.of() though toMap() JDK collector here is succinct (+1 here) .

    Map<String,Integer> newMap = givenMap.
                    entrySet().
                    stream().collect(Collector.of
                   ( ()-> new HashMap<String,Integer>(),
                           (mutableMap,entryItem)-> mutableMap.put(entryItem.getKey(),Integer.parseInt(entryItem.getValue())),
                           (map1,map2)->{ map1.putAll(map2); return map1;}
                   ));
    

    How To Upload Files on GitHub

    I didn't find the above answers sufficiently explicit, and it took me some time to figure it out for myself. The most useful page I found was: http://www.lockergnome.com/web/2011/12/13/how-to-use-github-to-contribute-to-open-source-projects/

    I'm on a Unix box, using the command line. I expect this will all work on a Mac command line. (Mac or Window GUI looks to be available at desktop.github.com but I haven't tested this, and don't know how transferable this will be to the GUI.)

    Step 1: Create a Github account Step 2: Create a new repository, typically with a README and LICENCE file created in the process. Step 3: Install "git" software. (Links in answers above and online help at github should suffice to do these steps, so I don't provide detailed instructions.) Step 4: Tell git who you are:

    git config --global user.name "<NAME>"
    git config --global user.email "<email>"
    

    I think the e-mail must be one of the addresses you have associated with the github account. I used the same name as I used in github, but I think (not sure) that this is not required. Optionally you can add caching of credentials, so you don't need to type in your github account name and password so often. https://help.github.com/articles/caching-your-github-password-in-git/

    Create and navigate to some top level working directory:

    mkdir <working>
    cd <working>
    

    Import the nearly empty repository from github:

    git clone https://github.com/<user>/<repository>
    

    This might ask for credentials (if github repository is not 'public'.) Move to directory, and see what we've done:

    cd <repository>
    ls -a
    git remote -v
    

    (The 'ls' and 'git remote' commands are optional, they just show you stuff) Copy the 10000 files and millions of lines of code that you want to put in the repository:

    cp -R <path>/src .
    git status -s
    

    (assuming everything you want is under a directory named "src".) (The second command again is optional and just shows you stuff)

    Add all the files you just copied to git, and optionally admire the the results:

    git add src
    git status -s
    

    Commit all the changes:

    git commit -m "<commit comment>"
    

    Push the changes

    git push origin master
    

    "Origin" is an alias for your github repository which was automatically set up by the "git clone" command. "master" is the branch you are pushing to. Go look at github in your browser and you should see all the files have been added.

    Optionally remove the directory you did all this in, to reclaim disk space:

    cd ..
    rm -r <working>
    

    How to Lock/Unlock screen programmatically?

    Use Activity.getWindow() to get the window of your activity; use Window.addFlags() to add whichever of the following flags in WindowManager.LayoutParams that you desire:

    How to read lines of a file in Ruby

    how about gets ?

    myFile=File.open("paths_to_file","r")
    while(line=myFile.gets)
     //do stuff with line
    end
    

    PivotTable to show values, not sum of values

    I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.

    Assuming your data is in ColumnA:C and has column labels in Row 1, also that Month is formatted mmm(this last for ease of sorting):

    1. Sort the data by Name then Month
    2. Enter in D2 =IF(AND(A2=A1,C2=C1),D1+1,1) (One way to deal with what is the tricky issue of multiple entries for the same person for the same month).
    3. Create a pivot table from A1:D(last occupied row no.)
    4. Say insert in F1.
    5. Layout as in screenshot.

    SO12803305 example

    I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.

    1. Copy pivot table and Paste Special/Values to, say, L1.
    2. Delete top row of copied range with shift cells up.
    3. Insert new cell at L1 and shift down.
    4. Key 'Name' into L1.
    5. Filter copied range and for ColumnL, select Row Labels and numeric values.
    6. Delete contents of L2:L(last selected cell)
    7. Delete blank rows in copied range with shift cells up (may best via adding a column that counts all 12 months). Hopefully result should be as highlighted in yellow.

    Happy to explain further/try again (I've not really tested this) if does not suit.

    EDIT (To avoid second block of steps above and facilitate updating for source data changes)

    .0. Before first step 2. add a blank row at the very top and move A2:D2 up.
    .2. Adjust cell references accordingly (in D3 =IF(AND(A3=A2,C3=C2),D2+1,1).
    .3. Create pivot table from A:D

    .6. Overwrite Row Labels with Name.
    .7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
    .8. Hide Row1, ColumnG and rows and columns that show (blank).

    additional example

    Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).

    Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank) into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.

    How can I mark a foreign key constraint using Hibernate annotations?

    There are many answers and all are correct as well. But unfortunately none of them have a clear explanation.

    The following works for a non-primary key mapping as well.

    Let's say we have parent table A with column 1 and another table, B, with column 2 which references column 1:

    @ManyToOne
    @JoinColumn(name = "TableBColumn", referencedColumnName = "TableAColumn")
    private TableA session_UserName;
    

    Enter image description here

    @ManyToOne
    @JoinColumn(name = "bok_aut_id", referencedColumnName = "aut_id")
    private Author bok_aut_id;
    

    Why should I use core.autocrlf=true in Git?

    I am a .NET developer, and have used Git and Visual Studio for years. My strong recommendation is set line endings to true. And do it as early as you can in the lifetime of your Repository.

    That being said, I HATE that Git changes my line endings. A source control should only save and retrieve the work I do, it should NOT modify it. Ever. But it does.

    What will happen if you don't have every developer set to true, is ONE developer eventually will set to true. This will begin to change the line endings of all of your files to LF in your repo. And when users set to false check those out, Visual Studio will warn you, and ask you to change them. You will have 2 things happen very quickly. One, you will get more and more of those warnings, the bigger your team the more you get. The second, and worse thing, is that it will show that every line of every modified file was changed(because the line endings of every line will be changed by the true guy). Eventually you won't be able to track changes in your repo reliably anymore. It is MUCH easier and cleaner to make everyone keep to true, than to try to keep everyone false. As horrible as it is to live with the fact that your trusted source control is doing something it should not. Ever.

    Make: how to continue after a command fails?

    make -k (or --keep-going on gnumake) will do what you are asking for, I think.

    You really ought to find the del or rm line that is failing and add a -f to it to keep that error from happening to others though.

    How to change colour of blue highlight on select box dropdown

    i just found this site that give a cool themes for the select box http://gregfranko.com/jquery.selectBoxIt.js/

    and you can try this themes if your problem with the overall look blue - yellow - grey

    Get all child views inside LinearLayout at once

    use this

        final int childCount = mainL.getChildCount();
        for (int i = 0; i < childCount; i++) {
              View element = mainL.getChildAt(i);
    
            // EditText
            if (element instanceof EditText) {
                EditText editText = (EditText)element;
                System.out.println("ELEMENTS EditText getId=>"+editText.getId()+ " getTag=>"+element.getTag()+
                " getText=>"+editText.getText());
            }
    
            // CheckBox
            if (element instanceof CheckBox) {
                CheckBox checkBox = (CheckBox)element;
                System.out.println("ELEMENTS CheckBox getId=>"+checkBox.getId()+ " getTag=>"+checkBox.getTag()+
                " getText=>"+checkBox.getText()+" isChecked=>"+checkBox.isChecked());
            }
    
            // DatePicker
            if (element instanceof DatePicker) {
                DatePicker datePicker = (DatePicker)element;
                System.out.println("ELEMENTS DatePicker getId=>"+datePicker.getId()+ " getTag=>"+datePicker.getTag()+
                " getDayOfMonth=>"+datePicker.getDayOfMonth());
            }
    
            // Spinner
            if (element instanceof Spinner) {
                Spinner spinner = (Spinner)element;
                System.out.println("ELEMENTS Spinner getId=>"+spinner.getId()+ " getTag=>"+spinner.getTag()+
                " getSelectedItemId=>"+spinner.getSelectedItemId()+
                " getSelectedItemPosition=>"+spinner.getSelectedItemPosition()+
                " getTag(key)=>"+spinner.getTag(spinner.getSelectedItemPosition()));
            }
    
        }
    

    Escaping single quote in PHP when inserting into MySQL

    You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"

    where $val is the data which is troubling you.

    wamp server mysql user id and password

    Use http://localhost/sqlbuddy --> users interface.

    You can find it at the localhost main page at Your Aliases section.

    ant build.xml file doesn't exist

    There may be two situations.

    1. No build.xml is present in the current directory
    2. Your ant configuration file has diffrent name.

    Please see and confim the same. In the case one you have to find where your build file is located and in the case 2, You will have to run command ant -f <your build file name>.

    How do you decompile a swf file

    Get the Sothink SWF decompiler. Not free, but worth it. Recently used it to decompile an SWF that I had lost the fla for, and I could completely round-trip swf-fla and back!
    link text

    How To Get Selected Value From UIPickerView

    You can access the selected row for a given component using the following method:

    - (NSInteger)selectedRowInComponent:(NSInteger)component
    

    Otherwise, implementing the delegate function is the only other option.

    JAX-WS client : what's the correct path to access the local WSDL?

    Had the exact same problem that is described herein. No matter what I did, following the above examples, to change the location of my WSDL file (in our case from a web server), it was still referencing the original location embedded within the source tree of the server process.

    After MANY hours trying to debug this, I noticed that the Exception was always being thrown from the exact same line (in my case 41). Finally this morning, I decided to just send my source client code to our trade partner so they can at least understand how the code looks, but perhaps build their own. To my shock and horror I found a bunch of class files mixed in with my .java files within my client source tree. How bizarre!! I suspect these were a byproduct of the JAX-WS client builder tool.

    Once I zapped those silly .class files and performed a complete clean and rebuild of the client code, everything works perfectly!! Redonculous!!

    YMMV, Andrew

    Does Spring @Transactional attribute work on a private method?

    The answer is no. Please see Spring Reference: Using @Transactional :

    The @Transactional annotation may be placed before an interface definition, a method on an interface, a class definition, or a public method on a class

    android image button

    just use a Button with android:drawableRight properties like this:

    <Button android:id="@+id/btnNovaCompra" android:layout_width="wrap_content"
            android:text="@string/btn_novaCompra"
            android:gravity="center"
            android:drawableRight="@drawable/shoppingcart"
            android:layout_height="wrap_content"/>
    

    Return char[]/string from a function

    char* charP = createStr();
    

    Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.

    How to convert/parse from String to char in java?

    If the string is 1 character long, just take that character. If the string is not 1 character long, it cannot be parsed into a character.

    How to force composer to reinstall a library?

    For some reason no one suggested the obvious and the most straight forward way to force re-install:

    > composer remove vendor-name/package-name && composer vendor-name/package-name
    

    How do I combine two dataframes?

    Thought to add this here in case someone finds it useful. @ostrokach already mentioned how you can merge the data frames across rows which is

    df_row_merged = pd.concat([df_a, df_b], ignore_index=True)
    

    To merge across columns, you can use the following syntax:

    df_col_merged = pd.concat([df_a, df_b], axis=1)
    

    How to set a Javascript object values dynamically?

    You could also create something that would be similar to a value object (vo);

    SomeModelClassNameVO.js;

    function SomeModelClassNameVO(name,id) {
        this.name = name;
        this.id = id;
    }
    

    Than you can just do;

       var someModelClassNameVO = new someModelClassNameVO('name',1);
       console.log(someModelClassNameVO.name);
    

    What size should apple-touch-icon.png be for iPad and iPhone?

    The icon on Apple's site is 152x152 pixels.
    http://www.apple.com/apple-touch-icon.png

    Hope that answers your question.

    Compare cell contents against string in Excel

    If a case-insensitive comparison is acceptable, just use =:

    =IF(A1="ENG",1,0)
    

    How to create a timeline with LaTeX?

    If you are looking for UML sequence diagrams, you might be interested in pkf-umlsd, which is based on TiKZ. Nice demos can be found here.

    How can I select item with class within a DIV?

    You'll do it the same way you would apply a css selector. For instanse you can do

    $("#mydiv > .myclass")
    

    or

    $("#mydiv .myclass")
    

    The last one will match every myclass inside myDiv, including myclass inside myclass.

    How to run ~/.bash_profile in mac terminal

    On MacOS: add source ~/.bash_profile to the end of ~/.zshrc. Then this profile will be in effect when you open zsh.

    Command to list all files in a folder as well as sub-folders in windows

    Following commands we can use for Linux or Mac. For Windows we can use below on git bash.

    List all files, first level folders, and their contents

    ls * -r
    

    List all first-level subdirectories and files

    file */*
    

    Save file list to text

    file */* *>> ../files.txt
    file */* -r *>> ../files-recursive.txt
    

    Get everything

    find . -type f
    

    Save everything to file

    find . -type f > ../files-all.txt
    

    Programmatically get height of navigation bar

    I have used:

    let originY: CGFloat = self.navigationController!.navigationBar.frame.maxY
    

    Working great if you want to get the navigation bar height AND its Y origin.

    Windows batch command(s) to read first line from text file

    To cicle a file (file1.txt, file1[1].txt, file1[2].txt, etc.):

    START/WAIT C:\LAERCIO\DELPHI\CICLADOR\dprCiclador.exe C:\LAERCIUM\Ciclavel.txt
    
    rem set/p ciclo=< C:\LAERCIUM\Ciclavel.txt:
    set/p ciclo=< C:\LAERCIUM\Ciclavel.txt
    
    rem echo %ciclo%:
    echo %ciclo%
    

    And it's running.

    How to Import .bson file format on mongodb

    I have used this:

    mongorestore -d databasename -c file.bson fullpath/file.bson
    

    1.copy the file path and file name from properties (try to put all bson files in different folder), 2.use this again and again with changing file name only.

    How to set Spring profile from system variable?

    My solution is to set the environment variable as spring.profiles.active=development. So that all applications running in that machine will refer the variable and start the application. The order in which spring loads a properties as follows

    application.properties
    system properties
    environment variable
    

    What happens if you mount to a non-empty mount point with fuse?

    Just add -o nonempty in command line, like this:

    s3fs -o nonempty  <bucket-name> </mount/point/>
    

    How to convert a file to utf-8 in Python?

    You can use the codecs module, like this:

    import codecs
    BLOCKSIZE = 1048576 # or some other, desired size in bytes
    with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
        with codecs.open(targetFileName, "w", "utf-8") as targetFile:
            while True:
                contents = sourceFile.read(BLOCKSIZE)
                if not contents:
                    break
                targetFile.write(contents)
    

    EDIT: added BLOCKSIZE parameter to control file chunk size.

    Excel VBA Run-time error '13' Type mismatch

    Diogo

    Justin has given you some very fine tips :)

    You will also get that error if the cell where you are performing the calculation has an error resulting from a formula.

    For example if Cell A1 has #DIV/0! error then you will get "Excel VBA Run-time error '13' Type mismatch" when performing this code

    Sheets("Sheet1").Range("A1").Value - 1
    

    I have made some slight changes to your code. Could you please test it for me? Copy the code with the line numbers as I have deliberately put them there.

    Option Explicit
    
    Sub Sample()
      Dim ws As Worksheet
      Dim x As Integer, i As Integer, a As Integer, y As Integer
      Dim name As String
      Dim lastRow As Long
    10        On Error GoTo Whoa
    
    20        Application.ScreenUpdating = False
    
    30        name = InputBox("Please insert the name of the sheet")
    
    40        If Len(Trim(name)) = 0 Then Exit Sub
    
    50        Set ws = Sheets(name)
    
    60        With ws
    70            If Not IsError(.Range("BE4").Value) Then
    80                x = Val(.Range("BE4").Value)
    90            Else
    100               MsgBox "Please check the value of cell BE4. It seems to have an error"
    110               GoTo LetsContinue
    120           End If
    
    130           .Range("BF4").Value = x
    
    140           lastRow = .Range("BE" & Rows.Count).End(xlUp).Row
    
    150           For i = 5 To lastRow
    160               If IsError(.Range("BE" & i)) Then
    170                   MsgBox "Please check the value of cell BE" & i & ". It seems to have an error"
    180                   GoTo LetsContinue
    190               End If
    
    200               a = 0: y = Val(.Range("BE" & i))
    210               If y <> x Then
    220                   If y <> 0 Then
    230                       If y = 3 Then
    240                           a = x
    250                           .Range("BF" & i) = Val(.Range("BE" & i)) - x
    
    260                           x = Val(.Range("BE" & i)) - x
    270                       End If
    280                       .Range("BF" & i) = Val(.Range("BE" & i)) - a
    290                       x = Val(.Range("BE" & i)) - a
    300                   Else
    310                       .Range("BF" & i).ClearContents
    320                   End If
    330               Else
    340                   .Range("BF" & i).ClearContents
    350               End If
    360           Next i
    370       End With
    
    LetsContinue:
    380       Application.ScreenUpdating = True
    390       Exit Sub
    Whoa:
    400       MsgBox "Error Description :" & Err.Description & vbNewLine & _
             "Error at line     : " & Erl
    410       Resume LetsContinue
    End Sub
    

    Storing and retrieving datatable from session

    this is just as a side note, but generally what you want to do is keep size on the Session and ViewState small. I generally just store IDs and small amounts of packets in Session and ViewState.

    for instance if you want to pass large chunks of data from one page to another, you can store an ID in the querystring and use that ID to either get data from a database or a file.

    PS: but like I said, this might be totally unrelated to your query :)

    Duplicate and rename Xcode project & associated folders

    I'm using simple BASH script for renaming.

    Usage: ./rename.sh oldName newName

    #!/bin/sh
    
    OLDNAME=$1
    NEWNAME=$2
    
    export LC_CTYPE=C 
    export LANG=C
    find . -type f ! -path ".*/.*" -exec sed -i '' -e "s/${OLDNAME}/${NEWNAME}/g" {} +
    
    mv "${OLDNAME}.xcodeproj" "${NEWNAME}.xcodeproj"
    mv "${OLDNAME}" "${NEWNAME}"
    

    Notes:

    1. This script will ignore all files like .git and .DS_Store
    2. Will not work if old name/new name contains spaces
    3. May not work if you use pods (not tested)
    4. Scheme name will not be changed (anyway project runs and compiles normally)

    How do I kill all the processes in Mysql "show processlist"?

    I used the command flush tables to kill all inactive connections which where actually the mass problem.

    Instantiate and Present a viewController in Swift

    guard let vc = storyboard?.instantiateViewController(withIdentifier: "add") else { return }
            vc.modalPresentationStyle = .fullScreen
            present(vc, animated: true, completion: nil)
    

    How to select records without duplicate on just one field in SQL?

    Having Clause is the easiest way to find duplicate entry in Oracle and using rowid we can remove duplicate data..

    DELETE FROM products WHERE rowid IN (
      SELECT MAX(sl) FROM (
      SELECT itemcode, (rowid) sl FROM products WHERE itemcode IN (
      SELECT itemcode FROM products GROUP BY itemcode HAVING COUNT(itemcode)>1
    )) GROUP BY itemcode);
    

    How do I code my submit button go to an email address

    There are several ways to do an email from HTML. Typically you see people doing a mailto like so:

    <a href="mailto:[email protected]">Click to email</a>
    

    But if you are doing it from a button you may want to look into a javascript solution.

    How to show text on image when hovering?

    You can also use the title attribute in your image tag

    <img src="content/assets/thumbnails/transparent_150x150.png" alt="" title="hover text" />
    

    How can I convert a PFX certificate file for use with Apache on a linux server?

    To get it to work with Apache, we needed one extra step.

    openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
    openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain_encrypted.key
    openssl rsa -in domain_encrypted.key -out domain.key
    

    The final command decrypts the key for use with Apache. The domain.key file should look like this:

    -----BEGIN RSA PRIVATE KEY-----
    MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3
    LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp
    YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG
    A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq
    -----END RSA PRIVATE KEY-----
    

    Read a Csv file with powershell and capture corresponding data

    So I figured out what is wrong with this statement:

    Import-Csv H:\Programs\scripts\SomeText.csv |`
    

    (Original)

    Import-Csv H:\Programs\scripts\SomeText.csv -Delimiter "|"
    

    (Proposed, You must use quotations; otherwise, it will not work and ISE will give you an error)

    It requires the -Delimiter "|", in order for the variable to be populated with an array of items. Otherwise, Powershell ISE does not display the list of items.

    I cannot say that I would recommend the | operator, since it is used to pipe cmdlets into one another.

    I still cannot get the if statement to return true and output the values entered via the prompt.

    If anyone else can help, it would be great. I still appreciate the post, it has been very helpful!

    Add a link to an image in a css style sheet

    You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.

    Based only on your style you would have:

    <a href="home.com" id="logo"></a>
    

    Selecting non-blank cells in Excel with VBA

    If you are looking for the last row of a column, use:

    Sub SelectFirstColumn()
       SelectEntireColumn (1)
    End Sub
    
    Sub SelectSecondColumn()
        SelectEntireColumn (2)
    End Sub
    
    Sub SelectEntireColumn(columnNumber)
        Dim LastRow
        Sheets("sheet1").Select
        LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row
    
        ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
    End Sub
    

    Other commands you will need to get familiar with are copy and paste commands:

    Sub CopyOneToTwo()
        SelectEntireColumn (1)
        Selection.Copy
    
        Sheets("sheet1").Select
        ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
    End Sub
    

    Finally, you can reference worksheets in other workbooks by using the following syntax:

    Dim book2
    Set book2 = Workbooks.Open("C:\book2.xls")
    book2.Worksheets("sheet1")
    

    Problems with Android Fragment back stack

    If you are Struggling with addToBackStack() & popBackStack() then simply use

    FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, new HomeFragment(), "Home");
    ft.commit();`
    

    In your Activity In OnBackPressed() find out fargment by tag and then do your stuff

    Fragment home = getSupportFragmentManager().findFragmentByTag("Home");
    
    if (home instanceof HomeFragment && home.isVisible()) {
        // do you stuff
    }
    

    For more Information https://github.com/DattaHujare/NavigationDrawer I never use addToBackStack() for handling fragment.

    How to remove illegal characters from path and filenames?

    If you remove or replace with a single character the invalid characters, you can have collisions:

    <abc -> abc
    >abc -> abc
    

    Here is a simple method to avoid this:

    public static string ReplaceInvalidFileNameChars(string s)
    {
        char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars();
        foreach (char c in invalidFileNameChars)
            s = s.Replace(c.ToString(), "[" + Array.IndexOf(invalidFileNameChars, c) + "]");
        return s;
    }
    

    The result:

     <abc -> [1]abc
     >abc -> [2]abc
    

    Escape double quotes in Java

    Escaping the double quotes with backslashes is the only way to do this in Java.

    Some IDEs around such as IntelliJ IDEA do this escaping automatically when pasting such a String into a String literal (i.e. between the double quotes surrounding a java String literal)

    One other option would be to put the String into some kind of text file that you would then read at runtime

    Auto detect mobile browser (via user-agent?)

    My favorite Mobile Browser Detection mechanism is WURFL. It's updated frequently and it works with every major programming/language platform.

    In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

    The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

    In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

    Here with a dplyr solution to summarise the data and compute the standard error beforehand.

    library(dplyr)
    d <- GVW %>% group_by(Genotype,variable) %>%
        summarise(mean = mean(value),se = sd(value) / sqrt(n()))
    
    ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
      geom_bar(position = position_dodge(), stat = "identity", 
          colour="black", size=.3) +
      geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
          size=.3, width=.2, position=position_dodge(.9)) +
      xlab("Time") +
      ylab("Weight [g]") +
      scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
          labels = c("Knock-out", "Wild type")) +
      ggtitle("Effect of genotype on weight-gain") +
      scale_y_continuous(breaks = 0:20*4) +
      theme_bw()
    

    Wait until an HTML5 video loads

    you can use preload="none" in the attribute of video tag so the video will be displayed only when user clicks on play button.

    _x000D_
    _x000D_
    <video preload="none">
    _x000D_
    _x000D_
    _x000D_

    How to create a Restful web service with input parameters?

    Be careful. For this you need @GET (not @PUT).

    How to convert an IPv4 address into a integer in C#?

    32-bit unsigned integers are IPv4 addresses. Meanwhile, the IPAddress.Address property, while deprecated, is an Int64 that returns the unsigned 32-bit value of the IPv4 address (the catch is, it's in network byte order, so you need to swap it around).

    For example, my local google.com is at 64.233.187.99. That's equivalent to:

    64*2^24 + 233*2^16 + 187*2^8 + 99
    = 1089059683
    

    And indeed, http://1089059683/ works as expected (at least in Windows, tested with IE, Firefox and Chrome; doesn't work on iPhone though).

    Here's a test program to show both conversions, including the network/host byte swapping:

    using System;
    using System.Net;
    
    class App
    {
        static long ToInt(string addr)
        {
            // careful of sign extension: convert to uint first;
            // unsigned NetworkToHostOrder ought to be provided.
            return (long) (uint) IPAddress.NetworkToHostOrder(
                 (int) IPAddress.Parse(addr).Address);
        }
    
        static string ToAddr(long address)
        {
            return IPAddress.Parse(address.ToString()).ToString();
            // This also works:
            // return new IPAddress((uint) IPAddress.HostToNetworkOrder(
            //    (int) address)).ToString();
        }
    
        static void Main()
        {
            Console.WriteLine(ToInt("64.233.187.99"));
            Console.WriteLine(ToAddr(1089059683));
        }
    }
    

    How to parse XML to R data frame

    Data in XML format are rarely organized in a way that would allow the xmlToDataFrame function to work. You're better off extracting everything in lists and then binding the lists together in a data frame:

    require(XML)
    data <- xmlParse("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")
    
    xml_data <- xmlToList(data)
    

    In the case of your example data, getting location and start time is fairly straightforward:

    location <- as.list(xml_data[["data"]][["location"]][["point"]])
    
    start_time <- unlist(xml_data[["data"]][["time-layout"]][
        names(xml_data[["data"]][["time-layout"]]) == "start-valid-time"])
    

    Temperature data is a bit more complicated. First you need to get to the node that contains the temperature lists. Then you need extract both the lists, look within each one, and pick the one that has "hourly" as one of its values. Then you need to select only that list but only keep the values that have the "value" label:

    temps <- xml_data[["data"]][["parameters"]]
    temps <- temps[names(temps) == "temperature"]
    temps <- temps[sapply(temps, function(x) any(unlist(x) == "hourly"))]
    temps <- unlist(temps[[1]][sapply(temps, names) == "value"])
    
    out <- data.frame(
      as.list(location),
      "start_valid_time" = start_time,
      "hourly_temperature" = temps)
    
    head(out)
      latitude longitude          start_valid_time hourly_temperature
    1    29.81    -82.42 2013-06-19T16:00:00-04:00                 91
    2    29.81    -82.42 2013-06-19T17:00:00-04:00                 90
    3    29.81    -82.42 2013-06-19T18:00:00-04:00                 89
    4    29.81    -82.42 2013-06-19T19:00:00-04:00                 85
    5    29.81    -82.42 2013-06-19T20:00:00-04:00                 83
    6    29.81    -82.42 2013-06-19T21:00:00-04:00                 80
    

    Is it possible to iterate through JSONArray?

    Not with an iterator.

    For org.json.JSONArray, you can do:

    for (int i = 0; i < arr.length(); i++) {
      arr.getJSONObject(i);
    }
    

    For javax.json.JsonArray, you can do:

    for (int i = 0; i < arr.size(); i++) {
      arr.getJsonObject(i);
    }
    

    Simple UDP example to send and receive data from same socket

    I'll try to keep this short, I've done this a few months ago for a game I was trying to build, it does a UDP "Client-Server" connection that acts like TCP, you can send (message) (message + object) using this. I've done some testing with it and it works just fine, feel free to modify it if needed.

    Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

    body{
    height: 100%;
    overflow: hidden !important;
    width: 100%;
    position: fixed;
    

    works on iOS9

    How to avoid Sql Query Timeout

    Your query is probably fine. "The semaphore timeout period has expired" is a Network error, not a SQL Server timeout.

    There is apparently some sort of network problem between you and the SQL Server.

    edit: However, apparently the query runs for 15-20 min before giving the network error. That is a very long time, so perhaps the network error could be related to the long execution time. Optimization of the underlying View might help.

    If [MyTable] in your example is a View, can you post the View Definition so that we can have a go at optimizing it?

    iPad Multitasking support requires these orientations

    I am using Xamarin and there is no available option in the UI to specify "Requires full screen". I, therefore, had to follow @Michael Wang's answer with a slight modification. Here goes:

    Open the info.plist file in a text editor and add the lines:

    <key>UIRequiresFullScreen</key>
    <true/>
    

    I tried setting the value to "YES" but it didn't work, which was kind of expected.

    In case you are wondering, I placed the above lines below the UISupportedInterfaceOrientations section

    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
    </array>
    

    Hope this helps someone. Credit to Michael.

    T-SQL XOR Operator

    From your comment:

    Example: WHERE (Note is null) ^ (ID is null)

    you could probably try:

    where
       (case when Note is null then 1 else 0 end)
     <>(case when ID is null then 1 else 0 end)
    

    Getting the absolute path of the executable, using C#?

    The one that worked for me and isn't above was Process.GetCurrentProcess().MainModule.FileName.

    Sort array of objects by single key with date value

    I face with same thing, so i handle this with a generic why and i build a function for this:

    //example:
    //array: [{name: 'idan', workerType: '3'}, {name: 'stas', workerType: '5'}, {name: 'kirill', workerType: '2'}]
    //keyField: 'workerType'
    // keysArray: ['4', '3', '2', '5', '6']
    
    sortByArrayOfKeys = (array, keyField, keysArray) => {
        array.sort((a, b) => {
            const aIndex = keysArray.indexOf(a[keyField])
            const bIndex = keysArray.indexOf(b[keyField])
            if (aIndex < bIndex) return -1;
            if (aIndex > bIndex) return 1;
            return 0;
        })
    }
    

    No provider for Router?

    Please do the import like below:

    import { Router } from '@angular/Router';

    The mistake that was being done was -> import { Router } from '@angular/router';

    How to INNER JOIN 3 tables using CodeIgniter

    function fetch_comments($ticket_id){
        $this->db->select('tbl_tickets_replies.comments, 
               tbl_users.username,tbl_roles.role_name');
        $this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
        $this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
        $this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
        return $this->db->get('tbl_tickets_replies');
    }
    

    Display milliseconds in Excel

    I've discovered in Excel 2007, if the results are a Table from an embedded query, the ss.000 does not work. I can paste the query results (from SQL Server Management Studio), and format the time just fine. But when I embed the query as a Data Connection in Excel, the format always gives .000 as the milliseconds.

    Right click to select a row in a Datagridview and show a menu to delete it

    I finally solved it:

    • In Visual Studio, create a ContextMenuStrip with an item called "DeleteRow"

    • Then at the DataGridView link the ContextMenuStrip

    Using the code below helped me getting it work.

    this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
    this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);
    

    Here is the cool part

    private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
    {
        if(e.Button == MouseButtons.Right)
        {
            var hti = MyDataGridView.HitTest(e.X, e.Y);
            MyDataGridView.ClearSelection();
            MyDataGridView.Rows[hti.RowIndex].Selected = true;
        }
    }
    
    private void DeleteRow_Click(object sender, EventArgs e)
    {
        Int32 rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
        MyDataGridView.Rows.RemoveAt(rowToDelete);
        MyDataGridView.ClearSelection();
    }
    

    Adding header to all request with Retrofit 2

    Try this type header for Retrofit 1.9 and 2.0. For Json Content Type.

    @Headers({"Accept: application/json"})
    @POST("user/classes")
    Call<playlist> addToPlaylist(@Body PlaylistParm parm);
    

    You can add many more headers i.e

    @Headers({
            "Accept: application/json",
            "User-Agent: Your-App-Name",
            "Cache-Control: max-age=640000"
        })
    

    Dynamically Add to headers:

    @POST("user/classes")
    Call<ResponseModel> addToPlaylist(@Header("Content-Type") String content_type, @Body RequestModel req);
    

    Call you method i.e

    mAPI.addToPlayList("application/json", playListParam);
    

    Or

    Want to pass everytime then Create HttpClient object with http Interceptor:

    OkHttpClient httpClient = new OkHttpClient();
            httpClient.networkInterceptors().add(new Interceptor() {
                @Override
                public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                    Request.Builder requestBuilder = chain.request().newBuilder();
                    requestBuilder.header("Content-Type", "application/json");
                    return chain.proceed(requestBuilder.build());
                }
            });
    

    Then add to retrofit object

    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();
    

    UPDATE if you are using Kotlin remove the { } else it will not work

    Excel VBA date formats

    It's important to distinguish between the content of cells, their display format, the data type read from cells by VBA, and the data type written to cells from VBA and how Excel automatically interprets this. (See e.g. this previous answer.) The relationship between these can be a bit complicated, because Excel will do things like interpret values of one type (e.g. string) as being a certain other data type (e.g. date) and then automatically change the display format based on this. Your safest bet it do everything explicitly and not to rely on this automatic stuff.

    I ran your experiment and I don't get the same results as you do. My cell A1 stays a Date the whole time, and B1 stays 41575. So I can't answer your question #1. Results probably depend on how your Excel version/settings choose to automatically detect/change a cell's number format based on its content.

    Question #2, "How can I ensure that a cell will return a date value": well, not sure what you mean by "return" a date value, but if you want it to contain a numerical value that is displayed as a date, based on what you write to it from VBA, then you can either:

    • Write to the cell a string value that you hope Excel will automatically interpret as a date and format as such. Cross fingers. Obviously this is not very robust. Or,

    • Write a numerical value to the cell from VBA (obviously a Date type is the intended type, but an Integer, Long, Single, or Double could do as well) and explicitly set the cells' number format to your desired date format using the .NumberFormat property (or manually in Excel). This is much more robust.

    If you want to check that existing cell contents can be displayed as a date, then here's a function that will help:

    Function CellContentCanBeInterpretedAsADate(cell As Range) As Boolean
        Dim d As Date
        On Error Resume Next
        d = CDate(cell.Value)
        If Err.Number <> 0 Then
            CellContentCanBeInterpretedAsADate = False
        Else
            CellContentCanBeInterpretedAsADate = True
        End If
        On Error GoTo 0
    End Function
    

    Example usage:

    Dim cell As Range
    Set cell = Range("A1")
    
    If CellContentCanBeInterpretedAsADate(cell) Then
        cell.NumberFormat = "mm/dd/yyyy hh:mm"
    Else
        cell.NumberFormat = "General"
    End If
    

    How can I show a combobox in Android?

    The questions is perfectly valid and clear since Spinner and ComboBox (read it: Spinner where you can provide a custom value as well) are two different things.

    I was looking for the same thing myself and I wasn't satisfied with the given answers. So I created my own thing. Perhaps some will find the following hints useful. I am not providing the full source code as I am using some legacy calls in my own project. It should be pretty clear anyway.

    Here is the screenshot of the final thing:

    ComboBox on Android

    The first thing was to create a view that will look the same as the spinner that hasn't been expanded yet. In the screenshot, on the top of the screen (out of focus) you can see the spinner and the custom view right bellow it. For that purpose I used LinearLayout (actually, I inherited from Linear Layout) with style="?android:attr/spinnerStyle". LinearLayout contains TextView with style="?android:attr/spinnerItemStyle". Complete XML snippet would be:

    <com.example.comboboxtest.ComboBox 
        style="?android:attr/spinnerStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
    
        <TextView
            android:id="@+id/textView"
            style="?android:attr/spinnerItemStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="marquee"
            android:singleLine="true"
            android:text="January"
            android:textAlignment="inherit" 
        />
    
    </com.example.comboboxtest.ComboBox>
    

    As, I mentioned earlier ComboBox inherits from LinearLayout. It also implements OnClickListener which creates a dialog with a custom view inflated from the XML file. Here is the inflated view:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" 
        >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" 
            >
            <EditText
                android:id="@+id/editText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10"
                android:hint="Enter custom value ..." >
    
                <requestFocus />
            </EditText>
    
            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="OK" 
            />
        </LinearLayout>
    
        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" 
        />
    
    </LinearLayout>
    

    There are two more listeners that you need to implement: onItemClick for the list and onClick for the button. Both of these set the selected value and dismiss the dialog.

    For the list, you want it to look the same as expanded Spinner, you can do that providing the list adapter with the appropriate (Spinner) style like this:

    ArrayAdapter<String> adapter = 
        new ArrayAdapter<String>(
            activity,
            android.R.layout.simple_spinner_dropdown_item, 
            states
        );
    

    More or less, that should be it.

    Free Barcode API for .NET

    Could the Barcode Rendering Framework at Codeplex GitHub be of help?

    browser sessionStorage. share between tabs?

    Using sessionStorage for this is not possible.

    From the MDN Docs

    Opening a page in a new tab or window will cause a new session to be initiated.

    That means that you can't share between tabs, for this you should use localStorage

    Java abstract interface

    Well 'Abstract Interface' is a Lexical construct: http://en.wikipedia.org/wiki/Lexical_analysis.

    It is required by the compiler, you could also write interface.

    Well don't get too much into Lexical construct of the language as they might have put it there to resolve some compilation ambiguity which is termed as special cases during compiling process or for some backward compatibility, try to focus on core Lexical construct.

    The essence of `interface is to capture some abstract concept (idea/thought/higher order thinking etc) whose implementation may vary ... that is, there may be multiple implementation.

    An Interface is a pure abstract data type that represents the features of the Object it is capturing or representing.

    Features can be represented by space or by time. When they are represented by space (memory storage) it means that your concrete class will implement a field and method/methods that will operate on that field or by time which means that the task of implementing the feature is purely computational (requires more cpu clocks for processing) so you have a trade off between space and time for feature implementation.

    If your concrete class does not implement all features it again becomes abstract because you have a implementation of your thought or idea or abstractness but it is not complete , you specify it by abstract class.

    A concrete class will be a class/set of classes which will fully capture the abstractness you are trying to capture class XYZ.

    So the Pattern is

    Interface--->Abstract class/Abstract classes(depends)-->Concrete class
    

    PHP memcached Fatal error: Class 'Memcache' not found

    I went into wp-config/ and deleted the object-cache.php and advanced-cache.php and it worked fine for me.

    load external URL into modal jquery ui dialog

    EDIT: This answer might be outdated if you're using a recent version of jQueryUI.

    For an anchor to trigger the dialog -

    <a href="http://ibm.com" class="example">
    

    Here's the script -

    $('a.example').click(function(){   //bind handlers
       var url = $(this).attr('href');
       showDialog(url);
    
       return false;
    });
    
    $("#targetDiv").dialog({  //create dialog, but keep it closed
       autoOpen: false,
       height: 300,
       width: 350,
       modal: true
    });
    
    function showDialog(url){  //load content and open dialog
        $("#targetDiv").load(url);
        $("#targetDiv").dialog("open");         
    }
    

    JUNIT testing void methods

    If your method has no side effects, and doesn't return anything, then it's not doing anything.

    If your method does some computation and returns the result of that computation, you can obviously enough assert that the result returned is correct.

    If your code doesn't return anything but does have side effects, you can call the code and then assert that the correct side effects have happened. What the side effects are will determine how you do the checks.

    In your example, you are calling static methods from your non-returning functions, which makes it tricky unless you can inspect that the result of all those static methods are correct. A better way - from a testing point of view - is to inject actual objects in that you call methods on. You can then use something like EasyMock or Mockito to create a Mock Object in your unit test, and inject the mock object into the class. The Mock Object then lets you assert that the correct functions were called, with the correct values and in the correct order.

    For example:

    private ErrorFile errorFile;
    
    public void setErrorFile(ErrorFile errorFile) {
        this.errorFile = errorFile;
    }
    
    private void method1(arg1) {
        if (arg1.indexOf("$") == -1) {
    
            //Add an error message 
            errorFile.addErrorMessage("There is a dollar sign in the specified parameter");
        }
    }
    

    Then in your test you can write:

    public void testMethod1() {
        ErrorFile errorFile = EasyMock.createMock(ErrorFile.class);
        errorFile.addErrorMessage("There is a dollar sign in the specified parameter");
        EasyMock.expectLastCall(errorFile);
        EasyMock.replay(errorFile);
    
        ClassToTest classToTest = new ClassToTest();
        classToTest.setErrorFile(errorFile);
        classToTest.method1("a$b");
    
        EasyMock.verify(errorFile); // This will fail the test if the required addErrorMessage call didn't happen
    }
    

    How to add header row to a pandas DataFrame

    You can use names directly in the read_csv

    names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

    Cov = pd.read_csv("path/to/file.txt", 
                      sep='\t', 
                      names=["Sequence", "Start", "End", "Coverage"])
    

    Difference between InvariantCulture and Ordinal string comparison

    It does matter, for example - there is a thing called character expansion

    var s1 = "Strasse";
    var s2 = "Straße";
    
    s1.Equals(s2, StringComparison.Ordinal);           //false
    s1.Equals(s2, StringComparison.InvariantCulture);  //true
    

    With InvariantCulture the ß character gets expanded to ss.

    How to strip all non-alphabetic characters from string in SQL Server?

    This solution, inspired by Mr. Allen's solution, requires a Numbers table of integers (which you should have on hand if you want to do serious query operations with good performance). It does not require a CTE. You can change the NOT IN (...) expression to exclude specific characters, or change it to an IN (...) OR LIKE expression to retain only certain characters.

    SELECT (
        SELECT  SUBSTRING([YourString], N, 1)
        FROM    dbo.Numbers
        WHERE   N > 0 AND N <= CONVERT(INT, LEN([YourString]))
            AND SUBSTRING([YourString], N, 1) NOT IN ('(',')',',','.')
        FOR XML PATH('')
    ) AS [YourStringTransformed]
    FROM ...
    

    Generate random number between two numbers in JavaScript

    var x = 6; // can be any number
    var rand = Math.floor(Math.random()*x) + 1;
    

    Defining a HTML template to append using JQuery

    Add somewhere in body

    <div class="hide">
    <a href="#" class="list-group-item">
        <table>
            <tr>
                <td><img src=""></td>
                <td><p class="list-group-item-text"></p></td>
            </tr>
        </table>
    </a>
    </div>
    

    then create css

    .hide { display: none; }
    

    and add to your js

    $('#output').append( $('.hide').html() );
    

    How to move/rename a file using an Ansible task on a remote system

    I know it's a YEARS old topic, but I got frustrated and built a role for myself to do exactly this for an arbitrary list of files. Extend as you see fit:

    main.yml

    - name: created destination directory
      file:
        path: /path/to/directory
        state: directory
        mode: '0750'
    - include_tasks: move.yml
      loop:
        - file1
        - file2
        - file3
    

    move.yml

    - name: stat the file
      stat:
        path: {{ item }}
      register: my_file
    
    - name: hard link the file into directory
      file:
        src: /original/path/to/{{ item }}
        dest: /path/to/directory/{{ item }}
        state: hard
      when: my_file.stat.exists
    
    - name: Delete the original file
      file:
        path: /original/path/to/{{ item }}
        state: absent
      when: my_file.stat.exists
    

    Note that hard linking is preferable to copying here, because it inherently preserves ownership and permissions (in addition to not consuming more disk space for a second copy of the file).

    Why does modulus division (%) only work with integers?

    You're looking for fmod().

    I guess to more specifically answer your question, in older languages the % operator was just defined as integer modular division and in newer languages they decided to expand the definition of the operator.

    EDIT: If I were to wager a guess why, I would say it's because the idea of modular arithmetic originates in number theory and deals specifically with integers.

    presenting ViewController with NavigationViewController swift

    The accepted answer is great. This is not answer, but just an illustration of the issue.

    I present a viewController like this:

    inside vc1:

    func showVC2() {
        if let navController = self.navigationController{
            navController.present(vc2, animated: true)
        }
    }
    

    inside vc2:

    func returnFromVC2() {
        if let navController = self.navigationController {
            navController.popViewController(animated: true)
        }else{
            print("navigationController is nil") <-- I was reaching here!
        }
    }
    

    As 'stefandouganhyde' has said: "it is not contained by your UINavigationController or any other"

    new solution:

    func returnFromVC2() {
        dismiss(animated: true, completion: nil)
    }
    

    List all liquibase sql types

    This is a comprehensive list of all liquibase datatypes and how they are converted for different databases:

    boolean
    MySQLDatabase: BIT(1)
    SQLiteDatabase: BOOLEAN
    H2Database: BOOLEAN
    PostgresDatabase: BOOLEAN
    UnsupportedDatabase: BOOLEAN
    DB2Database: SMALLINT
    MSSQLDatabase: [bit]
    OracleDatabase: NUMBER(1)
    HsqlDatabase: BOOLEAN
    FirebirdDatabase: SMALLINT
    DerbyDatabase: SMALLINT
    InformixDatabase: BOOLEAN
    SybaseDatabase: BIT
    SybaseASADatabase: BIT
    
    tinyint
    MySQLDatabase: TINYINT
    SQLiteDatabase: TINYINT
    H2Database: TINYINT
    PostgresDatabase: SMALLINT
    UnsupportedDatabase: TINYINT
    DB2Database: SMALLINT
    MSSQLDatabase: [tinyint]
    OracleDatabase: NUMBER(3)
    HsqlDatabase: TINYINT
    FirebirdDatabase: SMALLINT
    DerbyDatabase: SMALLINT
    InformixDatabase: TINYINT
    SybaseDatabase: TINYINT
    SybaseASADatabase: TINYINT
    
    int
    MySQLDatabase: INT
    SQLiteDatabase: INTEGER
    H2Database: INT
    PostgresDatabase: INT
    UnsupportedDatabase: INT
    DB2Database: INTEGER
    MSSQLDatabase: [int]
    OracleDatabase: INTEGER
    HsqlDatabase: INT
    FirebirdDatabase: INT
    DerbyDatabase: INTEGER
    InformixDatabase: INT
    SybaseDatabase: INT
    SybaseASADatabase: INT
    
    mediumint
    MySQLDatabase: MEDIUMINT
    SQLiteDatabase: MEDIUMINT
    H2Database: MEDIUMINT
    PostgresDatabase: MEDIUMINT
    UnsupportedDatabase: MEDIUMINT
    DB2Database: MEDIUMINT
    MSSQLDatabase: [int]
    OracleDatabase: MEDIUMINT
    HsqlDatabase: MEDIUMINT
    FirebirdDatabase: MEDIUMINT
    DerbyDatabase: MEDIUMINT
    InformixDatabase: MEDIUMINT
    SybaseDatabase: MEDIUMINT
    SybaseASADatabase: MEDIUMINT
    
    bigint
    MySQLDatabase: BIGINT
    SQLiteDatabase: BIGINT
    H2Database: BIGINT
    PostgresDatabase: BIGINT
    UnsupportedDatabase: BIGINT
    DB2Database: BIGINT
    MSSQLDatabase: [bigint]
    OracleDatabase: NUMBER(38, 0)
    HsqlDatabase: BIGINT
    FirebirdDatabase: BIGINT
    DerbyDatabase: BIGINT
    InformixDatabase: INT8
    SybaseDatabase: BIGINT
    SybaseASADatabase: BIGINT
    
    float
    MySQLDatabase: FLOAT
    SQLiteDatabase: FLOAT
    H2Database: FLOAT
    PostgresDatabase: FLOAT
    UnsupportedDatabase: FLOAT
    DB2Database: FLOAT
    MSSQLDatabase: [float](53)
    OracleDatabase: FLOAT
    HsqlDatabase: FLOAT
    FirebirdDatabase: FLOAT
    DerbyDatabase: FLOAT
    InformixDatabase: FLOAT
    SybaseDatabase: FLOAT
    SybaseASADatabase: FLOAT
    
    double
    MySQLDatabase: DOUBLE
    SQLiteDatabase: DOUBLE
    H2Database: DOUBLE
    PostgresDatabase: DOUBLE PRECISION
    UnsupportedDatabase: DOUBLE
    DB2Database: DOUBLE
    MSSQLDatabase: [float](53)
    OracleDatabase: FLOAT(24)
    HsqlDatabase: DOUBLE
    FirebirdDatabase: DOUBLE PRECISION
    DerbyDatabase: DOUBLE
    InformixDatabase: DOUBLE PRECISION
    SybaseDatabase: DOUBLE
    SybaseASADatabase: DOUBLE
    
    decimal
    MySQLDatabase: DECIMAL
    SQLiteDatabase: DECIMAL
    H2Database: DECIMAL
    PostgresDatabase: DECIMAL
    UnsupportedDatabase: DECIMAL
    DB2Database: DECIMAL
    MSSQLDatabase: [decimal](18, 0)
    OracleDatabase: DECIMAL
    HsqlDatabase: DECIMAL
    FirebirdDatabase: DECIMAL
    DerbyDatabase: DECIMAL
    InformixDatabase: DECIMAL
    SybaseDatabase: DECIMAL
    SybaseASADatabase: DECIMAL
    
    number
    MySQLDatabase: numeric
    SQLiteDatabase: NUMBER
    H2Database: NUMBER
    PostgresDatabase: numeric
    UnsupportedDatabase: NUMBER
    DB2Database: numeric
    MSSQLDatabase: [numeric](18, 0)
    OracleDatabase: NUMBER
    HsqlDatabase: numeric
    FirebirdDatabase: numeric
    DerbyDatabase: numeric
    InformixDatabase: numeric
    SybaseDatabase: numeric
    SybaseASADatabase: numeric
    
    blob
    MySQLDatabase: LONGBLOB
    SQLiteDatabase: BLOB
    H2Database: BLOB
    PostgresDatabase: BYTEA
    UnsupportedDatabase: BLOB
    DB2Database: BLOB
    MSSQLDatabase: [varbinary](MAX)
    OracleDatabase: BLOB
    HsqlDatabase: BLOB
    FirebirdDatabase: BLOB
    DerbyDatabase: BLOB
    InformixDatabase: BLOB
    SybaseDatabase: IMAGE
    SybaseASADatabase: LONG BINARY
    
    function
    MySQLDatabase: FUNCTION
    SQLiteDatabase: FUNCTION
    H2Database: FUNCTION
    PostgresDatabase: FUNCTION
    UnsupportedDatabase: FUNCTION
    DB2Database: FUNCTION
    MSSQLDatabase: [function]
    OracleDatabase: FUNCTION
    HsqlDatabase: FUNCTION
    FirebirdDatabase: FUNCTION
    DerbyDatabase: FUNCTION
    InformixDatabase: FUNCTION
    SybaseDatabase: FUNCTION
    SybaseASADatabase: FUNCTION
    
    UNKNOWN
    MySQLDatabase: UNKNOWN
    SQLiteDatabase: UNKNOWN
    H2Database: UNKNOWN
    PostgresDatabase: UNKNOWN
    UnsupportedDatabase: UNKNOWN
    DB2Database: UNKNOWN
    MSSQLDatabase: [UNKNOWN]
    OracleDatabase: UNKNOWN
    HsqlDatabase: UNKNOWN
    FirebirdDatabase: UNKNOWN
    DerbyDatabase: UNKNOWN
    InformixDatabase: UNKNOWN
    SybaseDatabase: UNKNOWN
    SybaseASADatabase: UNKNOWN
    
    datetime
    MySQLDatabase: datetime
    SQLiteDatabase: TEXT
    H2Database: TIMESTAMP
    PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
    UnsupportedDatabase: datetime
    DB2Database: TIMESTAMP
    MSSQLDatabase: [datetime]
    OracleDatabase: TIMESTAMP
    HsqlDatabase: TIMESTAMP
    FirebirdDatabase: TIMESTAMP
    DerbyDatabase: TIMESTAMP
    InformixDatabase: DATETIME YEAR TO FRACTION(5)
    SybaseDatabase: datetime
    SybaseASADatabase: datetime
    
    time
    MySQLDatabase: time
    SQLiteDatabase: time
    H2Database: time
    PostgresDatabase: TIME WITHOUT TIME ZONE
    UnsupportedDatabase: time
    DB2Database: time
    MSSQLDatabase: [time](7)
    OracleDatabase: DATE
    HsqlDatabase: time
    FirebirdDatabase: time
    DerbyDatabase: time
    InformixDatabase: INTERVAL HOUR TO FRACTION(5)
    SybaseDatabase: time
    SybaseASADatabase: time
    
    timestamp
    MySQLDatabase: timestamp
    SQLiteDatabase: TEXT
    H2Database: TIMESTAMP
    PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
    UnsupportedDatabase: timestamp
    DB2Database: timestamp
    MSSQLDatabase: [datetime]
    OracleDatabase: TIMESTAMP
    HsqlDatabase: TIMESTAMP
    FirebirdDatabase: TIMESTAMP
    DerbyDatabase: TIMESTAMP
    InformixDatabase: DATETIME YEAR TO FRACTION(5)
    SybaseDatabase: datetime
    SybaseASADatabase: timestamp
    
    date
    MySQLDatabase: date
    SQLiteDatabase: date
    H2Database: date
    PostgresDatabase: date
    UnsupportedDatabase: date
    DB2Database: date
    MSSQLDatabase: [date]
    OracleDatabase: date
    HsqlDatabase: date
    FirebirdDatabase: date
    DerbyDatabase: date
    InformixDatabase: date
    SybaseDatabase: date
    SybaseASADatabase: date
    
    char
    MySQLDatabase: CHAR
    SQLiteDatabase: CHAR
    H2Database: CHAR
    PostgresDatabase: CHAR
    UnsupportedDatabase: CHAR
    DB2Database: CHAR
    MSSQLDatabase: [char](1)
    OracleDatabase: CHAR
    HsqlDatabase: CHAR
    FirebirdDatabase: CHAR
    DerbyDatabase: CHAR
    InformixDatabase: CHAR
    SybaseDatabase: CHAR
    SybaseASADatabase: CHAR
    
    varchar
    MySQLDatabase: VARCHAR
    SQLiteDatabase: VARCHAR
    H2Database: VARCHAR
    PostgresDatabase: VARCHAR
    UnsupportedDatabase: VARCHAR
    DB2Database: VARCHAR
    MSSQLDatabase: [varchar](1)
    OracleDatabase: VARCHAR2
    HsqlDatabase: VARCHAR
    FirebirdDatabase: VARCHAR
    DerbyDatabase: VARCHAR
    InformixDatabase: VARCHAR
    SybaseDatabase: VARCHAR
    SybaseASADatabase: VARCHAR
    
    nchar
    MySQLDatabase: NCHAR
    SQLiteDatabase: NCHAR
    H2Database: NCHAR
    PostgresDatabase: NCHAR
    UnsupportedDatabase: NCHAR
    DB2Database: NCHAR
    MSSQLDatabase: [nchar](1)
    OracleDatabase: NCHAR
    HsqlDatabase: CHAR
    FirebirdDatabase: NCHAR
    DerbyDatabase: NCHAR
    InformixDatabase: NCHAR
    SybaseDatabase: NCHAR
    SybaseASADatabase: NCHAR
    
    nvarchar
    MySQLDatabase: NVARCHAR
    SQLiteDatabase: NVARCHAR
    H2Database: NVARCHAR
    PostgresDatabase: VARCHAR
    UnsupportedDatabase: NVARCHAR
    DB2Database: NVARCHAR
    MSSQLDatabase: [nvarchar](1)
    OracleDatabase: NVARCHAR2
    HsqlDatabase: VARCHAR
    FirebirdDatabase: NVARCHAR
    DerbyDatabase: VARCHAR
    InformixDatabase: NVARCHAR
    SybaseDatabase: NVARCHAR
    SybaseASADatabase: NVARCHAR
    
    clob
    MySQLDatabase: LONGTEXT
    SQLiteDatabase: TEXT
    H2Database: CLOB
    PostgresDatabase: TEXT
    UnsupportedDatabase: CLOB
    DB2Database: CLOB
    MSSQLDatabase: [varchar](MAX)
    OracleDatabase: CLOB
    HsqlDatabase: CLOB
    FirebirdDatabase: BLOB SUB_TYPE TEXT
    DerbyDatabase: CLOB
    InformixDatabase: CLOB
    SybaseDatabase: TEXT
    SybaseASADatabase: LONG VARCHAR
    
    currency
    MySQLDatabase: DECIMAL
    SQLiteDatabase: REAL
    H2Database: DECIMAL
    PostgresDatabase: DECIMAL
    UnsupportedDatabase: DECIMAL
    DB2Database: DECIMAL(19, 4)
    MSSQLDatabase: [money]
    OracleDatabase: NUMBER(15, 2)
    HsqlDatabase: DECIMAL
    FirebirdDatabase: DECIMAL(18, 4)
    DerbyDatabase: DECIMAL
    InformixDatabase: MONEY
    SybaseDatabase: MONEY
    SybaseASADatabase: MONEY
    
    uuid
    MySQLDatabase: char(36)
    SQLiteDatabase: TEXT
    H2Database: UUID
    PostgresDatabase: UUID
    UnsupportedDatabase: char(36)
    DB2Database: char(36)
    MSSQLDatabase: [uniqueidentifier]
    OracleDatabase: RAW(16)
    HsqlDatabase: char(36)
    FirebirdDatabase: char(36)
    DerbyDatabase: char(36)
    InformixDatabase: char(36)
    SybaseDatabase: UNIQUEIDENTIFIER
    SybaseASADatabase: UNIQUEIDENTIFIER
    

    For reference, this is the groovy script I've used to generate this output:

    @Grab('org.liquibase:liquibase-core:3.5.1')
    
    import liquibase.database.core.*
    import liquibase.datatype.core.*
    
    def datatypes = [BooleanType,TinyIntType,IntType,MediumIntType,BigIntType,FloatType,DoubleType,DecimalType,NumberType,BlobType,DatabaseFunctionType,UnknownType,DateTimeType,TimeType,TimestampType,DateType,CharType,VarcharType,NCharType,NVarcharType,ClobType,CurrencyType,UUIDType]
    def databases = [MySQLDatabase, SQLiteDatabase, H2Database, PostgresDatabase, UnsupportedDatabase, DB2Database, MSSQLDatabase, OracleDatabase, HsqlDatabase, FirebirdDatabase, DerbyDatabase, InformixDatabase, SybaseDatabase, SybaseASADatabase]
    datatypes.each {
        def datatype = it.newInstance()
        datatype.finishInitialization("")
        println datatype.name
        databases.each { println "$it.simpleName: ${datatype.toDatabaseDataType(it.newInstance())}"}
        println ''
    }
    

    Checking if sys.argv[x] is defined

    I use this - it never fails:

    startingpoint = 'blah'
    if sys.argv[1:]:
       startingpoint = sys.argv[1]
    

    PreparedStatement with Statement.RETURN_GENERATED_KEYS

    You mean something like this?

    long key = -1L;
    
    PreparedStatement preparedStatement = connection.prepareStatement(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
    preparedStatement.setXXX(index, VALUE);
    preparedStatement.executeUpdate();
    
    ResultSet rs = preparedStatement.getGeneratedKeys();
    
    if (rs.next()) {
        key = rs.getLong(1);
    }
    

    How to bind inverse boolean properties in WPF?

    I did something very similar. I created my property behind the scenes that enabled the selection of a combobox ONLY if it had finished searching for data. When my window first appears, it launches an async loaded command but I do not want the user to click on the combobox while it is still loading data (would be empty, then would be populated). So by default the property is false so I return the inverse in the getter. Then when I'm searching I set the property to true and back to false when complete.

    private bool _isSearching;
    public bool IsSearching
    {
        get { return !_isSearching; }
        set
        {
            if(_isSearching != value)
            {
                _isSearching = value;
                OnPropertyChanged("IsSearching");
            }
        }
    }
    
    public CityViewModel()
    {
        LoadedCommand = new DelegateCommandAsync(LoadCity, LoadCanExecute);
    }
    
    private async Task LoadCity(object pArg)
    {
        IsSearching = true;
    
        //**Do your searching task here**
    
        IsSearching = false;
    }
    
    private bool LoadCanExecute(object pArg)
    {
        return IsSearching;
    }
    

    Then for the combobox I can bind it directly to the IsSearching:

    <ComboBox ItemsSource="{Binding Cities}" IsEnabled="{Binding IsSearching}" DisplayMemberPath="City" />
    

    How to declare a constant in Java

    Anything that is static is in the class level. You don't have to create instance to access static fields/method. Static variable will be created once when class is loaded.

    Instance variables are the variable associated with the object which means that instance variables are created for each object you create. All objects will have separate copy of instance variable for themselves.

    In your case, when you declared it as static final, that is only one copy of variable. If you change it from multiple instance, the same variable would be updated (however, you have final variable so it cannot be updated).

    In second case, the final int a is also constant , however it is created every time you create an instance of the class where that variable is declared.

    Have a look on this Java tutorial for better understanding ,

    Search a string in a file and delete it from this file by Shell Script

    Try the vim-way:

    ex -s +"g/foo/d" -cwq file.txt
    

    How should I escape strings in JSON?

    Try this org.codehaus.jettison.json.JSONObject.quote("your string").

    Download it here: http://mvnrepository.com/artifact/org.codehaus.jettison/jettison

    How to export iTerm2 Profiles

    It isn't the most obvious workflow. You first have to click "Load preferences from a custom folder or URL". Select the folder you want them saved in; I keep an appsync folder in Dropbox for these sorts of things. Once you have selected the folder, you can click "Save settings to Folder". On a new machine / fresh install of your OS, you can now load these settings from the folder. At first I was sure that loading preferences would wipe out my previous settings, but it didn't.

    How do you run a .exe with parameters using vba's shell()?

    Here are some examples of how to use Shell in VBA.
    Open stackoverflow in Chrome.

    Call Shell("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & _
     " -url" & " " & "www.stackoverflow.com",vbMaximizedFocus)
    

    Open some text file.

    Call Shell ("notepad C:\Users\user\Desktop\temp\TEST.txt")
    

    Open some application.

    Call Shell("C:\Temp\TestApplication.exe",vbNormalFocus)
    

    Hope this helps!

    Find all packages installed with easy_install/pip?

    Adding to @Paul Woolcock's answer,

    pip freeze > requirements.txt
    

    will create a requirements file with all installed packages along with the installed version numbers in the active environment at the current location. Running

    pip install -r requirements.txt
    

    will install the packages specified in the requirements file.

    How do I store data in local storage using Angularjs?

    If you use $window.localStorage.setItem(key,value) to store,$window.localStorage.getItem(key) to retrieve and $window.localStorage.removeItem(key) to remove, then you can access the values in any page.

    You have to pass the $window service to the controller. Though in JavaScript, window object is available globally.

    By using $window.localStorage.xxXX() the user has control over the localStorage value. The size of the data depends upon the browser. If you only use $localStorage then value remains as long as you use window.location.href to navigate to other page and if you use <a href="location"></a> to navigate to other page then your $localStorage value is lost in the next page.

    'typeid' versus 'typeof' in C++

    C++ language has no such thing as typeof. You must be looking at some compiler-specific extension. If you are talking about GCC's typeof, then a similar feature is present in C++11 through the keyword decltype. Again, C++ has no such typeof keyword.

    typeid is a C++ language operator which returns type identification information at run time. It basically returns a type_info object, which is equality-comparable with other type_info objects.

    Note, that the only defined property of the returned type_info object has is its being equality- and non-equality-comparable, i.e. type_info objects describing different types shall compare non-equal, while type_info objects describing the same type have to compare equal. Everything else is implementation-defined. Methods that return various "names" are not guaranteed to return anything human-readable, and even not guaranteed to return anything at all.

    Note also, that the above probably implies (although the standard doesn't seem to mention it explicitly) that consecutive applications of typeid to the same type might return different type_info objects (which, of course, still have to compare equal).

    How to exit an Android app programmatically?

    How about this.finishAffinity()

    From the docs,

    Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch. Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.

    Store select query's output in one array in postgres

    There are two ways. One is to aggregate:

    SELECT array_agg(column_name::TEXT)
    FROM information.schema.columns
    WHERE table_name = 'aean'
    

    The other is to use an array constructor:

    SELECT ARRAY(
    SELECT column_name 
    FROM information.schema.columns 
    WHERE table_name = 'aean')
    

    I'm presuming this is for plpgsql. In that case you can assign it like this:

    colnames := ARRAY(
    SELECT column_name
    FROM information.schema.columns
    WHERE table_name='aean'
    );
    

    Change File Extension Using C#

    You should do a move of the file to rename it. In your example code you are only changing the string, not the file:

    myfile= "c:/my documents/my images/cars/a.jpg";
    string extension = Path.GetExtension(myffile); 
    myfile.replace(extension,".Jpeg");
    

    you are only changing myfile (which is a string). To move the actual file, you should do

    FileInfo f = new FileInfo(myfile);
    f.MoveTo(Path.ChangeExtension(myfile, ".Jpeg"));
    

    See FileInfo.MoveTo

    How to select Multiple images from UIImagePickerController

    You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

    Objective-C
    1. ELCImagePickerController
    2. WSAssetPickerController
    3. QBImagePickerController
    4. ZCImagePickerController
    5. CTAssetsPickerController
    6. AGImagePickerController
    7. UzysAssetsPickerController
    8. MWPhotoBrowser
    9. TSAssetsPickerController
    10. CustomImagePicker
    11. InstagramPhotoPicker
    12. GMImagePicker
    13. DLFPhotosPicker
    14. CombinationPickerController
    15. AssetPicker
    16. BSImagePicker
    17. SNImagePicker
    18. DoImagePickerController
    19. grabKit
    20. IQMediaPickerController
    21. HySideScrollingImagePicker
    22. MultiImageSelector
    23. TTImagePicker
    24. SelectImages
    25. ImageSelectAndSave
    26. imagepicker-multi-select
    27. MultiSelectImagePickerController
    28. YangMingShan(Yahoo like image selector)
    29. DBAttachmentPickerController
    30. BRImagePicker
    31. GLAssetGridViewController
    32. CreolePhotoSelection

    Swift
    1. LimPicker (Similar to WhatsApp's image picker)
    2. RMImagePicker
    3. DKImagePickerController
    4. BSImagePicker
    5. Fusuma(Instagram like image selector)
    6. YangMingShan(Yahoo like image selector)
    7. NohanaImagePicker
    8. ImagePicker
    9. OpalImagePicker
    10. TLPhotoPicker
    11. AssetsPickerViewController
    12. Alerts-and-pickers/Telegram Picker

    Thanx to @androidbloke,
    I have added some library that I know for multiple image picker in swift.
    Will update list as I find new ones.
    Thank You.

    Datatable vs Dataset

    There are some optimizations you can use when filling a DataTable, such as calling BeginLoadData(), inserting the data, then calling EndLoadData(). This turns off some internal behavior within the DataTable, such as index maintenance, etc. See this article for further details.

    Child element click event trigger the parent click event

    Without jQuery : DEMO

     <div id="parentDiv" onclick="alert('parentDiv');">
       <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
         AAA
       </div>   
    </div>
    

    How to run Ruby code from terminal?

    If Ruby is installed, then

    ruby yourfile.rb
    

    where yourfile.rb is the file containing the ruby code.

    Or

    irb
    

    to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

    How to force HTTPS using a web.config file

    A simple way is to tell IIS to send your custom error file for HTTP requests. The file can then contain a meta redirect, a JavaScript redirect and instructions with link, etc... Importantly, you can still check "Require SSL" for the site (or folder) and this will work.

    </configuration>
    </system.webServer>
        <httpErrors>
            <clear/>
            <!--redirect if connected without SSL-->
            <error statusCode="403" subStatusCode="4" path="errors\403.4_requiressl.html" responseMode="File"/>
        </httpErrors>
    </system.webServer>
    </configuration>
    

    Running an Excel macro via Python?

    I suspect you haven't authorize your Excel installation to run macro from an automated Excel. It is a security protection by default at installation. To change this:

    1. File > Options > Trust Center
    2. Click on Trust Center Settings... button
    3. Macro Settings > Check Enable all macros

    How to get current value of RxJS Subject or Observable?

    A Subject or Observable doesn't have a current value. When a value is emitted, it is passed to subscribers and the Observable is done with it.

    If you want to have a current value, use BehaviorSubject which is designed for exactly that purpose. BehaviorSubject keeps the last emitted value and emits it immediately to new subscribers.

    It also has a method getValue() to get the current value.

    simple custom event

    Like has been mentioned already the progress field needs the keyword event

    public event EventHandler<Progress> progress;
    

    But I don't think that's where you actually want your event. I think you actually want the event in TestClass. How does the following look? (I've never actually tried setting up static events so I'm not sure if the following will compile or not, but I think this gives you an idea of the pattern you should be aiming for.)

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            TestClass.progress += SetStatus;
        }
    
        private void SetStatus(object sender, Progress e)
        {
            label1.Text = e.Status;
        }
    
        private void button1_Click_1(object sender, EventArgs e)
        {
             TestClass.Func();
        }
    
     }
    
    public class TestClass
    {
        public static event EventHandler<Progress> progress; 
    
        public static void Func()
        {
            //time consuming code
            OnProgress(new Progress("current status"));
            // time consuming code
            OnProgress(new Progress("some new status"));            
        }
    
        private static void OnProgress(EventArgs e) 
        {
           if (progress != null)
              progress(this, e);
        }
    }
    
    
    public class Progress : EventArgs
    {
        public string Status { get; private set; }
    
        private Progress() {}
    
        public Progress(string status)
        {
            Status = status;
        }
    }
    

    How to get the size of a varchar[n] field in one SQL statement?

    select column_name, data_type, character_maximum_length    
    from INFORMATION_SCHEMA.COLUMNS
    where table_name = 'Table1'
    

    How Do I Upload Eclipse Projects to GitHub?

    While the EGit plugin for Eclipse is a good option, an even better one would be to learn to use git bash -- i.e., git from the command line. It isn't terribly difficult to learn the very basics of git, and it is often very beneficial to understand some basic operations before relying on a GUI to do it for you. But to answer your question:

    First things first, download git from http://git-scm.com/. Then go to http://github.com/ and create an account and repository.

    On your machine, first you will need to navigate to the project folder using git bash. When you get there you do:

    git init
    

    which initiates a new git repository in that directory.

    When you've done that, you need to register that new repo with a remote (where you'll upload -- push -- your files to), which in this case will be github. This assumes you have already created a github repository. You'll get the correct URL from your repo in GitHub.

    git remote add origin https://github.com/[username]/[reponame].git
    

    You need to add you existing files to your local commit:

    git add .   # this adds all the files
    

    Then you need to make an initial commit, so you do:

    git commit -a -m "Initial commit" # this stages your files locally for commit. 
                                      # they haven't actually been pushed yet
    

    Now you've created a commit in your local repo, but not in the remote one. To put it on the remote, you do the second line you posted:

    git push -u origin --all
    

    Autonumber value of last inserted row - MS Access / VBA

    If DAO use

    RS.Move 0, RS.LastModified
    lngID = RS!AutoNumberFieldName
    

    If ADO use

    cn.Execute "INSERT INTO TheTable.....", , adCmdText + adExecuteNoRecords
    Set rs = cn.Execute("SELECT @@Identity", , adCmdText)
    Debug.Print rs.Fields(0).Value
    

    cn being a valid ADO connection, @@Identity will return the last Identity (Autonumber) inserted on this connection.

    Note that @@Identity might be troublesome because the last generated value may not be the one you are interested in. For the Access database engine, consider a VIEW that joins two tables, both of which have the IDENTITY property, and you INSERT INTO the VIEW. For SQL Server, consider if there are triggers that in turn insert records into another table that also has the IDENTITY property.

    BTW DMax would not work as if someone else inserts a record just after you've inserted one but before your Dmax function finishes excecuting, then you would get their record.

    Count textarea characters

    $("#textarea").keyup(function(){
      $("#count").text($(this).val().length);
    });
    

    The above will do what you want. If you want to do a count down then change it to this:

    $("#textarea").keyup(function(){
      $("#count").text("Characters left: " + (500 - $(this).val().length));
    });
    

    Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks @Niet)

    document.getElementById('textarea').onkeyup = function () {
      document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
    };
    

    How to use Jackson to deserialise an array of objects

    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonFactory f = new JsonFactory();
        List<User> lstUser = null;
        JsonParser jp = f.createJsonParser(new File("C:\\maven\\user.json"));
        TypeReference<List<User>> tRef = new TypeReference<List<User>>() {};
        lstUser = mapper.readValue(jp, tRef);
        for (User user : lstUser) {
            System.out.println(user.toString());
        }
    
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    How to remove empty cells in UITableView?

    or you can call tableView method to set the footer height in 1 point, and it will add an last line, but you can hide it too, by setting footer background color.

    code:

    func tableView(tableView: UITableView,heightForFooterInSection section: Int) -> CGFloat {
         return 1
    }
    

    looks like last line

    TypeError: 'str' object is not callable (Python)

    it could be also you are trying to index in the wrong way:

    a = 'apple'
    a(3) ===> 'str' object is not callable
    
    a[3] = l
    

    Arrow operator (->) usage in C

    Well I have to add something as well. Structure is a bit different than array because array is a pointer and structure is not. So be careful!

    Lets say I write this useless piece of code:

    #include <stdio.h>
    
    typedef struct{
            int km;
            int kph;
            int kg;
        } car;
    
    int main(void){
    
        car audi = {12000, 230, 760};
        car *ptr = &audi;
    
    }
    

    Here pointer ptr points to the address (!) of the structure variable audi but beside address structure also has a chunk of data (!)! The first member of the chunk of data has the same address than structure itself and you can get it's data by only dereferencing a pointer like this *ptr (no braces).

    But If you want to acess any other member than the first one, you have to add a designator like .km, .kph, .kg which are nothing more than offsets to the base address of the chunk of data...

    But because of the preceedence you can't write *ptr.kg as access operator . is evaluated before dereference operator * and you would get *(ptr.kg) which is not possible as pointer has no members! And compiler knows this and will therefore issue an error e.g.:

    error: ‘ptr’ is a pointer; did you mean to use ‘->’?
      printf("%d\n", *ptr.km);
    

    Instead you use this (*ptr).kg and you force compiler to 1st dereference the pointer and enable acess to the chunk of data and 2nd you add an offset (designator) to choose the member.

    Check this image I made:

    enter image description here

    But if you would have nested members this syntax would become unreadable and therefore -> was introduced. I think readability is the only justifiable reason for using it as this ptr->kg is much easier to write than (*ptr).kg.

    Now let us write this differently so that you see the connection more clearly. (*ptr).kg ? (*&audi).kg ? audi.kg. Here I first used the fact that ptr is an "address of audi" i.e. &audi and fact that "reference" & and "dereference" * operators cancel eachother out.