Programs & Examples On #Application loader

Application Loader is a tool to help to prepare the applications for sale in the App Store.

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Following worked for me.

  1. Open another instance of Application Loader. ( Select "Application Loader" under the "Xcode -> Open Developer Tool" menu)

  2. "Agree" to the terms.

  3. After completing Step 2. First instance of Application Loader proceeded to the next step and build got submitted.

Omitting the second expression when using the if-else shorthand

Tiny addition to this very old thread..

If your'e evaluating an expression inside a for/while loop with a ternary operator, and want to continue or break as a result - you're gonna have a problem because both continue&break aren't expressions, they're statements without any value.

This will produce Uncaught SyntaxError: Unexpected token continue

 for (const item of myArray) {
      item.value ? break : continue;
 }

If you really want a one-liner that returns a statement, you can use this instead:

  for (const item of myArray) {
      if (item.value) break; else continue;
  }
  • P.S - This code might raise some eyebrows. Just saying.. :)

Trying to include a library, but keep getting 'undefined reference to' messages

If the .c source files are converted .cpp (like as in parsec), then the extern needs to be followed by "C" as in

extern "C" void foo();

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Set element focus in angular way

I prefered to use an expression. This lets me do stuff like focus on a button when a field is valid, reaches a certain length, and of course after load.

<button type="button" moo-focus-expression="form.phone.$valid">
<button type="submit" moo-focus-expression="smsconfirm.length == 6">
<input type="text" moo-focus-expression="true">

On a complex form this also reduces need to create additional scope variables for the purposes of focusing.

See https://stackoverflow.com/a/29963695/937997

Spark Dataframe distinguish columns with duplicated name

What worked for me

import databricks.koalas as ks

df1k = df1.to_koalas()
df2k = df2.to_koalas()
df3k = df1k.merge(df2k, on=['col1', 'col2'])
df3 = df3k.to_spark()

All of the columns except for col1 and col2 had "_x" appended to their names if they had come from df1 and "_y" appended if they had come from df2, which is exactly what I needed.

What is your single most favorite command-line trick using Bash?

You can use the watch command in conjunction with another command to look for changes. An example of this was when I was testing my router, and I wanted to get up-to-date numbers on stuff like signal-to-noise ratio, etc.

watch --interval=10 lynx -dump http://dslrouter/stats.html

getting only name of the class Class.getName()

Social.class.getSimpleName()

getSimpleName() : Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous. The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

Listing information about all database files in SQL Server

Executing following sql (It will only work when you don't have multiple mdf/ldf files for same database)

SELECT
    db.name AS DBName,
    (select mf.Physical_Name FROM sys.master_files mf where mf.type_desc = 'ROWS' and db.database_id = mf.database_id ) as DataFile,
    (select mf.Physical_Name FROM sys.master_files mf where mf.type_desc = 'LOG' and db.database_id = mf.database_id ) as LogFile
FROM sys.databases db

will return this output

DBName       DataFile                     LogFile
--------------------------------------------------------------------------------
master       C:\....\master.mdf           C:\....\mastlog.ldf
tempdb       C:\....\tempdb.mdf           C:\....\templog.ldf
model        C:\....\model.mdf            C:\....\modellog.ldf

and rest of the databases

If your TempDB's have multiple MDF's (like mine have), this script will fail. However, you can use

WHERE db.database_id > 4

at the end and it will return all databases except system databases.

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

Prior to standardization there was ioctl(...FIONBIO...) and fcntl(...O_NDELAY...), but these behaved inconsistently between systems, and even within the same system. For example, it was common for FIONBIO to work on sockets and O_NDELAY to work on ttys, with a lot of inconsistency for things like pipes, fifos, and devices. And if you didn't know what kind of file descriptor you had, you'd have to set both to be sure. But in addition, a non-blocking read with no data available was also indicated inconsistently; depending on the OS and the type of file descriptor the read may return 0, or -1 with errno EAGAIN, or -1 with errno EWOULDBLOCK. Even today, setting FIONBIO or O_NDELAY on Solaris causes a read with no data to return 0 on a tty or pipe, or -1 with errno EAGAIN on a socket. However 0 is ambiguous since it is also returned for EOF.

POSIX addressed this with the introduction of O_NONBLOCK, which has standardized behavior across different systems and file descriptor types. Because existing systems usually want to avoid any changes to behavior which might break backward compatibility, POSIX defined a new flag rather than mandating specific behavior for one of the others. Some systems like Linux treat all 3 the same, and also define EAGAIN and EWOULDBLOCK to the same value, but systems wishing to maintain some other legacy behavior for backward compatibility can do so when the older mechanisms are used.

New programs should use fcntl(...O_NONBLOCK...), as standardized by POSIX.

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

ORA-00054: resource busy and acquire with NOWAIT specified

When you killed the session, the session hangs around for a while in "KILLED" status while Oracle cleans up after it.

If you absolutely must, you can kill the OS process as well (look up v$process.spid), which would release any locks it was holding on to.

See this for more detailed info.

Overlay normal curve to histogram in R

Here's a nice easy way I found:

h <- hist(g, breaks = 10, density = 10,
          col = "lightgray", xlab = "Accuracy", main = "Overall") 
xfit <- seq(min(g), max(g), length = 40) 
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g)) 
yfit <- yfit * diff(h$mids[1:2]) * length(g) 

lines(xfit, yfit, col = "black", lwd = 2)

Switch with if, else if, else, and loops inside case

In this case, I'd recommend using break labels.

http://www.java-examples.com/break-statement

This way you can specifically call it outside of the for loop.

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

How to Insert Double or Single Quotes

If you save the Excel file as a CSV format file, you might find that the result is convenient to inserting into a database, though I'm not sure all of the fields would be quoted.

How can I compare a date and a datetime in Python?

I am trying to compare date which are in string format like '20110930'

benchMark = datetime.datetime.strptime('20110701', "%Y%m%d") 

actualDate = datetime.datetime.strptime('20110930', "%Y%m%d")

if actualDate.date() < benchMark.date():
    print True

Can not find the tag library descriptor of springframework

you have to add the dependency for springs mvc

tray adding that in your pom

<!-- mvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>

Get PostGIS version

PostGIS_Lib_Version(); - returns the version number of the PostGIS library.

http://postgis.refractions.net/docs/PostGIS_Lib_Version.html

How to install libusb in Ubuntu

Here is what worked for me.

Install the userspace USB programming library development files

sudo apt-get install libusb-1.0-0-dev
sudo updatedb && locate libusb.h

The path should appear as (or similar)

/usr/include/libusb-1.0/libusb.h

Include the header to your C code

#include <libusb-1.0/libusb.h>

Compile your C file

gcc -o example example.c -lusb-1.0

Best Practice: Access form elements by HTML id or name attribute?

Give your form an id only, and your input a name only:

<form id="myform">
  <input type="text" name="foo">

Then the most standards-compliant and least problematic way to access your input element is via:

document.getElementById("myform").elements["foo"]

using .elements["foo"] instead of just .foo is preferable because the latter might return a property of the form named "foo" rather than a HTML element!

input[type='text'] CSS selector does not apply to default-type text inputs?

By CSS specifications, browsers may or may not use information about default attributes; mostly the don’t. The relevant clause in the CSS 2.1 spec is 5.8.2 Default attribute values in DTDs. In CSS 3 Selectors, it’s clause 6.3.4, with the same name. It recommends: “Selectors should be designed so that they work whether or not the default values are included in the document tree.”

It is generally best to explicitly specify essential attributes such as type=text instead of defaulting them. The reason is that there is no simple reliable way to refer to the input elements with defaulted type attribute.

How to represent e^(-t^2) in MATLAB?

If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.

x = exp( -t.^2 )

or

x = exp( -t.*t )

How do you force a makefile to rebuild a target

make clean deletes all the already compiled object files.

What is a reasonable code coverage % for unit tests (and why)?

We were targeting >80% till few days back, But after we used a lot of Generated code, We do not care for %age, but rather make reviewer take a call on the coverage required.

Changing project port number in Visual Studio 2013

Well, I simply could not find this (for me) mythical "Use dynamic ports" option. I have post screenshots.

enter image description here

On a more constructive note, I believe that the port numbers are to be found in the solution file AND CRUCIALLY cross referenced against the IIS Express config file

C:\Users\<username>\Documents\IISExpress\config\applicationhost.config

I tried editing the port number in just the solution file but strange things happened. I propose (no time yet) that it needs a consistent edit across both the solution file and the config file.

In the shell, what does " 2>&1 " mean?

2 is the console standard error.

1 is the console standard output.

This is the standard Unix, and Windows also follows the POSIX.

E.g. when you run

perl test.pl 2>&1

the standard error is redirected to standard output, so you can see both outputs together:

perl test.pl > debug.log 2>&1

After execution, you can see all the output, including errors, in the debug.log.

perl test.pl 1>out.log 2>err.log

Then standard output goes to out.log, and standard error to err.log.

I suggest you to try to understand these.

What is the correct way to free memory in C#

Objects are eligable for garbage collection once they go out of scope become unreachable (thanks ben!). The memory won't be freed unless the garbage collector believes you are running out of memory.

For managed resources, the garbage collector will know when this is, and you don't need to do anything.

For unmanaged resources (such as connections to databases or opened files) the garbage collector has no way of knowing how much memory they are consuming, and that is why you need to free them manually (using dispose, or much better still the using block)

If objects are not being freed, either you have plenty of memory left and there is no need, or you are maintaining a reference to them in your application, and therefore the garbage collector will not free them (in case you actually use this reference you maintained)

Make Bootstrap's Carousel both center AND responsive?

Was having a very similar issue to this while using a CMS but it was not resolving with the above solution. What I did to solve it is put the following in the applicable css:

background-size: cover

and for placement purposes in case you are using bootstrap, I used:

background-position: center center /* or whatever position you wanted */

destination path already exists and is not an empty directory

Explanation

This is pretty vague but I'll do what I can to help.

First, while it may seem daunting at first, I suggest you learn how to do things from the command line (called terminal on OSX). This is a great way to make sure you're putting things where you really want to.

You should definitely google 'unix commands' to learn more, but here are a few important commands to help in this situation:

ls - list all files and directories (folders) in current directory

cd <input directory here without these brackets> - change directory, or change the folder you're looking in

mkdir <input directory name without brackets> - Makes a new directory (be careful, you will have to cd into the directory after you make it)

rm -r <input directory name without brackets> - Removes a directory and everything inside it

git clone <link to repo without brackets> - Clones the repository into the directory you are currently browsing.

Answer

So, on my computer, I would run the following commands to create a directory (folder) called projects within my documents folder and clone a repo there.

  1. Open terminal
  2. cd documents (Not case sensitive on mac)
  3. mkdir projects
  4. cd projects
  5. git clone https://github.com/seanbecker15/wherecanifindit.git
  6. cd wherecanifindit (if I want to go into the directory)

p.s. wherecanifindit is just the name of my git repository, not a command!

How to view transaction logs in SQL Server 2008

You can't read the transaction log file easily because that's not properly documented. There are basically two ways to do this. Using undocumented or semi-documented database functions or using third-party tools.

Note: This only makes sense if your database is in full recovery mode.

SQL Functions:

DBCC LOG and fn_dblog - more details here and here.

Third-party tools:

Toad for SQL Server and ApexSQL Log.

You can also check out several other topics where this was discussed:

Fatal error: Call to a member function query() on null

put this line in parent construct : $this->load->database();

function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..

How can I clear the Scanner buffer in Java?

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

Get the first item from an iterable that matches a condition

Oneliner:

thefirst = [i for i in range(10) if i > 3][0]

If youre not sure that any element will be valid according to the criteria, you should enclose this with try/except since that [0] can raise an IndexError.

How to delete a folder in C++?

The directory must be empty and your program must have permissions to delete it

but the function called rmdir will do it

rmdir("C:/Documents and Settings/user/Desktop/itsme") 

How to compare two lists in python?

a = ['a1','b2','c3']
b = ['a1','b2','c3']
c = ['b2','a1','c3']

# if you care about order
a == b # True
a == c # False

# if you don't care about order AND duplicates
set(a) == set(b) # True
set(a) == set(c) # True

By casting a, b and c as a set, you remove duplicates and order doesn't count. Comparing sets is also much faster and more efficient than comparing lists.

How to generate entire DDL of an Oracle schema (scriptable)?

If you want to individually generate ddl for each object,

Queries are:

--GENERATE DDL FOR ALL USER OBJECTS

--1. FOR ALL TABLES

SELECT DBMS_METADATA.GET_DDL('TABLE', TABLE_NAME) FROM USER_TABLES;

--2. FOR ALL INDEXES

SELECT DBMS_METADATA.GET_DDL('INDEX', INDEX_NAME) FROM USER_INDEXES WHERE INDEX_TYPE ='NORMAL';

--3. FOR ALL VIEWS

SELECT DBMS_METADATA.GET_DDL('VIEW', VIEW_NAME) FROM USER_VIEWS;

OR

SELECT TEXT FROM USER_VIEWS

--4. FOR ALL MATERILIZED VIEWS

SELECT QUERY FROM USER_MVIEWS

--5. FOR ALL FUNCTION

SELECT DBMS_METADATA.GET_DDL('FUNCTION', OBJECT_NAME) FROM USER_PROCEDURES WHERE OBJECT_TYPE = 'FUNCTION'

===============================================================================================

GET_DDL Function doesnt support for some object_type like LOB,MATERIALIZED VIEW, TABLE PARTITION

SO, Consolidated query for generating DDL will be:

SELECT OBJECT_TYPE, OBJECT_NAME,DBMS_METADATA.GET_DDL(OBJECT_TYPE, OBJECT_NAME, OWNER)
  FROM ALL_OBJECTS 
  WHERE (OWNER = 'XYZ') AND OBJECT_TYPE NOT IN('LOB','MATERIALIZED VIEW', 'TABLE PARTITION') ORDER BY OBJECT_TYPE, OBJECT_NAME;

When using SASS how can I import a file from a different directory?

To define the file to import it's possible to use all folders common definitions. You just have to be aware that it's relative to file you are defining it. More about import option with examples you can check here.

Prevent double submission of forms in jQuery

event.timeStamp doesn't work in Firefox. Returning false is non-standard, you should call event.preventDefault(). And while we're at it, always use braces with a control construct.

To sum up all of the previous answers, here is a plugin that does the job and works cross-browser.

jQuery.fn.preventDoubleSubmission = function() {

    var last_clicked, time_since_clicked;

    jQuery(this).bind('submit', function(event) {

        if(last_clicked) {
            time_since_clicked = jQuery.now() - last_clicked;
        }

        last_clicked = jQuery.now();

        if(time_since_clicked < 2000) {
            // Blocking form submit because it was too soon after the last submit.
            event.preventDefault();
        }

        return true;
    });
};

To address Kern3l, the timing method works for me simply because we're trying to stop a double-click of the submit button. If you have a very long response time to a submission, I recommend replacing the submit button or form with a spinner.

Completely blocking subsequent submissions of the form, as most of the above examples do, has one bad side-effect: if there is a network failure and they want to try to resubmit, they would be unable to do so and would lose the changes they made. This would definitely make an angry user.

The 'json' native gem requires installed build tools

My gem version 2.0.3 and I was getting the same issue. This command resolved it:

gem install json --platform=ruby --verbose

When is a C++ destructor called?

1) If the object is created via a pointer and that pointer is later deleted or given a new address to point to, does the object that it was pointing to call its destructor (assuming nothing else is pointing to it)?

It depends on the type of pointers. For example, smart pointers often delete their objects when they are deleted. Ordinary pointers do not. The same is true when a pointer is made to point to a different object. Some smart pointers will destroy the old object, or will destroy it if it has no more references. Ordinary pointers have no such smarts. They just hold an address and allow you to perform operations on the objects they point to by specifically doing so.

2) Following up on question 1, what defines when an object goes out of scope (not regarding to when an object leaves a given {block}). So, in other words, when is a destructor called on an object in a linked list?

That's up to the implementation of the linked list. Typical collections destroy all their contained objects when they are destroyed.

So, a linked list of pointers would typically destroy the pointers but not the objects they point to. (Which may be correct. They may be references by other pointers.) A linked list specifically designed to contain pointers, however, might delete the objects on its own destruction.

A linked list of smart pointers could automatically delete the objects when the pointers are deleted, or do so if they had no more references. It's all up to you to pick the pieces that do what you want.

3) Would you ever want to call a destructor manually?

Sure. One example would be if you want to replace an object with another object of the same type but don't want to free memory just to allocate it again. You can destroy the old object in place and construct a new one in place. (However, generally this is a bad idea.)

// pointer is destroyed because it goes out of scope,
// but not the object it pointed to. memory leak
if (1) {
 Foo *myfoo = new Foo("foo");
}


// pointer is destroyed because it goes out of scope,
// object it points to is deleted. no memory leak
if(1) {
 Foo *myfoo = new Foo("foo");
 delete myfoo;
}

// no memory leak, object goes out of scope
if(1) {
 Foo myfoo("foo");
}

How do I install boto?

  1. If necessary, install pip:

    sudo apt-get install python-pip

  2. Then install boto:

    pip install -U boto

What is the best way to implement constants in Java?

To take it a step further, you can place globally used constants in an interface so they can be used system wide. E.g.

public interface MyGlobalConstants {
    public static final int TIMEOUT_IN_SECS = 25;
}

But don't then implement it. Just refer to them directly in code via the fully qualified classname.

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

The operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value.

Examples:

1 === 1: true
1 == 1: true
1 === "1": false // 1 is an integer, "1" is a string
1 == "1": true // "1" gets casted to an integer, which is 1
"foo" === "foo": true // both operands are strings and have the same value

Warning: two instances of the same class with equivalent members do NOT match the === operator. Example:

$a = new stdClass();
$a->foo = "bar";
$b = clone $a;
var_dump($a === $b); // bool(false)

Draw text in OpenGL ES

The Android SDK doesn't come with any easy way to draw text on OpenGL views. Leaving you with the following options.

  1. Place a TextView over your SurfaceView. This is slow and bad, but the most direct approach.
  2. Render common strings to textures, and simply draw those textures. This is by far the simplest and fastest, but the least flexible.
  3. Roll-your-own text rendering code based on a sprite. Probably second best choice if 2 isn't an option. A good way to get your feet wet but note that while it seems simple (and basic features are), it get's harder and more challenging as you add more features (texture-alignment, dealing with line-breaks, variable-width fonts etc.) - if you take this route, make it as simple as you can get away with!
  4. Use an off-the-shelf/open-source library. There are a few around if you hunt on Google, the tricky bit is getting them integrated and running. But at least, once you do that, you'll have all the flexibility and maturity they provide.

How to use GROUP_CONCAT in a CONCAT in MySQL

 SELECT id, GROUP_CONCAT(CONCAT_WS(':', Name, CAST(Value AS CHAR(7))) SEPARATOR ',') AS result 
    FROM test GROUP BY id

you must use cast or convert, otherwise will be return BLOB

result is

id         Column
1          A:4,A:5,B:8
2          C:9

you have to handle result once again by program such as python or java

How to parse JSON data with jQuery / JavaScript?

var jsonP = "person" : [ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ];

var cand = document.getElementById("cand");
var json_arr = [];
$.each(jsonP.person,function(key,value){
    json_arr.push(key+' . '+value.name  + '<br>');
    cand.innerHTML = json_arr;
});

<div id="cand">
</div>

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

List of remotes for a Git repository?

A simple way to see remote branches is:

git branch -r

To see local branches:

git branch -l

There are No resources that can be added or removed from the server

I didn't find the Dynamic Web Module option when I clicked on the link, then I have installed Maven(Java EE) Integration for Eclipse WTP from the Eclipse Marketplace.Then, the above steps worked.

Convert from enum ordinal to enum type

So one way is to doExampleEnum valueOfOrdinal = ExampleEnum.values()[ordinal]; which works and its easy, however, as mentioned before, ExampleEnum.values() returns a new cloned array for every call. That can be unnecessarily expensive. We can solve that by caching the array like so ExampleEnum[] values = values(). It is also "dangerous" to allow our cached array to be modified. Someone could write ExampleEnum.values[0] = ExampleEnum.type2; So I would make it private with an accessor method that does not do extra copying.

private enum ExampleEnum{
    type0, type1, type2, type3;
    private static final ExampleEnum[] values = values();
    public static ExampleEnum value(int ord) {
        return values[ord];
    }
}

You would use ExampleEnum.value(ordinal) to get the enum value associated with ordinal

How do I run a node.js app as a background service?

If you are running OSX, then the easiest way to produce a true system process is to use launchd to launch it.

Build a plist like this, and put it into the /Library/LaunchDaemons with the name top-level-domain.your-domain.application.plist (you need to be root when placing it):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>top-level-domain.your-domain.application</string>

    <key>WorkingDirectory</key>
    <string>/your/preferred/workingdirectory</string>

    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/node</string>
        <string>your-script-file</string>
    </array>

    <key>RunAtLoad</key>
    <true/>

    <key>KeepAlive</key>
    <true/>

</dict>
</plist>

When done, issue this (as root):

launchctl load /Library/LaunchDaemons/top-level-domain.your-domain.application.plist
launchctl start top-level-domain.your-domain.application

and you are running.

And you will still be running after a restart.

For other options in the plist look at the man page here: https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man5/launchd.plist.5.html

React - clearing an input value after form submit

this.mainInput doesn't actually point to anything. Since you are using a controlled component (i.e. the value of the input is obtained from state) you can set this.state.city to null:

onHandleSubmit(e) {
  e.preventDefault();
  const city = this.state.city;
  this.props.onSearchTermChange(city);
  this.setState({ city: '' });
}

How can I roll back my last delete command in MySQL?

The accepted answer is not always correct. If you configure binary logging on MySQL, you can rollback the database to any previous point you still have a snapshot and binlog for.

7.5 Point-in-Time (Incremental) Recovery Using the Binary Log is a good starting point for learning about this facility.

How to write a:hover in inline CSS?

I agree with shadow. You could use the onmouseover and onmouseout event to change the CSS via JavaScript.

And don't say people need to have JavaScript activated. It's only a style issue, so it doesn't matter if there are some visitors without JavaScript ;) Although most of Web 2.0 works with JavaScript. See Facebook for example (lots of JavaScript) or Myspace.

Execute CMD command from code

Here's a simple example :

Process.Start("cmd","/C copy c:\\file.txt lpt1");

How to get full file path from file name?

You can get the current path:

string AssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();

Good luck!

Tuple unpacking in for loops

Enumerate basically gives you an index to work with in the for loop. So:

for i,a in enumerate([4, 5, 6, 7]):
    print i, ": ", a

Would print:

0: 4
1: 5
2: 6
3: 7

Sum of values in an array using jQuery

In http://bugs.jquery.com/ticket/1886 it becomes obvious that the jQuery devs have serious mental issues reg. functional programming inspired additions. Somehow it's good to have some fundamental things (like map) but not others (like reduce), unless it reduces jQuery's overall filesize. Go figure.

Helpfully, someone placed code to use the normal reduce function for jQuery arrays:

$.fn.reduce = [].reduce;

Now we can use a simple reduce function to create a summation:

//where X is a jQuery array
X.reduce(function(a,b){ return a + b; });
// (change "a" into parseFloat("a") if the first a is a string)

Lastly, as some older browsers hadn't yet implemented reduce, a polyfill can be taken from MDN (it's big but I guess it has the exact same behavior, which is desirable):

if ( 'function' !== typeof Array.prototype.reduce ) {
    Array.prototype.reduce = function( callback /*, initialValue*/ ) {
        'use strict';
        if ( null === this || 'undefined' === typeof this ) {
          throw new TypeError(
             'Array.prototype.reduce called on null or undefined' );
        }
        if ( 'function' !== typeof callback ) {
          throw new TypeError( callback + ' is not a function' );
        }
        var t = Object( this ), len = t.length >>> 0, k = 0, value;
        if ( arguments.length >= 2 ) {
          value = arguments[1];
        } else {
          while ( k < len && ! k in t ) k++; 
          if ( k >= len )
            throw new TypeError('Reduce of empty array with no initial value');
          value = t[ k++ ];
        }
        for ( ; k < len ; k++ ) {
          if ( k in t ) {
             value = callback( value, t[k], k, t );
          }
        }
        return value;
      };
    }

Python pandas: fill a dataframe row by row

If your input rows are lists rather than dictionaries, then the following is a simple solution:

import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])

pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
#    A  B  C
# 0  1  2  3
# 1  4  5  6

What exactly is a Context in Java?

In programming terms, it's the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.

In some API's you see this name back in an interface/class, e.g. Servlet's ServletContext, JSF's FacesContext, Spring's ApplicationContext, Android's Context, JNDI's InitialContext, etc. They all often follow the Facade Pattern which abstracts the environmental details the enduser doesn't need to know about away in a single interface/class.

Difference between UTF-8 and UTF-16?

They're simply different schemes for representing Unicode characters.

Both are variable-length - UTF-16 uses 2 bytes for all characters in the basic multilingual plane (BMP) which contains most characters in common use.

UTF-8 uses between 1 and 3 bytes for characters in the BMP, up to 4 for characters in the current Unicode range of U+0000 to U+1FFFFF, and is extensible up to U+7FFFFFFF if that ever becomes necessary... but notably all ASCII characters are represented in a single byte each.

For the purposes of a message digest it won't matter which of these you pick, so long as everyone who tries to recreate the digest uses the same option.

See this page for more about UTF-8 and Unicode.

(Note that all Java characters are UTF-16 code points within the BMP; to represent characters above U+FFFF you need to use surrogate pairs in Java.)

TypeScript: Property does not exist on type '{}'

myFunction(
        contextParamers : {
            param1: any,
            param2: string
            param3: string          
        }){
          contextParamers.param1 = contextParamers.param1+ 'canChange';
          //contextParamers.param4 = "CannotChange";
          var contextParamers2 : any = contextParamers;// lost the typescript on the new object of type any
          contextParamers2.param4 =  'canChange';
          return contextParamers2;
      }

Push items into mongo array via mongoose

The $push operator appends a specified value to an array.

{ $push: { <field1>: <value1>, ... } }

$push adds the array field with the value as its element.

Above answer fulfils all the requirements, but I got it working by doing the following

var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
Friend.findOneAndUpdate(
   { _id: req.body.id }, 
   { $push: { friends: objFriends  } },
  function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });
)

how to open a url in python

On window

import os
os.system("start \"\" https://example.com")

On macOS

import os
os.system("open \"\" https://example.com")

On Linux

import os
os.system("xdg-open \"\" https://example.com")

Cross-Platform

import webbrowser

webbrowser.open('https://example.com')

Restore the mysql database from .frm files

I made use of mysqlfrm which is a great tool which generates table creation sql code from .frm files. I was getting this nasty table not found error although tables were being listed. Thus I used this tool to regenerate the tables. In ubuntu you need to install this as:

sudo apt install mysql-utilities

then,

mysqlfrm --diagnostic mysql/db_name/ > db_name.sql

Create a new database and then you can use,

mysql -u username -p < db_name.sql

However, this will give you the tables but not the data. In my case this was enough.

Finding the number of days between two dates

If you're using PHP 5.3 >, this is by far the most accurate way of calculating the difference:

$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");

$diff = $later->diff($earlier)->format("%a");

Storing Form Data as a Session Variable

You can solve this problem using this code:

if(!empty($_GET['variable from which you get'])) 
{
$_SESSION['something']= $_GET['variable from which you get'];
}

So you get the variable from a GET form, you will store in the $_SESSION['whatever'] variable just once when $_GET['variable from which you get']is set and if it is empty $_SESSION['something'] will store the old parameter

post ajax data to PHP and return data

 $.ajax({
            type: "POST",
            data: {data:the_id},
            url: "http://localhost/test/index.php/data/count_votes",
            success: function(data){
               //data will contain the vote count echoed by the controller i.e.  
                 "yourVoteCount"
              //then append the result where ever you want like
              $("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller

                }
            });

in the controller

$data = $_POST['data'];  //$data will contain the_id
//do some processing
echo "yourVoteCount";

Clarification

i think you are confusing

{data:the_id}

with

success:function(data){

both the data are different for your own clarity sake you can modify it as

success:function(vote_count){
$(span#someId).html(vote_count);

Error in contrasts when defining a linear model in R

Metrics and Svens answer deals with the usual situation but for us who work in non-english enviroments if you have exotic characters (å,ä,ö) in your character variable you will get the same result, even if you have multiple factor levels.

Levels <- c("Pri", "För") gives the contrast error, while Levels <- c("Pri", "For") doesn't

This is probably a bug.

Error while installing json gem 'mkmf.rb can't find header files for ruby'

I had a similar problem using cygwin to run the following command:

$ gem install rerun

I solved it by installing the following cygwin packages:

  • ruby-devel
  • libffi-devel
  • gcc-core
  • gcc-g++
  • make
  • automake1.15

Assign one struct to another in C

Yes, you can assign one instance of a struct to another using a simple assignment statement.

  • In the case of non-pointer or non pointer containing struct members, assignment means copy.

  • In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.

Let us see this first hand:

#include <stdio.h>

struct Test{
    int foo;
    char *bar;
};

int main(){
    struct Test t1;
    struct Test t2;
    t1.foo = 1;
    t1.bar = malloc(100 * sizeof(char));
    strcpy(t1.bar, "t1 bar value");
    t2.foo = 2;
    t2.bar = malloc(100 * sizeof(char));
    strcpy(t2.bar, "t2 bar value");
    printf("t2 foo and bar before copy: %d %s\n", t2.foo, t2.bar);
    t2 = t1;// <---- ASSIGNMENT
    printf("t2 foo and bar after copy: %d %s\n", t2.foo, t2.bar);
    //The following 3 lines of code demonstrate that foo is deep copied and bar is shallow copied
    strcpy(t1.bar, "t1 bar value changed");
    t1.foo = 3;
    printf("t2 foo and bar after t1 is altered: %d %s\n", t2.foo, t2.bar);
    return 0;
}

Open file by its full path in C++

You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.

#include <fstream>
#include <iostream>
using namespace std;

int main() {
   ifstream ifs( "c:/demo.txt" );       // note no mode needed
   if ( ! ifs.is_open() ) {                 
      cout <<" Failed to open" << endl;
   }
   else {
      cout <<"Opened OK" << endl;
   }
}

What does this code produce on your system?

How can I reference a dll in the GAC from Visual Studio?

Registering assmblies into the GAC does not then place a reference to the assembly in the add references dialog. You still need to reference the assembly by path for your project, the main difference being you do not need to use the copy local option, your app will find it at runtime.

In this particular case, you just need to reference your assembly by path (browse) or if you really want to have it in the add reference dialog there is a registry setting where you can add additional paths.

Note, if you ship your app to someone who does not have this assembly installed you will need to ship it, and in this case you really need to use the SharedManagementObjects.msi redistributable.

SqlDataAdapter vs SqlDataReader

DataReader:

  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database

On the other hand, it:

  • Only has one record in memory at a time rather than an entire result set (this can be HUGE)
  • Is about as fast as you can get for that one iteration
  • Allows you start processing results sooner (once the first record is available). For some query types this can also be a very big deal.

DataAdapter/DataSet

  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database

At the cost of:

  • Much higher memory use
  • You wait until all the data is loaded before using any of it

So really it depends on what you're doing, but I tend to prefer a DataReader until I need something that's only supported by a dataset. SqlDataReader is perfect for the common data access case of binding to a read-only grid.

For more info, see the official Microsoft documentation.

How to get Android GPS location

Worked a day for this project. It maybe useful for u. I compressed and combined both Network and GPS. Plug and play directly in MainActivity.java (There are some DIY function for display result)

 ///////////////////////////////////
////////// LOCATION PACK //////////
// 
//  locationManager: (LocationManager) for getting LOCATION_SERVICE
//  osLocation: (Location) getting location data via standard method
//  dataLocation: class type storage locztion data
//    x,y: (Double) Longtitude, Latitude
//  location: (dataLocation) variable contain absolute location info. Autoupdate after run locationStart();
//  AutoLocation: class help getting provider info
//  tmLocation: (Timer) for running update location over time
//  LocationStart(int interval): start getting location data with setting interval time cycle in milisecond
//  LocationStart(): LocationStart(500)
//  LocationStop(): stop getting location data
//
//  EX:
//    LocationStart(); cycleF(new Runnable() {public void run(){bodyM.text("LOCATION \nLatitude: " + location.y+ "\nLongitude: " + location.x).show();}},500);
//

LocationManager locationManager;
Location osLocation;
public class dataLocation {double x,y;}
dataLocation location=new dataLocation();
public class AutoLocation extends Activity implements LocationListener {
    @Override public void onLocationChanged(Location p1){}
    @Override public void onStatusChanged(String p1, int p2, Bundle p3){}
    @Override public void onProviderEnabled(String p1){}
    @Override public void onProviderDisabled(String p1){}
    public Location getLocation(String provider) {
        if (locationManager.isProviderEnabled(provider)) {
            locationManager.requestLocationUpdates(provider,0,0,this);
            if (locationManager != null) {
                osLocation = locationManager.getLastKnownLocation(provider);
                return osLocation;
            }
        }
        return null;
    }
}
Timer tmLocation=new Timer();
public void LocationStart(int interval){
    locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
    final AutoLocation autoLocation = new AutoLocation();
    tmLocation=cycleF(new Runnable() {public void run(){ 
                Location nwLocation = autoLocation.getLocation(LocationManager.NETWORK_PROVIDER);
                if (nwLocation != null) {
                    location.y = nwLocation.getLatitude();
                    location.x = nwLocation.getLongitude();
                } else {
                    //bodym.text("NETWORK_LOCATION is loading...").show();
                }
                Location gpsLocation = autoLocation.getLocation(LocationManager.GPS_PROVIDER);
                if (gpsLocation != null) {
                    location.y = gpsLocation.getLatitude();
                    location.x = gpsLocation.getLongitude();    
                } else {
                    //bodym.text("GPS_LOCATION is loading...").show();
                }   
            }}, interval);
}
public void LocationStart(){LocationStart(500);};
public void LocationStop(){stopCycleF(tmLocation);}

//////////
///END//// LOCATION PACK //////////
//////////


/////////////////////////////
////////// RUNTIME //////////
//
// Need library:
//  import java.util.*;
//
// delayF(r,d): execute runnable r after d millisecond
//   Halt by execute the return: final Runnable rn=delayF(...); (new Handler()).post(rn);
// cycleF(r,i): execute r repeatedly with i millisecond each cycle
// stopCycleF(t): halt execute cycleF via the Timer return of cycleF
// 
// EX:
//   delayF(new Runnable(){public void run(){ sig("Hi"); }},2000);
//   final Runnable rn=delayF(new Runnable(){public void run(){ sig("Hi"); }},3000);
//     delayF(new Runnable(){public void run(){ (new Handler()).post(rn);sig("Hello"); }},1000);
//   final Timer tm=cycleF(new Runnable() {public void run(){ sig("Neverend"); }}, 1000);
//     delayF(new Runnable(){public void run(){ stopCycleF(tm);sig("Ended"); }},7000);
//
public static Runnable delayF(final Runnable r, long delay) {
    final Handler h = new Handler();
    h.postDelayed(r, delay);
    return new Runnable(){
        @Override
        public void run(){h.removeCallbacks(r);}
    };
}
public static Timer cycleF(final Runnable r, long interval) {
    final Timer t=new Timer();
    final Handler h = new Handler();
    t.scheduleAtFixedRate(new TimerTask() {
            public void run() {h.post(r);}
        }, interval, interval);
    return t;
}
public void stopCycleF(Timer t){t.cancel();t.purge();}
public boolean serviceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
//////////
///END//// RUNTIME //////////
//////////

Find the PID of a process that uses a port on Windows

Find the PID of a process that uses a port on Windows (e.g. port: "9999")

netstat -aon | find "9999"

-a Displays all connections and listening ports.

-o Displays the owning process ID associated with each connection.

-n Displays addresses and port numbers in numerical form.

Output:

TCP    0.0.0.0:9999       0.0.0.0:0       LISTENING       15776

Then kill the process by PID

taskkill /F /PID 15776

/F - Specifies to forcefully terminate the process(es).

Note: You may need an extra permission (run from administrator) to kill some certain processes

Select Pandas rows based on list index

ind_list = [1, 3]
df.ix[ind_list]

should do the trick! When I index with data frames I always use the .ix() method. Its so much easier and more flexible...

UPDATE This is no longer the accepted method for indexing. The ix method is deprecated. Use .iloc for integer based indexing and .loc for label based indexing.

AttributeError: Module Pip has no attribute 'main'

Pip 10.0.* doesn't support main.

You have to downgrade to pip 9.0.3.

Closing Bootstrap modal onclick

Close the modal with universal $().hide() method:

$('#product-options').hide();

How to turn a String into a JavaScript function call?

JavaScript has an eval function that evaluates a string and executes it as code:

eval(settings.functionName + '(' + t.parentNode.id + ')');

How to beautify JSON in Python?

A minimal in-python solution that colors json data supplied via the command line:

import sys
import json
from pygments import highlight, lexers, formatters

formatted_json = json.dumps(json.loads(sys.argv[1]), indent=4)
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)

Inspired by pjson mentioned above. This code needs pygments to be installed.

Output example:

enter image description here

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

You can use npm link to create a symbolic link to your global package in your projects folder.

Example:

$ npm install -g express
$ cd [local path]/project
$ npm link express

All it does is create a local node_modules folder and then create a symlink express -> [global directory]/node_modules/express which can then be resolved by require('express')

How to convert timestamp to datetime in MySQL?

Use the FROM_UNIXTIME() function in MySQL

Remember that if you are using a framework that stores it in milliseconds (for example Java's timestamp) you have to divide by 1000 to obtain the right Unix time in seconds.

Error - is not marked as serializable

Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:

Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable

Due to a class with an attribute IEnumerable<int> eg:

[Serializable]
class MySessionData{
    public int ID;
    public IEnumerable<int> RelatedIDs; //This can be an issue
}

Originally the problem instance of MySessionData was set from a non-serializable list:

MySessionData instance = new MySessionData(){ 
    ID = 123,
    RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};

The cause here is the concrete class that the Select<int>(...) returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int> to resolve it.

RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();

How to test valid UUID/GUID?

A good way to do it in Node is to use the ajv package (https://github.com/epoberezkin/ajv).

const Ajv = require('ajv');
const ajv = new Ajv({ allErrors: true, useDefaults: true, verbose: true });
const uuidSchema = { type: 'string', format: 'uuid' };
ajv.validate(uuidSchema, 'bogus'); // returns false
ajv.validate(uuidSchema, 'd42a8273-a4fe-4eb2-b4ee-c1fc57eb9865'); // returns true with v4 GUID
ajv.validate(uuidSchema, '892717ce-3bd8-11ea-b77f-2e728ce88125'); // returns true with a v1 GUID

How do I generate a stream from a string?

A good combination of String extensions:

public static byte[] GetBytes(this string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

public static Stream ToStream(this string str)
{
    Stream StringStream = new MemoryStream();
    StringStream.Read(str.GetBytes(), 0, str.Length);
    return StringStream;
}

How to convert an int array to String with toString method in Java

Using the utility I describe here, you can have a more control over the string representation you get for your array.

String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString();                 // gives "hello, world"
r.mkString(" | ");            // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"

Where can I find "make" program for Mac OS X Lion?

After upgrading to Mountain Lion using the NDK, I had the following error:

Cannot find 'make' program. Please install Cygwin make package or define the GNUMAKE variable to point to it

Error was fixed by downloading and using the latest NDK

Can’t delete docker image with dependent child images

You should try to remove unnecessary images before removing the image:

docker rmi $(docker images --filter "dangling=true" -q --no-trunc)

After that, run:

docker rmi c565603bc87f

Base64 encoding in SQL Server 2005 T-SQL

You can use just:

Declare @pass2 binary(32)
Set @pass2 =0x4D006A00450034004E0071006B00350000000000000000000000000000000000
SELECT CONVERT(NVARCHAR(16), @pass2)

then after encoding you'll receive text 'MjE4Nqk5'

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

Try installing this, it's a known workaround for enabling the C++ compiler for Python 2.7.

In my experience, when pip does not find vcvarsall.bat compiler, all I do is opening a Visual Studio console as it set the path variables to call vcvarsall.bat directly and then I run pip on this command line.

Get the year from specified date php

Assuming you have the date as a string (sorry it was unclear from your question if that is the case) could split the string on the - characters like so:

$date = "2068-06-15";
$split_date = split("-", $date);
$year = $split_date[0];

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

Using WAMP is perforce option if we want to use more then one version of php.

Find a value in an array of objects in Javascript

As per ECMAScript 6, you can use the findIndex function.

array[array.findIndex(x => x.name == 'string 1')]

Insert content into iFrame

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

See here [srcdoc]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

See here [sandbox]: https://www.w3schools.com/tags/att_iframe_sandbox.asp

What is the difference between 'E', 'T', and '?' for Java generics?

A type variable, <T>, can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

The most commonly used type parameter names are:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value

In Java 7 it is permitted to instantiate like this:

Foo<String, Integer> foo = new Foo<>(); // Java 7
Foo<String, Integer> foo = new Foo<String, Integer>(); // Java 6

how do I initialize a float to its max/min value?

You can use std::numeric_limits which is defined in <limits> to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a - in front for negative infinity).

#include <limits>

//...

std::numeric_limits<float>::max();
std::numeric_limits<float>::min();
std::numeric_limits<float>::infinity();

As noted in the comments, min() returns the lowest possible positive value. In other words the positive value closest to 0 that can be represented. The lowest possible value is the negative of the maximum possible value.

There is of course the std::max_element and min_element functions (defined in <algorithm>) which may be a better choice for finding the largest or smallest value in an array.

Display text from .txt file in batch file

@echo off
set log=%time% %date%
echo %log%

That is a batch for saving the date and time as a temporary variable, and displaying it. In a hurry, I don't have time to write a script to open a txt, maybe later.

iOS - Build fails with CocoaPods cannot find header files

I have got the same problem, but the above solutions can't work. I have fixed it by doing this:

  1. Remove the whole project
  2. Run git clone the project and run the bundle exec pod install
  3. cd the peoject and run remote add upstream your-remote-rep-add
  4. git fetch upstream
  5. git checkout master
  6. git merge upstream/master

And then it works.

input() error - NameError: name '...' is not defined

You could either do:

x = raw_input("enter your name")
print "your name is %s " % x

or:

x = str(input("enter your name"))
print "your name is %s" % x

Numpy - add row to array

As this question is been 7 years before, in the latest version which I am using is numpy version 1.13, and python3, I am doing the same thing with adding a row to a matrix, remember to put a double bracket to the second argument, otherwise, it will raise dimension error.

In here I am adding on matrix A

1 2 3
4 5 6

with a row

7 8 9

same usage in np.r_

A= [[1, 2, 3], [4, 5, 6]]
np.append(A, [[7, 8, 9]], axis=0)

    >> array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
#or 
np.r_[A,[[7,8,9]]]

Just to someone's intersted, if you would like to add a column,

array = np.c_[A,np.zeros(#A's row size)]

following what we did before on matrix A, adding a column to it

np.c_[A, [2,8]]

>> array([[1, 2, 3, 2],
          [4, 5, 6, 8]])

Correct format specifier for double in printf

"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).


1. C99, §6.5.2.2/6: "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions." In C++ the wording is somewhat different (e.g., it doesn't use the word "prototype") but the effect is the same: all the variadic parameters undergo default promotions before they're received by the function.

How to parse a CSV in a Bash script?

A sed or awk solution would probably be shorter, but here's one for Perl:

perl -F/,/ -ane 'print if $F[<INDEX>] eq "<VALUE>"`

where <INDEX> is 0-based (0 for first column, 1 for 2nd column, etc.)

Is it possible to start activity through adb shell?

eg:

MyPackageName is com.example.demo

MyActivityName is com.example.test.MainActivity

adb shell am start -n com.example.demo/com.example.test.MainActivity

@Media min-width & max-width

I've found the best method is to write your default CSS for the older browsers, as older browsers including i.e. 5.5, 6, 7 and 8. Can't read @media. When I use @media I use it like this:

<style type="text/css">
    /* default styles here for older browsers. 
       I tend to go for a 600px - 960px width max but using percentages
    */
    @media only screen and (min-width: 960px) {
        /* styles for browsers larger than 960px; */
    }
    @media only screen and (min-width: 1440px) {
        /* styles for browsers larger than 1440px; */
    }
    @media only screen and (min-width: 2000px) {
        /* for sumo sized (mac) screens */
    }
    @media only screen and (max-device-width: 480px) {
       /* styles for mobile browsers smaller than 480px; (iPhone) */
    }
    @media only screen and (device-width: 768px) {
       /* default iPad screens */
    }
    /* different techniques for iPad screening */
    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
      /* For portrait layouts only */
    }

    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
      /* For landscape layouts only */
    }
</style>

But you can do whatever you like with your @media, This is just an example of what I've found best for me when building styles for all browsers.

iPad CSS specifications.

Also! If you're looking for printability you can use @media print{}

What are the default color values for the Holo theme on Android 4.0?

If you want the default colors of Android ICS, you just have to go to your Android SDK and look for this path: platforms\android-15\data\res\values\colors.xml.

Here you go:

<!-- For holo theme -->
    <drawable name="screen_background_holo_light">#fff3f3f3</drawable>
    <drawable name="screen_background_holo_dark">#ff000000</drawable>
    <color name="background_holo_dark">#ff000000</color>
    <color name="background_holo_light">#fff3f3f3</color>
    <color name="bright_foreground_holo_dark">@android:color/background_holo_light</color>
    <color name="bright_foreground_holo_light">@android:color/background_holo_dark</color>
    <color name="bright_foreground_disabled_holo_dark">#ff4c4c4c</color>
    <color name="bright_foreground_disabled_holo_light">#ffb2b2b2</color>
    <color name="bright_foreground_inverse_holo_dark">@android:color/bright_foreground_holo_light</color>
    <color name="bright_foreground_inverse_holo_light">@android:color/bright_foreground_holo_dark</color>
    <color name="dim_foreground_holo_dark">#bebebe</color>
    <color name="dim_foreground_disabled_holo_dark">#80bebebe</color>
    <color name="dim_foreground_inverse_holo_dark">#323232</color>
    <color name="dim_foreground_inverse_disabled_holo_dark">#80323232</color>
    <color name="hint_foreground_holo_dark">#808080</color>
    <color name="dim_foreground_holo_light">#323232</color>
    <color name="dim_foreground_disabled_holo_light">#80323232</color>
    <color name="dim_foreground_inverse_holo_light">#bebebe</color>
    <color name="dim_foreground_inverse_disabled_holo_light">#80bebebe</color>
    <color name="hint_foreground_holo_light">#808080</color>
    <color name="highlighted_text_holo_dark">#6633b5e5</color>
    <color name="highlighted_text_holo_light">#6633b5e5</color>
    <color name="link_text_holo_dark">#5c5cff</color>
    <color name="link_text_holo_light">#0000ee</color>

This for the Background:

<color name="background_holo_dark">#ff000000</color>
<color name="background_holo_light">#fff3f3f3</color>

You won't get the same colors if you look this up in Photoshop etc. because they are set up with Alpha values.

Update for API Level 19:

<resources>
    <drawable name="screen_background_light">#ffffffff</drawable>
    <drawable name="screen_background_dark">#ff000000</drawable>
    <drawable name="status_bar_closed_default_background">#ff000000</drawable>
    <drawable name="status_bar_opened_default_background">#ff000000</drawable>
    <drawable name="notification_item_background_color">#ff111111</drawable>
    <drawable name="notification_item_background_color_pressed">#ff454545</drawable>
    <drawable name="search_bar_default_color">#ff000000</drawable>
    <drawable name="safe_mode_background">#60000000</drawable>
    <!-- Background drawable that can be used for a transparent activity to
         be able to display a dark UI: this darkens its background to make
         a dark (default theme) UI more visible. -->
    <drawable name="screen_background_dark_transparent">#80000000</drawable>
    <!-- Background drawable that can be used for a transparent activity to
         be able to display a light UI: this lightens its background to make
         a light UI more visible. -->
    <drawable name="screen_background_light_transparent">#80ffffff</drawable>
    <color name="safe_mode_text">#80ffffff</color>
    <color name="white">#ffffffff</color>
    <color name="black">#ff000000</color>
    <color name="transparent">#00000000</color>
    <color name="background_dark">#ff000000</color>
    <color name="background_light">#ffffffff</color>
    <color name="bright_foreground_dark">@android:color/background_light</color>
    <color name="bright_foreground_light">@android:color/background_dark</color>
    <color name="bright_foreground_dark_disabled">#80ffffff</color>
    <color name="bright_foreground_light_disabled">#80000000</color>
    <color name="bright_foreground_dark_inverse">@android:color/bright_foreground_light</color>
    <color name="bright_foreground_light_inverse">@android:color/bright_foreground_dark</color>
    <color name="dim_foreground_dark">#bebebe</color>
    <color name="dim_foreground_dark_disabled">#80bebebe</color>
    <color name="dim_foreground_dark_inverse">#323232</color>
    <color name="dim_foreground_dark_inverse_disabled">#80323232</color>
    <color name="hint_foreground_dark">#808080</color>
    <color name="dim_foreground_light">#323232</color>
    <color name="dim_foreground_light_disabled">#80323232</color>
    <color name="dim_foreground_light_inverse">#bebebe</color>
    <color name="dim_foreground_light_inverse_disabled">#80bebebe</color>
    <color name="hint_foreground_light">#808080</color>
    <color name="highlighted_text_dark">#9983CC39</color>
    <color name="highlighted_text_light">#9983CC39</color>
    <color name="link_text_dark">#5c5cff</color>
    <color name="link_text_light">#0000ee</color>
    <color name="suggestion_highlight_text">#177bbd</color>

    <drawable name="stat_notify_sync_noanim">@drawable/stat_notify_sync_anim0</drawable>
    <drawable name="stat_sys_download_done">@drawable/stat_sys_download_done_static</drawable>
    <drawable name="stat_sys_upload_done">@drawable/stat_sys_upload_anim0</drawable>
    <drawable name="dialog_frame">@drawable/panel_background</drawable>
    <drawable name="alert_dark_frame">@drawable/popup_full_dark</drawable>
    <drawable name="alert_light_frame">@drawable/popup_full_bright</drawable>
    <drawable name="menu_frame">@drawable/menu_background</drawable>
    <drawable name="menu_full_frame">@drawable/menu_background_fill_parent_width</drawable>
    <drawable name="editbox_dropdown_dark_frame">@drawable/editbox_dropdown_background_dark</drawable>
    <drawable name="editbox_dropdown_light_frame">@drawable/editbox_dropdown_background</drawable>

    <drawable name="dialog_holo_dark_frame">@drawable/dialog_full_holo_dark</drawable>
    <drawable name="dialog_holo_light_frame">@drawable/dialog_full_holo_light</drawable>

    <drawable name="input_method_fullscreen_background">#fff9f9f9</drawable>
    <drawable name="input_method_fullscreen_background_holo">@drawable/screen_background_holo_dark</drawable>
    <color name="input_method_navigation_guard">#ff000000</color>

    <!-- For date picker widget -->
    <drawable name="selected_day_background">#ff0092f4</drawable>

    <!-- For settings framework -->
    <color name="lighter_gray">#ddd</color>
    <color name="darker_gray">#aaa</color>

    <!-- For security permissions -->
    <color name="perms_dangerous_grp_color">#33b5e5</color>
    <color name="perms_dangerous_perm_color">#33b5e5</color>
    <color name="shadow">#cc222222</color>
    <color name="perms_costs_money">#ffffbb33</color>

    <!-- For search-related UIs -->
    <color name="search_url_text_normal">#7fa87f</color>
    <color name="search_url_text_selected">@android:color/black</color>
    <color name="search_url_text_pressed">@android:color/black</color>
    <color name="search_widget_corpus_item_background">@android:color/lighter_gray</color>

    <!-- SlidingTab -->
    <color name="sliding_tab_text_color_active">@android:color/black</color>
    <color name="sliding_tab_text_color_shadow">@android:color/black</color>

    <!-- keyguard tab -->
    <color name="keyguard_text_color_normal">#ffffff</color>
    <color name="keyguard_text_color_unlock">#a7d84c</color>
    <color name="keyguard_text_color_soundoff">#ffffff</color>
    <color name="keyguard_text_color_soundon">#e69310</color>
    <color name="keyguard_text_color_decline">#fe0a5a</color>

    <!-- keyguard clock -->
    <color name="lockscreen_clock_background">#ffffffff</color>
    <color name="lockscreen_clock_foreground">#ffffffff</color>
    <color name="lockscreen_clock_am_pm">#ffffffff</color>
    <color name="lockscreen_owner_info">#ff9a9a9a</color>

    <!-- keyguard overscroll widget pager -->
    <color name="kg_multi_user_text_active">#ffffffff</color>
    <color name="kg_multi_user_text_inactive">#ff808080</color>
    <color name="kg_widget_pager_gradient">#ffffffff</color>

    <!-- FaceLock -->
    <color name="facelock_spotlight_mask">#CC000000</color>

    <!-- For holo theme -->
      <drawable name="screen_background_holo_light">#fff3f3f3</drawable>
      <drawable name="screen_background_holo_dark">#ff000000</drawable>
    <color name="background_holo_dark">#ff000000</color>
    <color name="background_holo_light">#fff3f3f3</color>
    <color name="bright_foreground_holo_dark">@android:color/background_holo_light</color>
    <color name="bright_foreground_holo_light">@android:color/background_holo_dark</color>
    <color name="bright_foreground_disabled_holo_dark">#ff4c4c4c</color>
    <color name="bright_foreground_disabled_holo_light">#ffb2b2b2</color>
    <color name="bright_foreground_inverse_holo_dark">@android:color/bright_foreground_holo_light</color>
    <color name="bright_foreground_inverse_holo_light">@android:color/bright_foreground_holo_dark</color>
    <color name="dim_foreground_holo_dark">#bebebe</color>
    <color name="dim_foreground_disabled_holo_dark">#80bebebe</color>
    <color name="dim_foreground_inverse_holo_dark">#323232</color>
    <color name="dim_foreground_inverse_disabled_holo_dark">#80323232</color>
    <color name="hint_foreground_holo_dark">#808080</color>
    <color name="dim_foreground_holo_light">#323232</color>
    <color name="dim_foreground_disabled_holo_light">#80323232</color>
    <color name="dim_foreground_inverse_holo_light">#bebebe</color>
    <color name="dim_foreground_inverse_disabled_holo_light">#80bebebe</color>
    <color name="hint_foreground_holo_light">#808080</color>
    <color name="highlighted_text_holo_dark">#6633b5e5</color>
    <color name="highlighted_text_holo_light">#6633b5e5</color>
    <color name="link_text_holo_dark">#5c5cff</color>
    <color name="link_text_holo_light">#0000ee</color>

    <!-- Group buttons -->
    <eat-comment />
    <color name="group_button_dialog_pressed_holo_dark">#46c5c1ff</color>
    <color name="group_button_dialog_focused_holo_dark">#2699cc00</color>

    <color name="group_button_dialog_pressed_holo_light">#ffffffff</color>
    <color name="group_button_dialog_focused_holo_light">#4699cc00</color>

    <!-- Highlight colors for the legacy themes -->
    <eat-comment />
    <color name="legacy_pressed_highlight">#fffeaa0c</color>
    <color name="legacy_selected_highlight">#fff17a0a</color>
    <color name="legacy_long_pressed_highlight">#ffffffff</color>

    <!-- General purpose colors for Holo-themed elements -->
    <eat-comment />

    <!-- A light Holo shade of blue -->
    <color name="holo_blue_light">#ff33b5e5</color>
    <!-- A light Holo shade of gray -->
    <color name="holo_gray_light">#33999999</color>
    <!-- A light Holo shade of green -->
    <color name="holo_green_light">#ff99cc00</color>
    <!-- A light Holo shade of red -->
    <color name="holo_red_light">#ffff4444</color>
    <!-- A dark Holo shade of blue -->
    <color name="holo_blue_dark">#ff0099cc</color>
    <!-- A dark Holo shade of green -->
    <color name="holo_green_dark">#ff669900</color>
    <!-- A dark Holo shade of red -->
    <color name="holo_red_dark">#ffcc0000</color>
    <!-- A Holo shade of purple -->
    <color name="holo_purple">#ffaa66cc</color>
    <!-- A light Holo shade of orange -->
    <color name="holo_orange_light">#ffffbb33</color>
    <!-- A dark Holo shade of orange -->
    <color name="holo_orange_dark">#ffff8800</color>
    <!-- A really bright Holo shade of blue -->
    <color name="holo_blue_bright">#ff00ddff</color>
    <!-- A really bright Holo shade of gray -->
    <color name="holo_gray_bright">#33CCCCCC</color>

    <drawable name="notification_template_icon_bg">#3333B5E5</drawable>
    <drawable name="notification_template_icon_low_bg">#0cffffff</drawable>

    <!-- Keyguard colors -->
    <color name="keyguard_avatar_frame_color">#ffffffff</color>
    <color name="keyguard_avatar_frame_shadow_color">#80000000</color>
    <color name="keyguard_avatar_nick_color">#ffffffff</color>
    <color name="keyguard_avatar_frame_pressed_color">#ff35b5e5</color>

    <color name="accessibility_focus_highlight">#80ffff00</color>
</resources>

CSS two divs next to each other

I ran into this problem today. Based on the solutions above, this worked for me:

<div style="width:100%;"> 
    <div style="float:left;">Content left div</div> 
    <div style="float:right;">Content right div</div> 
</div> 

Simply make the parent div span the full width and float the divs contained within.

How do I drag and drop files into an application?

You need to be aware of a gotcha. Any class that you pass around as the DataObject in the drag/drop operation has to be Serializable. So if you try and pass an object, and it is not working, ensure it can be serialized as that is almost certainly the problem. This has caught me out a couple of times!

How to redirect the output of a PowerShell to a file during its execution

If you want a straight redirect of all output to a file, try using *>>:

# You'll receive standard output for the first command, and an error from the second command.
mkdir c:\temp -force *>> c:\my.log ;
mkdir c:\temp *>> c:\my.log ;

Since this is a straight redirect to file, it won't output to the console (often helpful). If you desire the console output, combined all output with *&>1, and then pipe with Tee-Object:

mkdir c:\temp -force *>&1 | Tee-Object -Append -FilePath c:\my.log ;
mkdir c:\temp *>&1 | Tee-Object -Append -FilePath c:\my.log ;

# Shorter aliased version
mkdir c:\temp *>&1 | tee -Append c:\my.log ;

I believe these techniques are supported in PowerShell 3.0 or later; I'm testing on PowerShell 5.0.

Blurry text after using CSS transform: scale(); in Chrome

In Chrome 74.0.3729.169, current as of 5-25-19, there doesn't seem to be any fix for blurring occurring at certain browser zoom levels caused by the transform. Even a simple TransformY(50px) will blur the element. This doesn't occur in current versions of Firefox, Edge or Safari, and it doesn't seem to occur at all zoom levels.

Find column whose name contains a specific string

Just iterate over DataFrame.columns, now this is an example in which you will end up with a list of column names that match:

import pandas as pd

data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)

spike_cols = [col for col in df.columns if 'spike' in col]
print(list(df.columns))
print(spike_cols)

Output:

['hey spke', 'no', 'spike-2', 'spiked-in']
['spike-2', 'spiked-in']

Explanation:

  1. df.columns returns a list of column names
  2. [col for col in df.columns if 'spike' in col] iterates over the list df.columns with the variable col and adds it to the resulting list if col contains 'spike'. This syntax is list comprehension.

If you only want the resulting data set with the columns that match you can do this:

df2 = df.filter(regex='spike')
print(df2)

Output:

   spike-2  spiked-in
0        1          7
1        2          8
2        3          9

How to test that a registered variable is not empty?

(ansible 2.9.6 ansible-lint 4.2.0)

See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string

    when: test_myscript.stderr != ""

Correct syntax and also "Ansible Galaxy Warning-Free" option is

    when: test_myscript.stderr | length > 0

Quoting from source code

"Use when: var|length > 0 rather than when: var != "" (or ' 'conversely when: var|length == 0 rather than when: var == "")"


Notes

  1. Test empty bare variable e.g.
    - debug:
        msg: "Empty string '{{ var }}' evaluates to False"
      when: not var
      vars:
        var: ''

    - debug:
        msg: "Empty list {{ var }} evaluates to False"
      when: not var
      vars:
        var: []

give

    "msg": "Empty string '' evaluates to False"
    "msg": "Empty list [] evaluates to False"
  1. But, testing non-empty bare variable string depends on CONDITIONAL_BARE_VARS. Setting ANSIBLE_CONDITIONAL_BARE_VARS=false the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true the condition will fail
    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var
      vars:
        var: 'abc'

gives

fatal: [localhost]: FAILED! => 
  msg: |-
    The conditional check 'var' failed. The error was: error while 
    evaluating conditional (var): 'abc' is undefined

Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'). When the filter bool is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true and ANSIBLE_CONDITIONAL_BARE_VARS=false have no effect

    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var|bool
      vars:
        var: 'abc'

gives

skipping: [localhost]
  1. Quoting from Porting guide 2.8 Bare variables in conditionals
  - include_tasks: teardown.yml
    when: teardown

  - include_tasks: provision.yml
    when: not teardown

" based on a variable you define as a string (with quotation marks around it):"

  • In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'

  • In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'

  • In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')

  1. Quoting from CONDITIONAL_BARE_VARS

"Expect that this setting eventually will be deprecated after 2.12"

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

You can explicitly tell Eclipse where to find it. Open eclipse.ini and add the following lines to the top of the file:

-vm
/absolute/path/to/jre6/bin

Update: I just nailed down the root cause on my own Windows machine. The GlassFish installer complained with exactly the same error message and after digging in GlassFish forums, the cause was clear: a corrupt JRE install on a Windows machine. My JRE came along with the JDK and the Java 6 JDK installer didn't install the JRE properly somehow. A DLL file was missing in JDK's JRE installation. After I reinstalled the standalone JRE from http://java.com, overwriting the old one, the GlassFish installer continued and also Eclipse was able to start flawlessly without those two lines in eclipse.ini.

How can I list all tags for a Docker image on a remote registry?

Get all tags from Docker Hub: this command uses the command-line JSON processor jq to select the tag names from the JSON returned by the Docker Hub Registry (the quotes are removed with tr). Replace library with the Docker Hub user name, debian with the image name:

curl -s 'https://registry.hub.docker.com/v2/repositories/library/debian/tags/' | jq -r '."results"[]["name"]'

JQuery $.ajax() post - data in a java servlet

For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:

  &A2168=1&A1837=5&A8472=1&A1987=2

On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:

Enumeration keys = request.getParameterNames(); 
HashMap map = new HashMap(); 
String key = null; 
while(keys.hasMoreElements()){ 
      key = keys.nextElement().toString(); 
      map.put(key, request.getParameter(key)); 
}

Searching a string in eclipse workspace

Goto Search->File

You will get an window, you can give either simple search text or regx pattern. Once you enter your search keyword click Search and make sure that Scope is Workspace.

You may use this for Replace as well.

How can I force users to access my page over HTTPS instead of HTTP?

Don't mix HTTP and HTTPS on the same page. If you have a form page that is served up via HTTP, I'm going to be nervous about submitting data -- I can't see if the submit goes over HTTPS or HTTP without doing a View Source and hunting for it.

Serving up the form over HTTPS along with the submit link isn't that heavy a change for the advantage.

Is there a way to split a widescreen monitor in to two or more virtual monitors?

It seems a window manager is what you want. The problem is finding one that works.

I use a tiling window manager in Linux (dwm) and it seems to do exactly what you are after, PLUS it has multiple workspaces which is what I thought you were going for at first.

A tiling window manager has no concept of "maximized" windows. All windows take up the full amount of space that they are allotted, and they never overlap. When you only have one window up on the screen, it gets the full screen. Open up another window, and it opens next to the first, while the first re-sizes automatically to take up only part of the screen. In dwm, the split between them is adjustable with keystrokes. Additional windows each take up their own allotted space on the screen, and any existing windows re-size to accommodate them depending on the particular layout you have chosen.

Workspaces use "tags"; any window can have one or more tags, and you can choose to see any windows that have one or more of a certain set of tags at a time. Thus you can hide windows that you don't want to see, and let the other windows take up more space.

Unfortunately, the few tiling add-ons I've tried for Windows don't work anywhere near as well. Although dwm has a few quirks with certain apps that use an SDI-style interface like Gimp or Pidgin (you can set windows as "floating" above the tiled layout to work around this), I've never had it get confused about where my windows are or shove windows off the screen like some of the window managers I've tried on Windows. If anyone knows of something with equivalent functionality that actually WORKS on Windows, I would love to know about it.

Python extract pattern matches

You can also use a capture group (?P<user>pattern) and access the group like a dictionary match['user'].

string = '''someline abc\n
            someother line\n
            name my_user_name is valid\n
            some more lines\n'''

pattern = r'name (?P<user>.*) is valid'
matches = re.search(pattern, str(string), re.DOTALL)
print(matches['user'])

# my_user_name

TypeError: Cannot read property "0" from undefined

Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.

Ammend your while statement to this...

for(var iIndex = 1; iIndex <= data.length; iIndex++){
    if (data[iIndex][0] === name){
         break;
    };
    Logger.log(data[i][0]);
 };

HTTP Error 404.3-Not Found in IIS 7.5

You should install IIS sub components from

Control Panel -> Programs and Features -> Turn Windows features on or off

Internet Information Services has subsection World Wide Web Services / Application Development Features

There you must check ASP.NET (.NET Extensibility, ISAPI Extensions, ISAPI Filters will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.

Run from cmd:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.

Also, look at this answer.

Check if a string matches a regex in Bash script

A good way to test if a string is a correct date is to use the command date:

if date -d "${DATE}" >/dev/null 2>&1
then
  # do what you need to do with your date
else
  echo "${DATE} incorrect date" >&2
  exit 1
fi

from comment: one can use formatting

if [ "2017-01-14" == $(date -d "2017-01-14" '+%Y-%m-%d') ] 

UITableView Separator line

Simplest way to add a separator line under each tableview cell can be done in the storyboard itself. First select the tableview, then in the attribute inspector select the separator line property to be single line. After this, select the separator inset to be custom and update the left inset to be 0 from the left.

Example

multi line comment vb.net in Visual studio 2010

I just learned this trick from a friend. Put your code inside these 2 statements and it will be commented out.

#if false

#endif

is there a 'block until condition becomes true' function in java?

Polling like this is definitely the least preferred solution.

I assume that you have another thread that will do something to make the condition true. There are several ways to synchronize threads. The easiest one in your case would be a notification via an Object:

Main thread:

synchronized(syncObject) {
    try {
        // Calling wait() will block this thread until another thread
        // calls notify() on the object.
        syncObject.wait();
    } catch (InterruptedException e) {
        // Happens if someone interrupts your thread.
    }
}

Other thread:

// Do something
// If the condition is true, do the following:
synchronized(syncObject) {
    syncObject.notify();
}

syncObject itself can be a simple Object.

There are many other ways of inter-thread communication, but which one to use depends on what precisely you're doing.

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

Easiest way to reverse a string:

    backwards = input("Enter string to reverse: ")
    print(backwards[::-1])

How to display length of filtered ng-repeat data

For completeness, in addition to previous answers (perform calculation of visible people inside controller) you can also perform that calculations in your HTML template as in the example below.

Assuming your list of people is in data variable and you filter people using query model, the following code will work for you:

<p>Number of visible people: {{(data|filter:query).length}}</p>
<p>Total number of people: {{data.length}}</p>
  • {{data.length}} - prints total number of people
  • {{(data|filter:query).length}} - prints filtered number of people

Note that this solution works fine if you want to use filtered data only once in a page. However, if you use filtered data more than once e.g. to present items and to show length of filtered list, I would suggest using alias expression (described below) for AngularJS 1.3+ or the solution proposed by @Wumms for AngularJS version prior to 1.3.

New Feature in Angular 1.3

AngularJS creators also noticed that problem and in version 1.3 (beta 17) they added "alias" expression which will store the intermediate results of the repeater after the filters have been applied e.g.

<div ng-repeat="person in data | filter:query as results">
    <!-- template ... -->
</div>

<p>Number of visible people: {{results.length}}</p>

The alias expression will prevent multiple filter execution issue.

I hope that will help.

Close window automatically after printing dialog closes

IE had (has?) the onbeforeprint and onafterprint events: you could wait for that, but it would only work on IE (which may or may not be ok).

Alternatively, you could try and wait for the focus to return to the window from the print dialog and close it. Amazon Web Services does this in their invoice print dialogs: you hit the print button, it opens up the print-friendly view and immediately opens up the printer dialog. If you hit print or cancel the print dialog closes and then the print-friendly view immediately closes.

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

Cannot construct instance of - Jackson

Your @JsonSubTypes declaration does not make sense: it needs to list implementation (sub-) classes, NOT the class itself (which would be pointless). So you need to modify that entry to list sub-class(es) there are; or use some other mechanism to register sub-classes (SimpleModule has something like addAbstractTypeMapping).

Converting json results to a date

If that number represents milliseconds, use the Date's constructor :

var myDate = new Date(1238540400000);

How can I disable a button on a jQuery UI dialog?

function getDialogButton( jqUIdialog, button_names )
{
    if (typeof button_names == 'string')
        button_names = [button_names];
    var buttons = jqUIdialog.parent().find('.ui-dialog-buttonpane button');
    for (var i = 0; i < buttons.length; i++)
    {
        var jButton = $( buttons[i] );
        for (var j = 0; j < button_names.length; j++)
            if ( jButton.text() == button_names[j] )
                return jButton;
    }

    return null;
}

function enableDialogButton( jqUIdialog, button_names, enable )
{
    var button = getDialogButton( jqUIdialog, button_names );
    if (button == null)
        alert('button not found: '+button_names);
    else
    {
        if (enable)
            button.removeAttr('disabled').removeClass( 'ui-state-disabled' );
        else
            button.attr('disabled', 'disabled').addClass( 'ui-state-disabled' );
    }
}

Custom format for time command

From the man page for time:

  1. There may be a shell built-in called time, avoid this by specifying /usr/bin/time
  2. You can provide a format string and one of the format options is elapsed time - e.g. %E

    /usr/bin/time -f'%E' $CMD

Example:

$ /usr/bin/time -f'%E' ls /tmp/mako/
res.py  res.pyc
0:00.01

JS how to cache a variable

You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.

Cookie *Create and Store a Cookie:*

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

The function which will return the specified cookie:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

Display a welcome message if the cookie is set

function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.

Jquery

Set a value to the session storage.

Javascript:

$.sessionStorage( 'foo', {data:'bar'} );

Retrieve the value:

$.sessionStorage( 'foo', {data:'bar'} );

$.sessionStorage( 'foo' );Results:
{data:'bar'}

Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:

var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);

//...
var storedNames=JSON.parse(localStorage['names']);

Server Side Example using ASP.NET

Adding to Sesion

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

// When retrieving an object from session state, cast it to // the appropriate type.

ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;

I hope that answered your question.

Postgresql - unable to drop database because of some auto connections to DB

Stop your running application.(in Eclipse) After you try again.

Changing directory in Google colab (breaking out of the python interpreter)

use

%cd SwitchFrequencyAnalysis

to change the current working directory for the notebook environment (and not just the subshell that runs your ! command).

you can confirm it worked with the pwd command like this:

!pwd

further information about jupyter / ipython magics: http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-cd

Spring boot Security Disable security

The easiest way for Spring Boot 2 without dependencies or code changes is just:

spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

How can I debug git/git-shell related problems?

Git 2.9.x/2.10 (Q3 2016) adds another debug option: GIT_TRACE_CURL.

See commit 73e57aa, commit 74c682d (23 May 2016) by Elia Pinto (devzero2000).
Helped-by: Torsten Bögershausen (tboegi), Ramsay Jones , Junio C Hamano (gitster), Eric Sunshine (sunshineco), and Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 2f84df2, 06 Jul 2016)

http.c: implement the GIT_TRACE_CURL environment variable

Implement the GIT_TRACE_CURL environment variable to allow a greater degree of detail of GIT_CURL_VERBOSE, in particular the complete transport header and all the data payload exchanged.
It might be useful if a particular situation could require a more thorough debugging analysis.

The documentation will state:

GIT_TRACE_CURL

Enables a curl full trace dump of all incoming and outgoing data, including descriptive information, of the git transport protocol.
This is similar to doing curl --trace-ascii on the command line.

This option overrides setting the GIT_CURL_VERBOSE environment variable.


You can see that new option used in this answer, but also in the Git 2.11 (Q4 2016) tests:

See commit 14e2411, commit 81590bf, commit 4527aa1, commit 4eee6c6 (07 Sep 2016) by Elia Pinto (devzero2000).
(Merged by Junio C Hamano -- gitster -- in commit 930b67e, 12 Sep 2016)

Use the new GIT_TRACE_CURL environment variable instead of the deprecated GIT_CURL_VERBOSE.

GIT_TRACE_CURL=true git clone --quiet $HTTPD_URL/smart/repo.git

How to normalize a signal to zero mean and unit variance?

It seems like you are essentially looking into computing the z-score or standard score of your data, which is calculated through the formula: z = (x-mean(x))/std(x)

This should work:

%% Original data (Normal with mean 1 and standard deviation 2)
x = 1 + 2*randn(100,1);
mean(x)
var(x)
std(x)

%% Normalized data with mean 0 and variance 1
z = (x-mean(x))/std(x);
mean(z)
var(z)
std(z)

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Have had the same problem happen to me twice now, the only fix sofa has been to restart the tomcat server and restart the build.

How to return a table from a Stored Procedure?

Where is your problem??

For the stored procedure, just create:

CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
   SELECT *  -- I would *strongly* recommend specifying the columns EXPLICITLY
   FROM dbo.Emp
   WHERE ID = @EmpID

That's all there is.

From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)

DataTable tblEmployees = new DataTable();

using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
    _cmd.CommandType = CommandType.StoredProcedure;

    _cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
    _cmd.Parameters["@EmpID"].Value = 42;

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);

    _dap.Fill(tblEmployees);
}

YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();

and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.

Set selected radio from radio group with a value

Pure JavaScript version:

document.querySelector('input[name="myradio"][value="5"]').checked = true;

How do I change Android Studio editor's background color?

You can change it by going File => Settings (Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance , Now from Right Panel choose theme.

enter image description here

Android Studio 2.1

Preference -> Search for Appearance -> UI options , Click on DropDown Theme

enter image description here

Android 2.2

Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options

EDIT :

Import External Themes

You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the .jar file downloaded.

Escape single quote character for use in an SQLite query

In C# you can use the following to replace the single quote with a double quote:

 string sample = "St. Mary's";
 string escapedSample = sample.Replace("'", "''");

And the output will be:

"St. Mary''s"

And, if you are working with Sqlite directly; you can work with object instead of string and catch special things like DBNull:

private static string MySqlEscape(Object usString)
{
    if (usString is DBNull)
    {
        return "";
    }
    string sample = Convert.ToString(usString);
    return sample.Replace("'", "''");
}

Error message "Forbidden You don't have permission to access / on this server"

I understand this issue is resolved but I happened to solve this same problem on my own.

The cause of

Forbidden You don't have permission to access / on this server

is actually the default configuration for an apache directory in httpd.conf.

#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories). 
#
# First, we configure the "default" to be a very restrictive set of 
# features.  
#
<Directory "/">
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all          # the cause of permission denied
</Directory>

Simply changing Deny from all to Allow from all should solve the permission problem.

Alternatively, a better approach would be to specify individual directory permissions on virtualhost configuration.

<VirtualHost *:80>
    ....

    # Set access permission
    <Directory "/path/to/docroot">
        Allow from all
    </Directory>

    ....
</VirtualHost>

As of Apache-2.4, however, access control is done using the new module mod_authz_host (Upgrading to 2.4 from 2.2). Consequently, the new Require directive should be used.

<VirtualHost *:80>
    ....

    # Set access permission
    <Directory "/path/to/docroot">
        Require all granted
    </Directory>

    ....
</VirtualHost>

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Ajax forms work asynchronously using Javascript. So it is required, to load the script files for execution. Even though it's a small performance compromise, the execution happens without postback.

We need to understand the difference between the behaviours of both Html and Ajax forms.

Ajax:

  1. Won't redirect the form, even you do a RedirectAction().

  2. Will perform save, update and any modification operations asynchronously.

Html:

  1. Will redirect the form.

  2. Will perform operations both Synchronously and Asynchronously (With some extra code and care).

Demonstrated the differences with a POC in below link. Link

Statically rotate font-awesome icons

New Font-Awesome v5 has Power Transforms

You can rotate any icon by adding attribute data-fa-transform to icon

<i class="fas fa-magic" data-fa-transform="rotate-45"></i>

Here is a fiddle

For more information, check this out : Font-Awesome5 Power Tranforms

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

I used the following code on Django side to interpret the OPTIONS request and to set the required Access-Control headers. After this my cross domain requests from Firefox started working. As said before, the browser first sends the OPTIONS request and then immediately after that the POST/GET

def send_data(request):
    if request.method == "OPTIONS": 
        response = HttpResponse()
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
        response['Access-Control-Max-Age'] = 1000
        # note that '*' is not valid for Access-Control-Allow-Headers
        response['Access-Control-Allow-Headers'] = 'origin, x-csrftoken, content-type, accept'
        return response
    if request.method == "POST":
        # ... 

Edit: it seems to be that at least in some cases you also need to add the same Access-Control headers to the actual response. This can be a little bit confusing, since the request seems to succeed, but Firefox does not pass the contents of the response to the Javascript.

Android - how to replace part of a string by another string?

In kotlin there is no replaceAll, so I created this loop to replace repeated values ??in a string or any variable.

 var someValue = "https://www.google.com.br/"
    while (someValue.contains(".")) {
        someValue = someValue.replace(".", "")
    }
Log.d("newValue :", someValue)
// in that case the stitches have been removed
//https://wwwgooglecombr/

CHECK constraint in MySQL is not working

Update to MySQL 8.0.16 to use checks:

As of MySQL 8.0.16, CREATE TABLE permits the core features of table and column CHECK constraints, for all storage engines. CREATE TABLE permits the following CHECK constraint syntax, for both table constraints and column constraints

MySQL Checks Documentation

How to change the default encoding to UTF-8 for Apache?

Just a hint if you have long filenames in utf-8: by default they will be shortened to 20 bytes, so it may happen that the last character might be "cut in half" and therefore unrecognized properly. Then you may want to set the following:

IndexOptions Charset=UTF-8 NameWidth=*

NameWidth setting will prevent shortening your file names, making them properly displayed and readable.

As other users already mentioned, this should be added either in httpd.conf or apache2.conf (if you do have admin rights) or in .htaccess (if you don't).

What is the Python equivalent for a case/switch statement?

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

How do I install a plugin for vim?

Those two commands will create a ~/.vim/vim-haml/ directory with the ftplugin, syntax, etc directories in it. Those directories need to be immediately in the ~/.vim directory proper or ~/.vim/vim-haml needs to be added to the list of paths that vim searches for plugins.

Edit:

I recently decided to tweak my vim config and in the process wound up writing the following rakefile. It only works on Mac/Linux, but the advantage over cp versions is that it's completely safe (symlinks don't overwrite existing files, uninstall only deletes symlinks) and easy to keep things updated.

# Easily install vim plugins from a source control checkout (e.g. Github)
#
# alias vim-install=rake -f ~/.vim/rakefile-vim-install
# vim-install
# vim-install uninstall

require 'ftools'
require 'fileutils'

task :default => :install
desc "Install a vim plugin the lazy way"
task :install do
  vim_dir      = File.expand_path("~/.vim")
  plugin_dir   = Dir.pwd

  if not (FileTest.exists? File.join(plugin_dir,".git") or
          FileTest.exists? File.join(plugin_dir,".svn") or
          FileTest.exists? File.join(plugin_dir,".hg"))
      puts "#{plugin_dir} isn't a source controlled directory. Aborting."
      exit 1
  end

  Dir['**/'].each do |d|
    FileUtils.mkdir_p File.join(vim_dir, d)
  end

  Dir["**/*.{txt,snippet,snippets,vim,js,wsf}"].each do |f|
    ln File.join(plugin_dir, f), File.join(vim_dir,f)
  end

  boldred = "\033[1;31m"
  clear = "\033[0m"
  puts "\nDone. Remember to #{boldred}:helptags ~/.vim/doc#{clear}"
end

task :uninstall do
  vim_dir      = File.expand_path("~/.vim")
  plugin_dir   = Dir.pwd
  Dir["**/*.{txt,snippet,snippets,vim}"].each do |f|
    safe_rm File.join(vim_dir, f)
  end
end

def nicename(path)
    boldgreen = "\033[1;32m"
    clear = "\033[0m"
    return "#{boldgreen}#{File.join(path.split('/')[-2..-1])}#{clear}\t"
end

def ln(src, dst)
    begin
        FileUtils.ln_s src, dst
        puts "    Symlink #{nicename src}\t => #{nicename dst}"
    rescue Errno::EEXIST
        puts "  #{nicename dst} exists! Skipping."
    end
end

def cp(src, dst)
  puts "    Copying #{nicename src}\t=> #{nicename dst}"
  FileUtils.cp src, dst
end

def safe_rm(target)
    if FileTest.exists? target and FileTest.symlink? target
        puts "    #{nicename target} removed."
        File.delete target
    else
        puts "  #{nicename target} is not a symlink. Skipping"
    end
end

How to access elements of a JArray (or iterate over them)

There is a much simpler solution for that.
Actually treating the items of JArray as JObject works.
Here is an example:
Let's say we have such array of JSON objects:

JArray jArray = JArray.Parse(@"[
              {
                ""name"": ""Croke Park II"",
                ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                ""promoted_content"": null,
                ""query"": ""%22Croke+Park+II%22"",
                ""events"": null
              },
              {
                ""name"": ""Siptu"",
                ""url"": ""http://twitter.com/search?q=Siptu"",
                ""promoted_content"": null,
                ""query"": ""Siptu"",
                ""events"": null
              }]");

To get access each item we just do the following:

foreach (JObject item in jArray)
{
    string name = item.GetValue("name").ToString();
    string url = item.GetValue("url").ToString();
    // ...
}

Relative div height

add this to your css:

html, body{height: 100%}

and change the max-height of #block12 to height

Explanation:

Basically #wrap was 100% height (relative measure) but when you use relative measures it looks for its parent element's measure, and it's normally undefined because it's also relative. The only element(s) being able to use a relative heights are body and or html themselves depending on the browser, the rest of the elements need a parent element with absolute height.

But be careful, it's tricky playing around with relative heights, you have to calculate properly your header's height so you can substract it from the other element's percentages.

Json.NET serialize object with root name

I found an easy way to render this out... simply declare a dynamic object and assign the first item within the dynamic object to be your collection class...This example assumes you're using Newtonsoft.Json

private class YourModelClass
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

var collection = new List<YourModelClass>();

var collectionWrapper = new {

    myRoot = collection

};

var output = JsonConvert.SerializeObject(collectionWrapper);

What you should end up with is something like this:

{"myRoot":[{"firstName":"John", "lastName": "Citizen"}, {...}]}

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

Split string in JavaScript and detect line break

Here's the final code I [OP] used. Probably not best practice, but it worked.

function wrapText(context, text, x, y, maxWidth, lineHeight) {

    var breaks = text.split('\n');
    var newLines = "";
    for(var i = 0; i < breaks.length; i ++){
      newLines = newLines + breaks[i] + ' breakLine ';
    }

    var words = newLines.split(' ');
    var line = '';
    console.log(words);
    for(var n = 0; n < words.length; n++) {
      if(words[n] != 'breakLine'){
        var testLine = line + words[n] + ' ';
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > maxWidth && n > 0) {
          context.fillText(line, x, y);
          line = words[n] + ' ';
          y += lineHeight;
        }
        else {
          line = testLine;
        }
      }else{
          context.fillText(line, x, y);
          line = '';
          y += lineHeight;
      }
    }
    context.fillText(line, x, y);
  }

How can I run a PHP script in the background after a form is submitted?

How about this?

  1. Your PHP script that holds the form saves a flag or some value into a database or file.
  2. A second PHP script polls for this value periodically and if it's been set, it triggers the Email script in a synchronous manner.

This second PHP script should be set to run as a cron.

Oracle date difference to get number of years

I'd use months_between, possibly combined with floor:

select floor(months_between(date '2012-10-10', date '2011-10-10') /12) from dual;

select floor(months_between(date '2012-10-9' , date '2011-10-10') /12) from dual;

floor makes sure you get down-rounded years. If you want the fractional parts, you obviously want to not use floor.

C# how to convert File.ReadLines into string array?

Change string[] lines = File.ReadLines("c:\\file.txt"); to IEnumerable<string> lines = File.ReadLines("c:\\file.txt"); The rest of your code should work fine.

Java ArrayList Index

Here is how I would write it.

String[] fruit = "apple banana orange".split(" ");
System.out.println(fruit[1]);

How to customize listview using baseadapter

main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

    </ListView>

</RelativeLayout>

custom.xml:

<?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="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="255dp"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Video1"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="#339966"
                    android:textStyle="bold" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/detail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="video1"
                    android:textColor="#606060" />
            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />

    </LinearLayout>

</LinearLayout>

main.java:

package com.example.sample;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


public class MainActivity extends Activity {

    ListView l1;
    String[] t1={"video1","video2"};
    String[] d1={"lesson1","lesson2"};
    int[] i1 ={R.drawable.ic_launcher,R.drawable.ic_launcher};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        l1=(ListView)findViewById(R.id.list);
        l1.setAdapter(new dataListAdapter(t1,d1,i1));
    }

    class dataListAdapter extends BaseAdapter {
        String[] Title, Detail;
        int[] imge;

        dataListAdapter() {
            Title = null;
            Detail = null;
            imge=null;
        }

        public dataListAdapter(String[] text, String[] text1,int[] text3) {
            Title = text;
            Detail = text1;
            imge = text3;

        }

        public int getCount() {
            // TODO Auto-generated method stub
            return Title.length;
        }

        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater = getLayoutInflater();
            View row;
            row = inflater.inflate(R.layout.custom, parent, false);
            TextView title, detail;
            ImageView i1;
            title = (TextView) row.findViewById(R.id.title);
            detail = (TextView) row.findViewById(R.id.detail);
            i1=(ImageView)row.findViewById(R.id.img);
            title.setText(Title[position]);
            detail.setText(Detail[position]);
            i1.setImageResource(imge[position]);

            return (row);
        }
    }
}

Try this.

"Unable to locate tools.jar" when running ant

  1. Try to check it once more according to this tutorial: http://vietpad.sourceforge.net/javaonwindows.html

  2. Try to reboot your system.

  3. If nothing, try to run "cmd" and type there "java", does it print anything?

How to convert a std::string to const char* or char*?

If you just want to pass a std::string to a function that needs const char* you can use

std::string str;
const char * c = str.c_str();

If you want to get a writable copy, like char *, you can do that with this:

std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0

// don't forget to free the string after finished using it
delete[] writable;

Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.

boost::scoped_array

boost::scoped_array will delete the memory for you upon going out of scope:

std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = '\0'; // don't forget the terminating 0

// get the char* using writable.get()

// memory is automatically freed if the smart pointer goes 
// out of scope

std::vector

This is the standard way (does not require any external library). You use std::vector, which completely manages the memory for you.

std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');

// get the char* using &writable[0] or &*writable.begin()

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

Running this:

sqllocaldb create "v12.0"

From cmd prompt solved this for me...

Using jQuery to test if an input has focus

What I wound up doing is creating an arbitrary class called .elementhasfocus which is added and removed within the jQuery focus() function. When the hover() function runs on mouse out, it checks for .elementhasfocus:

if(!$("#quotebox").is(".boxhasfocus")) $(this).removeClass("box_border");

So if it doesn't have that class (read: no elements within the div have focus) the border is removed. Otherwise, nothing happens.

Drop all tables whose names begin with a certain string

Xenph Yan's answer was far cleaner than mine but here is mine all the same.

DECLARE @startStr AS Varchar (20)
SET @startStr = 'tableName'

DECLARE @startStrLen AS int
SELECT @startStrLen = LEN(@startStr)

SELECT 'DROP TABLE ' + name FROM sysobjects
WHERE type = 'U' AND LEFT(name, @startStrLen) = @startStr

Just change tableName to the characters that you want to search with.

How can I change Eclipse theme?

In the eclipse Version: 2019-09 R (4.13.0) on windows Go to Window > preferences > Appearance Select the required theme for dark theme to choose Dark and click on Ok. enter image description here

What is the maximum number of characters that nvarchar(MAX) will hold?

From char and varchar (Transact-SQL)

varchar [ ( n | max ) ]

Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

How to listen to route changes in react router v4?

With react Hooks, I am using useEffect

  const history = useHistory()
  const queryString = require('query-string')
  const parsed = queryString.parse(location.search)
  const [search, setSearch] = useState(parsed.search ? parsed.search : '')

  useEffect(() => {
    const parsedSearch = parsed.search ? parsed.search : ''
    if (parsedSearch !== search) {
      // do some action! The route Changed!
    }
  }, [location.search])

Return Bit Value as 1/0 and NOT True/False in SQL Server

 Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
              ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME

in your query for only true or false column

How do I find the width & height of a terminal window?

There are some cases where your rows/LINES and columns do not match the actual size of the "terminal" being used. Perhaps you may not have a "tput" or "stty" available.

Here is a bash function you can use to visually check the size. This will work up to 140 columns x 80 rows. You can adjust the maximums as needed.

function term_size
{
    local i=0 digits='' tens_fmt='' tens_args=()
    for i in {80..8}
    do
        echo $i $(( i - 2 ))
    done
    echo "If columns below wrap, LINES is first number in highest line above,"
    echo "If truncated, LINES is second number."
    for i in {1..14}
    do
        digits="${digits}1234567890"
        tens_fmt="${tens_fmt}%10d"
        tens_args=("${tens_args[@]}" $i)
    done
    printf "$tens_fmt\n" "${tens_args[@]}"
    echo "$digits"
}

How to convert comma-delimited string to list in Python?

You can use this function to convert comma-delimited single character strings to list-

def stringtolist(x):
    mylist=[]
    for i in range(0,len(x),2):
        mylist.append(x[i])
    return mylist

Convert txt to csv python script

You need to split the line first.

import csv

with open('log.txt', 'r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line.split(",") for line in stripped if line)
    with open('log.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro'))
        writer.writerows(lines)

How do I concatenate two strings in C?

using memcpy

char *str1="hello";
char *str2=" world";
char *str3;

str3=(char *) malloc (11 *sizeof(char));
memcpy(str3,str1,5);
memcpy(str3+strlen(str1),str2,6);

printf("%s + %s = %s",str1,str2,str3);
free(str3);

ActiveMQ connection refused

I encountered a similar problem when I was using the below to obtain connection factory ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");

Its resolved when I changed it to the below

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");

The below then showed that my Q size was increasing.. http://:8161/admin/queues.jsp

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

I'm using:

Eclipse Java EE IDE for Web Developers.

Version: Neon.3 Release (4.6.3) Build id: 20170314-1500

The fix/trick for me was deleting my local repository in ~/.m2/repository in order to remove local dependencies and rebuilding my project in which fresh dependencies are pulled down.

How to know which version of Symfony I have?

Use the following command in your Terminal/Command Prompt:

php bin/console --version

This will give you your Symfony Version.

Declare and initialize a Dictionary in Typescript

For using dictionary object in typescript you can use interface as below:

interface Dictionary<T> {
    [Key: string]: T;
}

and, use this for your class property type.

export class SearchParameters {
    SearchFor: Dictionary<string> = {};
}

to use and initialize this class,

getUsers(): Observable<any> {
        var searchParams = new SearchParameters();
        searchParams.SearchFor['userId'] = '1';
        searchParams.SearchFor['userName'] = 'xyz';

        return this.http.post(searchParams, 'users/search')
            .map(res => {
                return res;
            })
            .catch(this.handleError.bind(this));
    }

Check if a row exists, otherwise insert

The best approach to this problem is first making the database column UNIQUE

ALTER TABLE table_name ADD UNIQUE KEY

THEN INSERT IGNORE INTO table_name ,the value won't be inserted if it results in a duplicate key/already exists in the table.

How to remove all white spaces in java

public static String removeSpace(String s) {
    String withoutspaces = "";
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) != ' ')
            withoutspaces += s.charAt(i);

    }
    return withoutspaces;

}

This is the easiest and most straight forward method to remove spaces from a String.

Efficient way to add spaces between characters in a string

s = "BINGO"
print(s.replace("", " ")[1: -1])

Timings below

$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop

ActionController::InvalidAuthenticityToken

This happened to me when upgrading from Rails 4.0 to 4.2.

The 4.2 implementation of verified_request? looks at request.headers['X-CSRF-Token'], whereas the header my 4.0 app had been getting was X-XSRF-TOKEN. A quick fix in my ApplicationController was to add the function:

  def verify_authenticity_token
    request.headers['X-CSRF-Token'] ||= request.headers['X-XSRF-TOKEN']
    super
  end

How to reload a page using Angularjs?

$scope.rtGo = function(){
            $window.sessionStorage.removeItem('message');
            $window.sessionStorage.removeItem('status');
        }

Get list of JSON objects with Spring RestTemplate

First define an object to hold the entity coming back in the array.. e.g.

@JsonIgnoreProperties(ignoreUnknown = true)
public class Rate {
    private String name;
    private String code;
    private Double rate;
    // add getters and setters
}

Then you can consume the service and get a strongly typed list via:

ResponseEntity<List<Rate>> rateResponse =
        restTemplate.exchange("https://bitpay.com/api/rates",
                    HttpMethod.GET, null, new ParameterizedTypeReference<List<Rate>>() {
            });
List<Rate> rates = rateResponse.getBody();

The other solutions above will also work, but I like getting a strongly typed list back instead of an Object[].

How to iterate for loop in reverse order in swift?

For Swift 2.0 and above you should apply reverse on a range collection

for i in (0 ..< 10).reverse() {
  // process
}

It has been renamed to .reversed() in Swift 3.0

downloading all the files in a directory with cURL

If you're not bound to curl, you might want to use wget in recursive mode but restricting it to one level of recursion, try the following;

wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
  • --no-parent : Do not ever ascend to the parent directory when retrieving recursively.
  • --level=depth : Specify recursion maximum depth level depth. The default maximum depth is five layers.
  • --no-directories : Do not create a hierarchy of directories when retrieving recursively.

How to have jQuery restrict file types on upload?

This code works fine, but the only issue is if the file format is other than specified options, it shows an alert message but it displays the file name while it should be neglecting it.

$('#ff2').change(
                function () {
                    var fileExtension = ['jpeg', 'jpg', 'pdf'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                        alert("Only '.jpeg','.jpg','.pdf' formats are allowed.");
                        return false; }
});

ASP.Net 2012 Unobtrusive Validation with jQuery

Add a reference to Microsoft.JScript in your application in your web.config as below :

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="Microsoft.JScript, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
  </appSettings>
</configuration>

SQL JOIN, GROUP BY on three tables to get totals

First of all, shouldn't there be a CustomerId in the Invoices table? As it is, You can't perform this query for Invoices that have no payments on them as yet. If there are no payments on an invoice, that invoice will not even show up in the ouput of the query, even though it's an outer join...

Also, When a customer makes a payment, how do you know what Invoice to attach it to ? If the only way is by the InvoiceId on the stub that arrives with the payment, then you are (perhaps inappropriately) associating Invoices with the customer that paid them, rather than with the customer that ordered them... . (Sometimes an invoice can be paid by someone other than the customer who ordered the services)

PHP sessions default timeout

http://php.net/session.gc-maxlifetime

session.gc_maxlifetime = 1440
(1440 seconds = 24 minutes)

Uppercase first letter of variable

var country= $('#country').val();

var con=country[0].toUpperCase();

ctr= country.replace(country[0], con);
   

no need to create any function just jugaaar