Programs & Examples On #Extern

extern is an access-specifier in C and C++ which defines a global variable that is visible to all object modules.

How do I share a global variable between c files?

If you want to use global variable i of file1.c in file2.c, then below are the points to remember:

  1. main function shouldn't be there in file2.c
  2. now global variable i can be shared with file2.c by two ways:
    a) by declaring with extern keyword in file2.c i.e extern int i;
    b) by defining the variable i in a header file and including that header file in file2.c.

How do I use extern to share variables between source files?

With xc8 you have to be careful about declaring a variable as the same type in each file as you could , erroneously, declare something an int in one file and a char say in another. This could lead to corruption of variables.

This problem was elegantly solved in a microchip forum some 15 years ago /* See "http:www.htsoft.com" / / "forum/all/showflat.php/Cat/0/Number/18766/an/0/page/0#18766"

But this link seems to no longer work...

So I;ll quickly try to explain it; make a file called global.h.

In it declare the following

#ifdef MAIN_C
#define GLOBAL
 /* #warning COMPILING MAIN.C */
#else
#define GLOBAL extern
#endif
GLOBAL unsigned char testing_mode; // example var used in several C files

Now in the file main.c

#define MAIN_C 1
#include "global.h"
#undef MAIN_C

This means in main.c the variable will be declared as an unsigned char.

Now in other files simply including global.h will have it declared as an extern for that file.

extern unsigned char testing_mode;

But it will be correctly declared as an unsigned char.

The old forum post probably explained this a bit more clearly. But this is a real potential gotcha when using a compiler that allows you to declare a variable in one file and then declare it extern as a different type in another. The problems associated with that are if you say declared testing_mode as an int in another file it would think it was a 16 bit var and overwrite some other part of ram, potentially corrupting another variable. Difficult to debug!

static and extern global variables in C and C++

When you #include a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal variable is defined in the source so it will work no matter how it's declared.

Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.

using extern template (C++11)

The known problem with the templates is code bloating, which is consequence of generating the class definition in each and every module which invokes the class template specialization. To prevent this, starting with C++0x, one could use the keyword extern in front of the class template specialization

#include <MyClass>
extern template class CMyClass<int>;

The explicit instantion of the template class should happen only in a single translation unit, preferable the one with template definition (MyClass.cpp)

template class CMyClass<int>;
template class CMyClass<float>;

Force Intellij IDEA to reread all maven dependencies

Setting > Maven > Always update snapshots

Colorized grep -- viewing the entire file with highlighted matches

Here's something along the same lines. Chances are, you'll be using less anyway, so try this:

less -p pattern file

It will highlight the pattern and jump to the first occurrence of it in the file.

You can jump to the next occurence with n and to the previous occurence with p. Quit with q.

How to center absolute div horizontally using CSS?

Centering div with position: absolute and width: unknown:

HTML:

<div class="center">
  <span></span>

  <div>
    content...
  </div>

</div>

CSS:

.center{
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: grid;
  grid-template-columns: auto auto;
  overflow: auto;
}

How can I setup & run PhantomJS on Ubuntu?

Here are the build steps I used (note these instructions are for version 1.3. See comments to this answer for the installation instructions of the latest PhantomJS):

sudo apt-get update
sudo apt-get install git-core
sudo apt-get install build-essential
sudo apt-get install libqt4-dev libqtwebkit-dev qt4-qmake
git clone git://github.com/ariya/phantomjs.git && cd phantomjs
git checkout 1.3
qmake-qt4 && make

Now install Xvfb

sudo apt-get install xvfb xfonts-100dpi xfonts-75dpi xfonts-scalable xfonts-cyrillic

Launch Xvfb:
Xvfb :23 -screen 0 1024x768x24 &

Now run phantom:
DISPLAY=:23 ./phantomjs hello.js

matplotlib: how to change data points color based on some variable

This is what matplotlib.pyplot.scatter is for.

As a quick example:

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)

plt.scatter(t,x,c=y)
plt.show()

enter image description here

How to pass arguments from command line to gradle

As of Gradle 4.9 Application plugin understands --args option, so passing the arguments is as simple as:

build.gradle

plugins {
    id 'application'
}

mainClassName = "my.App"

src/main/java/my/App.java

public class App {
    public static void main(String[] args) {
        System.out.println(args);
    }
}

bash

./gradlew run --args='This string will be passed into my.App#main arguments'

or in Windows, use double quotes:

gradlew run --args="This string will be passed into my.App#main arguments"

open_basedir restriction in effect. File(/) is not within the allowed path(s):

The path you're refering to is incorect, and not withing the directoryRoot of your workspace. Try building an absolute path the the file you want to access, where you are now probably using a relative path...

How to sort pandas data frame using values from several columns?

DataFrame.sort is deprecated; use DataFrame.sort_values.

>>> df.sort_values(['c1','c2'], ascending=[False,True])
   c1   c2
0   3   10
3   2   15
1   2   30
4   2  100
2   1   20
>>> df.sort(['c1','c2'], ascending=[False,True])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ampawake/anaconda/envs/pseudo/lib/python2.7/site-packages/pandas/core/generic.py", line 3614, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'sort'

How to open warning/information/error dialog in Swing?

JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....

Have a look on this tutorial on how to make dialogs.

PDOException “could not find driver”

I Fixed this issue on my Debian 6. Normally I just had installed php5-common package. After installation, you have to restart your web server (apache or nginx depending on which one you installed). Then I just do an lsof on the apache process id (lsof -p process_id) as followed :

sudo lsof -p 1399   #replace 1399 by your apache process id
apache2 1399 root  mem    REG  254,2    80352 227236 /usr/lib/php5/20090626/xmlrpc.so
apache2 1399 root  mem    REG  254,2   166496 227235 /usr/lib/php5/20090626/suhosin.so
apache2 1399 root  mem    REG  254,2    31120 227233 /usr/lib/php5/20090626/pdo_mysql.so
apache2 1399 root  mem    REG  254,2   100776 227216 /usr/lib/php5/20090626/pdo.so
apache2 1399 root  mem    REG  254,2   135864 227232 /usr/lib/php5/20090626/mysqli.so

As you can see above, the modules are installed on a file path not known or guided by common library path: /usr/lib/php5/20090626/. For your installation, it may be different, but only the path of pdo_mysql.so, pdo.so, mysqli.so. So, this is why Drupal or any other php engine couldn't find the library and shows that error: PDOException: could not find driver

I just don't know why it is installed on such a weird path, for me it's just a bug in the library package installation script in debian 6. I solved the issue by creating a symbolic for all the files under /usr/lib/php5/20090626/ to /usr/lib/php5/ with this command :

ln -s /usr/lib/php5/20090626/* /usr/lib/php5/

CRC32 C or C++ implementation

I am the author of the source code at the specified link. While the intention of the source code license is not clear (it will be later today), the code is in fact open and free for use in your free or commercial applications with no strings attached.

How to generate java classes from WSDL file

jdk 6 comes with wsimport that u can use to create Java-classes from a WSDL. It also creates a Service-class.

http://docs.oracle.com/javase/6/docs/technotes/tools/share/wsimport.html

Can a main() method of class be invoked from another class in java

If you want to call the main method of another class you can do it this way assuming I understand the question.

public class MyClass {

    public static void main(String[] args) {

        System.out.println("main() method of MyClass");
        OtherClass obj = new OtherClass();
    }
}

class OtherClass {

    public OtherClass() {

        // Call the main() method of MyClass
        String[] arguments = new String[] {"123"};
        MyClass.main(arguments);
    }
}

How do I read the first line of a file using cat?

You could use cat file.txt | head -1, but it would probably be better to use head directly, as in head -1 file.txt.

How to check a string for a special character?

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

How to automatically close cmd window after batch file execution?

Just try /s as listed below.

As the last line in the batch file type:

exit /s

The above command will close the Windows CMD window.

/s - stands for silent as in (it would wait for an input from the keyboard).

Java - get pixel array from image

Something like this?

int[][] pixels = new int[w][h];

for( int i = 0; i < w; i++ )
    for( int j = 0; j < h; j++ )
        pixels[i][j] = img.getRGB( i, j );

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!

What causes a java.lang.StackOverflowError

I was having the same issue

Role.java

 @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY,cascade = CascadeType.ALL)
 Set<BusinessUnitMaster> businessUnits =new HashSet<>();

BusinessUnitMaster.java

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(
        name = "BusinessUnitRoles",
        joinColumns = {@JoinColumn(name = "unit_id", referencedColumnName = "record_id")},
        inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "record_id")}
)
private Set<Role> roles=new HashSet<>();

the problem is that when you create BusinessUnitMaster and Role you have to save the object for both sides for RoleService.java

roleRepository.save(role);

for BusinessUnitMasterService.java

businessUnitMasterRepository.save(businessUnitMaster);

What is the standard naming convention for html/css ids and classes?

I think it is platform dependent. When developing in .Net MVC, I use bootstrap style lower case and hyphens for class names, but for ids I use PascalCase.

The reasoning for this is that my views are backed by strongly typed view models. Properties of C# models are pascal case. For the sake of model binding with MVC it makes sense that the names of HTML elements that bind to the model are consistent with the view model properties which are pascal case. For simplicity my ids are use the same naming convention as element names except for radio buttons and check boxes which require unique ids for each element in the named input group.

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

java: Java application executor which is associated with a console to display output/errors

javaw: (Java windowed) application executor not associated with console. So no display of output/errors. It can be used to silently push the output/errors to text files. It is mostly used to launch GUI-based applications.

javaws: (Java web start) to download and run the distributed web applications. Again, no console is associated.

All are part of JRE and use the same JVM.

Lightweight Javascript DB for use in Node.js

Maybe you should try LocallyDB it's easy-to-use and lightweight in addition to the with advanced selecting system similar to javascript conditional expression...

https://github.com/btwael/locallydb

Android ADB stop application command like "force-stop" for non rooted device

The first way
Needs root

Use kill:

adb shell ps => Will list all running processes on the device and their process ids
adb shell kill <PID> => Instead of <PID> use process id of your application

The second way
In Eclipse open DDMS perspective.
In Devices view you will find all running processes.
Choose the process and click on Stop.

enter image description here

The third way
It will kill only background process of an application.

adb shell am kill [options] <PACKAGE> => Kill all processes associated with (the app's package name). This command kills only processes that are safe to kill and that will not impact the user experience.
Options are:

--user | all | current: Specify user whose processes to kill; all users if not specified.

The fourth way
Needs root

adb shell pm disable <PACKAGE> => Disable the given package or component (written as "package/class").

The fifth way
Note that run-as is only supported for apps that are signed with debug keys.

run-as <package-name> kill <pid>

The sixth way
Introduced in Honeycomb

adb shell am force-stop <PACKAGE> => Force stop everything associated with (the app's package name).

P.S.: I know that the sixth method didn't work for you, but I think that it's important to add this method to the list, so everyone will know it.

Can you change what a symlink points to after it is created?

Wouldn't unlinking it and creating the new one do the same thing in the end anyway?

Direct casting vs 'as' operator?

All given answers are good, if i might add something: To directly use string's methods and properties (e.g. ToLower) you can't write:

(string)o.ToLower(); // won't compile

you can only write:

((string)o).ToLower();

but you could write instead:

(o as string).ToLower();

The as option is more readable (at least to my opinion).

jQuery: Check if button is clicked

jQuery(':button').click(function () {
    if (this.id == 'button1') {
        alert('Button 1 was clicked');
    }
    else if (this.id == 'button2') {
        alert('Button 2 was clicked');
    }
});

EDIT:- This will work for all buttons.

How to use the command update-alternatives --config java

You will notice a big change when selecting options if you type in "java -version" after doing so. So if you run update-alternatives --config java and select option 3, you will be using the Sun implementation.
Also, with regards to auto vs manual mode, making a selection should take it out of auto mode per this page stating:

When using the --config option, alternatives will list all of the choices for the link group of which given name is the master link. You will then be prompted for which of the choices to use for the link group. Once you make a change, the link group will no longer be in auto mode. You will need to use the --auto option in order to return to the automatic state.

And I believe auto mode is set when you install the first/only JRE/JDK.

What is a semaphore?

There are two essential concepts to building concurrent programs - synchronization and mutual exclusion. We will see how these two types of locks (semaphores are more generally a kind of locking mechanism) help us achieve synchronization and mutual exclusion.

A semaphore is a programming construct that helps us achieve concurrency, by implementing both synchronization and mutual exclusion. Semaphores are of two types, Binary and Counting.

A semaphore has two parts : a counter, and a list of tasks waiting to access a particular resource. A semaphore performs two operations : wait (P) [this is like acquiring a lock], and release (V)[ similar to releasing a lock] - these are the only two operations that one can perform on a semaphore. In a binary semaphore, the counter logically goes between 0 and 1. You can think of it as being similar to a lock with two values : open/closed. A counting semaphore has multiple values for count.

What is important to understand is that the semaphore counter keeps track of the number of tasks that do not have to block, i.e., they can make progress. Tasks block, and add themselves to the semaphore's list only when the counter is zero. Therefore, a task gets added to the list in the P() routine if it cannot progress, and "freed" using the V() routine.

Now, it is fairly obvious to see how binary semaphores can be used to solve synchronization and mutual exclusion - they are essentially locks.

ex. Synchronization:

thread A{
semaphore &s; //locks/semaphores are passed by reference! think about why this is so.
A(semaphore &s): s(s){} //constructor
foo(){
...
s.P();
;// some block of code B2
...
}

//thread B{
semaphore &s;
B(semaphore &s): s(s){} //constructor
foo(){
...
...
// some block of code B1
s.V();
..
}

main(){
semaphore s(0); // we start the semaphore at 0 (closed)
A a(s);
B b(s);
}

In the above example, B2 can only execute after B1 has finished execution. Let's say thread A comes executes first - gets to sem.P(), and waits, since the counter is 0 (closed). Thread B comes along, finishes B1, and then frees thread A - which then completes B2. So we achieve synchronization.

Now let's look at mutual exclusion with a binary semaphore:

thread mutual_ex{
semaphore &s;
mutual_ex(semaphore &s): s(s){} //constructor
foo(){
...
s.P();
//critical section
s.V();
...
...
s.P();
//critical section
s.V();
...

}

main(){
semaphore s(1);
mutual_ex m1(s);
mutual_ex m2(s);
}

The mutual exclusion is quite simple as well - m1 and m2 cannot enter the critical section at the same time. So each thread is using the same semaphore to provide mutual exclusion for its two critical sections. Now, is it possible to have greater concurrency? Depends on the critical sections. (Think about how else one could use semaphores to achieve mutual exclusion.. hint hint : do i necessarily only need to use one semaphore?)

Counting semaphore: A semaphore with more than one value. Let's look at what this is implying - a lock with more than one value?? So open, closed, and ...hmm. Of what use is a multi-stage-lock in mutual exclusion or synchronization?

Let's take the easier of the two:

Synchronization using a counting semaphore: Let's say you have 3 tasks - #1 and 2 you want executed after 3. How would you design your synchronization?

thread t1{
...
s.P();
//block of code B1

thread t2{
...
s.P();
//block of code B2

thread t3{
...
//block of code B3
s.V();
s.V();
}

So if your semaphore starts off closed, you ensure that t1 and t2 block, get added to the semaphore's list. Then along comes all important t3, finishes its business and frees t1 and t2. What order are they freed in? Depends on the implementation of the semaphore's list. Could be FIFO, could be based some particular priority,etc. (Note : think about how you would arrange your P's and V;s if you wanted t1 and t2 to be executed in some particular order, and if you weren't aware of the implementation of the semaphore)

(Find out : What happens if the number of V's is greater than the number of P's?)

Mutual Exclusion Using counting semaphores: I'd like you to construct your own pseudocode for this (makes you understand things better!) - but the fundamental concept is this : a counting semaphore of counter = N allows N tasks to enter the critical section freely. What this means is you have N tasks (or threads, if you like) enter the critical section, but the N+1th task gets blocked (goes on our favorite blocked-task list), and only is let through when somebody V's the semaphore at least once. So the semaphore counter, instead of swinging between 0 and 1, now goes between 0 and N, allowing N tasks to freely enter and exit, blocking nobody!

Now gosh, why would you need such a stupid thing? Isn't the whole point of mutual exclusion to not let more than one guy access a resource?? (Hint Hint...You don't always only have one drive in your computer, do you...?)

To think about : Is mutual exclusion achieved by having a counting semaphore alone? What if you have 10 instances of a resource, and 10 threads come in (through the counting semaphore) and try to use the first instance?

How to check if a MySQL query using the legacy API was successful?

You can use mysql_errno() for this too.

$result = mysql_query($query);

if(mysql_errno()){
    echo "MySQL error ".mysql_errno().": "
         .mysql_error()."\n<br>When executing <br>\n$query\n<br>";
}

How do I update the element at a certain position in an ArrayList?

Let arrList be the ArrayList and newValue the new String, then just do:

arrList.set(5, newValue);

This can be found in the java api reference here.

Why doesn't file_get_contents work?

//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>        
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> 
</script>
</head>
<body>
<?php    
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData   = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>

C# string replace

You can't use string.replace...as one string is assigned you cannot manipulate. For that, we use string builder. Here is my example. In the HTML page I add [Name] which is replaced by Name. Make sure [Name] is unique or you can give any unique name:

string Name = txtname.Text;
string contents = File.ReadAllText(Server.MapPath("~/Admin/invoice.html"));

StringBuilder builder = new StringBuilder(contents);

builder.Replace("[Name]", Name);

StringReader sr = new StringReader(builder.ToString());

require(vendor/autoload.php): failed to open stream

For me Just run this command first

composer dump-autoload

to add vendor folder.

then run this command

composer update --no-scripts

to update composer.

How do I limit the number of results returned from grep?

For 2 use cases:

  1. I only want n overall results, not n results per file, the grep -m 2 is per file max occurrence.
  2. I often use git grep which doesn't take -m

A good alternative in these scenarios is grep | sed 2q to grep first 2 occurrences across all files. sed documentation: https://www.gnu.org/software/sed/manual/sed.html

Looping through the content of a file in Bash

#!/bin/bash
#
# Change the file name from "test" to desired input file 
# (The comments in bash are prefixed with #'s)
for x in $(cat test.txt)
do
    echo $x
done

How to force Selenium WebDriver to click on element which is not currently visible?

Or you may use Selenium Action Class to simulate user interaction -- For example

    WebDriver = new FirefoxDriver();

    WebElement menu = driver.findElement(By.xpath("")); // the triger event element

    Actions build = new Actions(driver); // heare you state ActionBuider
    build.moveToElement(menu).build().perform(); // Here you perform hover mouse over the needed elemnt to triger the visibility of the hidden
    WebElement m2m= driver.findElement(By.xpath(""));//the previous non visible element
    m2m.click();

Move an array element from one array position to another

You can implement some basic Calculus and create a universal function for moving array element from one position to the other.

For JavaScript it looks like this:

function magicFunction (targetArray, indexFrom, indexTo) { 

    targetElement = targetArray[indexFrom]; 
    magicIncrement = (indexTo - indexFrom) / Math.abs (indexTo - indexFrom); 

    for (Element = indexFrom; Element != indexTo; Element += magicIncrement){ 
        targetArray[Element] = targetArray[Element + magicIncrement]; 
    } 

    targetArray[indexTo] = targetElement; 

}

Check out "moving array elements" at "gloommatter" for detailed explanation.

http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html

Play infinitely looping video on-load in HTML5

The loop attribute should do it:

<video width="320" height="240" autoplay loop>
  <source src="movie.mp4" type="video/mp4" />
  <source src="movie.ogg" type="video/ogg" />
  Your browser does not support the video tag.
</video>

Should you have a problem with the loop attribute (as we had in the past), listen to the videoEnd event and call the play() method when it fires.

Note1: I'm not sure about the behavior on Apple's iPad/iPhone, because they have some restrictions against autoplay.

Note2: loop="true" and autoplay="autoplay" are deprecated

How can I schedule a job to run a SQL query daily?

Using T-SQL: My job is executing stored procedure. You can easy change @command to run your sql.

EXEC msdb.dbo.sp_add_job  
   @job_name = N'MakeDailyJob',   
   @enabled = 1,   
   @description = N'Procedure execution every day' ; 

 EXEC msdb.dbo.sp_add_jobstep  
    @job_name = N'MakeDailyJob',   
    @step_name = N'Run Procedure',   
    @subsystem = N'TSQL',   
    @command = 'exec BackupFromConfig';

 EXEC msdb.dbo.sp_add_schedule  
    @schedule_name = N'Everyday schedule',   
    @freq_type = 4,  -- daily start
    @freq_interval = 1,
    @active_start_time = '230000' ;   -- start time 23:00:00

 EXEC msdb.dbo.sp_attach_schedule  
   @job_name = N'MakeDailyJob',  
   @schedule_name = N'Everyday schedule' ;

 EXEC msdb.dbo.sp_add_jobserver  
   @job_name = N'MakeDailyJob',  
   @server_name = @@servername ;

Determine if a String is an Integer in Java

public boolean isInt(String str){
    return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
            "\\d+") : str.matches("\\d+");
}

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

How to get PID of process I've just started within java program?

I think I have found out a solution, that looks quite bulletproof while working on most platforms. Here is the idea:

  1. Create a JVM-wide mutex that you acquire before spawning new process/killing a process
  2. Use platform-dependent code to acquire list of child processes + pids of your JVM process
  3. Spawn new process
  4. Acquire new list of child processes + pids and compare with the previous list. The one that is new is your guy.

Since you check only for child processes, you cannot be wronged by some other process in the same machine. JVM-wide mutex than allows you to be sure, that the new process is the correct one.

Reading child process list is simpler than getting PID from process objects, because it does not require WIN API calls on windows, and, more importantly, it has been done already in several libs.

Below is an implementation of the above idea using JavaSysMon library. It

class UDKSpawner {

    private int uccPid;
    private Logger uccLog;

    /**
     * Mutex that forces only one child process to be spawned at a time. 
     * 
     */
    private static final Object spawnProcessMutex = new Object();

    /**
     * Spawns a new UDK process and sets {@link #uccPid} to it's PID. To work correctly,
     * the code relies on the fact that no other method in this JVM runs UDK processes and
     * that no method kills a process unless it acquires lock on spawnProcessMutex.
     * @param procBuilder
     * @return 
     */
    private Process spawnUDK(ProcessBuilder procBuilder) throws IOException {
        synchronized (spawnProcessMutex){            
            JavaSysMon monitor = new JavaSysMon();
            DirectUDKChildProcessVisitor beforeVisitor = new DirectUDKChildProcessVisitor();
            monitor.visitProcessTree(monitor.currentPid(), beforeVisitor);
            Set<Integer> alreadySpawnedProcesses = beforeVisitor.getUdkPids();

            Process proc = procBuilder.start();

            DirectUDKChildProcessVisitor afterVisitor = new DirectUDKChildProcessVisitor();
            monitor.visitProcessTree(monitor.currentPid(), afterVisitor);
            Set<Integer> newProcesses = afterVisitor.getUdkPids();

            newProcesses.removeAll(alreadySpawnedProcesses);

            if(newProcesses.isEmpty()){
                uccLog.severe("There is no new UKD PID.");
            }
            else if(newProcesses.size() > 1){
                uccLog.severe("Multiple new candidate UDK PIDs");
            } else {
                uccPid = newProcesses.iterator().next();
            }
            return proc;
        }
    }    

    private void killUDKByPID(){
        if(uccPid < 0){
            uccLog.severe("Cannot kill UCC by PID. PID not set.");
            return;
        }
        synchronized(spawnProcessMutex){
            JavaSysMon monitor = new JavaSysMon();
            monitor.killProcessTree(uccPid, false);
        }
    }

    private static class DirectUDKChildProcessVisitor implements ProcessVisitor {
        Set<Integer> udkPids = new HashSet<Integer>();

        @Override
        public boolean visit(OsProcess op, int i) {
            if(op.processInfo().getName().equals("UDK.exe")){
                udkPids.add(op.processInfo().getPid());
            }
            return false;
        }

        public Set<Integer> getUdkPids() {
            return udkPids;
        }
    }
}

An implementation of the fast Fourier transform (FFT) in C#

I see this is an old thread, but for what it's worth, here's a free (MIT License) 1-D power-of-2-length-only C# FFT implementation I wrote in 2010.

I haven't compared its performance to other C# FFT implementations. I wrote it mainly to compare the performance of Flash/ActionScript and Silverlight/C#. The latter is much faster, at least for number crunching.

/**
 * Performs an in-place complex FFT.
 *
 * Released under the MIT License
 *
 * Copyright (c) 2010 Gerald T. Beauregard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
public class FFT2
{
    // Element for linked list in which we store the
    // input/output data. We use a linked list because
    // for sequential access it's faster than array index.
    class FFTElement
    {
        public double re = 0.0;     // Real component
        public double im = 0.0;     // Imaginary component
        public FFTElement next;     // Next element in linked list
        public uint revTgt;         // Target position post bit-reversal
    }

    private uint m_logN = 0;        // log2 of FFT size
    private uint m_N = 0;           // FFT size
    private FFTElement[] m_X;       // Vector of linked list elements

    /**
     *
     */
    public FFT2()
    {
    }

    /**
     * Initialize class to perform FFT of specified size.
     *
     * @param   logN    Log2 of FFT length. e.g. for 512 pt FFT, logN = 9.
     */
    public void init(
        uint logN )
    {
        m_logN = logN;
        m_N = (uint)(1 << (int)m_logN);

        // Allocate elements for linked list of complex numbers.
        m_X = new FFTElement[m_N];
        for (uint k = 0; k < m_N; k++)
            m_X[k] = new FFTElement();

        // Set up "next" pointers.
        for (uint k = 0; k < m_N-1; k++)
            m_X[k].next = m_X[k+1];

        // Specify target for bit reversal re-ordering.
        for (uint k = 0; k < m_N; k++ )
            m_X[k].revTgt = BitReverse(k,logN);
    }

    /**
     * Performs in-place complex FFT.
     *
     * @param   xRe     Real part of input/output
     * @param   xIm     Imaginary part of input/output
     * @param   inverse If true, do an inverse FFT
     */
    public void run(
        double[] xRe,
        double[] xIm,
        bool inverse = false )
    {
        uint numFlies = m_N >> 1;   // Number of butterflies per sub-FFT
        uint span = m_N >> 1;       // Width of the butterfly
        uint spacing = m_N;         // Distance between start of sub-FFTs
        uint wIndexStep = 1;        // Increment for twiddle table index

        // Copy data into linked complex number objects
        // If it's an IFFT, we divide by N while we're at it
        FFTElement x = m_X[0];
        uint k = 0;
        double scale = inverse ? 1.0/m_N : 1.0;
        while (x != null)
        {
            x.re = scale*xRe[k];
            x.im = scale*xIm[k];
            x = x.next;
            k++;
        }

        // For each stage of the FFT
        for (uint stage = 0; stage < m_logN; stage++)
        {
            // Compute a multiplier factor for the "twiddle factors".
            // The twiddle factors are complex unit vectors spaced at
            // regular angular intervals. The angle by which the twiddle
            // factor advances depends on the FFT stage. In many FFT
            // implementations the twiddle factors are cached, but because
            // array lookup is relatively slow in C#, it's just
            // as fast to compute them on the fly.
            double wAngleInc = wIndexStep * 2.0*Math.PI/m_N;
            if (inverse == false)
                wAngleInc *= -1;
            double wMulRe = Math.Cos(wAngleInc);
            double wMulIm = Math.Sin(wAngleInc);

            for (uint start = 0; start < m_N; start += spacing)
            {
                FFTElement xTop = m_X[start];
                FFTElement xBot = m_X[start+span];

                double wRe = 1.0;
                double wIm = 0.0;

                // For each butterfly in this stage
                for (uint flyCount = 0; flyCount < numFlies; ++flyCount)
                {
                    // Get the top & bottom values
                    double xTopRe = xTop.re;
                    double xTopIm = xTop.im;
                    double xBotRe = xBot.re;
                    double xBotIm = xBot.im;

                    // Top branch of butterfly has addition
                    xTop.re = xTopRe + xBotRe;
                    xTop.im = xTopIm + xBotIm;

                    // Bottom branch of butterly has subtraction,
                    // followed by multiplication by twiddle factor
                    xBotRe = xTopRe - xBotRe;
                    xBotIm = xTopIm - xBotIm;
                    xBot.re = xBotRe*wRe - xBotIm*wIm;
                    xBot.im = xBotRe*wIm + xBotIm*wRe;

                    // Advance butterfly to next top & bottom positions
                    xTop = xTop.next;
                    xBot = xBot.next;

                    // Update the twiddle factor, via complex multiply
                    // by unit vector with the appropriate angle
                    // (wRe + j wIm) = (wRe + j wIm) x (wMulRe + j wMulIm)
                    double tRe = wRe;
                    wRe = wRe*wMulRe - wIm*wMulIm;
                    wIm = tRe*wMulIm + wIm*wMulRe;
                }
            }

            numFlies >>= 1;     // Divide by 2 by right shift
            span >>= 1;
            spacing >>= 1;
            wIndexStep <<= 1;   // Multiply by 2 by left shift
        }

        // The algorithm leaves the result in a scrambled order.
        // Unscramble while copying values from the complex
        // linked list elements back to the input/output vectors.
        x = m_X[0];
        while (x != null)
        {
            uint target = x.revTgt;
            xRe[target] = x.re;
            xIm[target] = x.im;
            x = x.next;
        }
    }

    /**
     * Do bit reversal of specified number of places of an int
     * For example, 1101 bit-reversed is 1011
     *
     * @param   x       Number to be bit-reverse.
     * @param   numBits Number of bits in the number.
     */
    private uint BitReverse(
        uint x,
        uint numBits)
    {
        uint y = 0;
        for (uint i = 0; i < numBits; i++)
        {
            y <<= 1;
            y |= x & 0x0001;
            x >>= 1;
        }
        return y;
    }

}

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

It seems that you've omitted the value attribute in HTML markup.

Add it there as <input value="" ... >.

How exactly to use Notification.Builder

Notification.Builder API 11 or NotificationCompat.Builder API 1

This is a usage example.

Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
        YOUR_PI_REQ_CODE, notificationIntent,
        PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) ctx
        .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);

builder.setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.some_img)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
            .setTicker(res.getString(R.string.your_ticker))
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle(res.getString(R.string.your_notif_title))
            .setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();

nm.notify(YOUR_NOTIF_ID, n);

What's an Aggregate Root?

In Erlang there is no need to differentiate between aggregates, once the aggregate is composed by data structures inside the state, instead of OO composition. See an example: https://github.com/bryanhunter/cqrs-with-erlang/tree/ndc-london

Trim leading and trailing spaces from a string in awk

If it is safe to assume only one set of spaces in column two (which is the original example):

awk '{print $1$2}' /tmp/input.txt

Adding another field, e.g. awk '{print $1$2$3}' /tmp/input.txt will catch two sets of spaces (up to three words in column two), and won't break if there are fewer.

If you have an indeterminate (large) number of space delimited words, I'd use one of the previous suggestions, otherwise this solution is the easiest you'll find using awk.

How to change the font on the TextView?

  1. add class FontTextView.java:


public class FontTextView extends TextView {
    String fonts[] = {"HelveticaNeue.ttf", "HelveticaNeueLight.ttf", "motschcc.ttf", "symbol.ttf"};

    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (!isInEditMode()) {
            init(attrs);
        }

    }

    public FontTextView(Context context) {
        super(context);
        if (!isInEditMode()) {
            init(null);
        }
    }

    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
            if (a.getString(R.styleable.FontTextView_font_type) != null) {
                String fontName = fonts[Integer.valueOf(a.getString(R.styleable.FontTextView_font_type))];

                if (fontName != null) {
                    Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/" + fontName);
                    setTypeface(myTypeface);
                }
                a.recycle();
            }
        }
    }
}


  1. add to assets library font
    enter image description here


  1. add to attrs.xml , The numbers should be in the order in array class.

    <declare-styleable name="FontTextView">
    <attr name="font_type" format="enum">
        <enum name="HelveticaNeue" value="0"/>
        <enum name="HelveticaNeueLight" value="1"/>
        <enum name="motschcc" value="2"/>
        <enum name="symbol" value="3"/>
    </attr>
    


  1. Select a font from the list
    enter image description here

How to test if a string is basically an integer in quotes using Ruby

The Best and Simple way is using Float

val = Float "234" rescue nil

Float "234" rescue nil #=> 234.0

Float "abc" rescue nil #=> nil

Float "234abc" rescue nil #=> nil

Float nil rescue nil #=> nil

Float "" rescue nil #=> nil

Integer is also good but it will return 0 for Integer nil

Change application's starting activity

If you are using Android Studio and you might have previously selected another Activity to launch.

Click on Run > Edit configuration and then make sure that Launch default Activity is selected.

Launch default Activity

npm install private github repositories by dependency in package.json

For those of you who came here for public directories, from the npm docs: https://docs.npmjs.com/files/package.json#git-urls-as-dependencies

Git URLs as Dependencies

Git urls can be of the form:

git://github.com/user/project.git#commit-ish
git+ssh://user@hostname:project.git#commit-ish
git+ssh://user@hostname/project.git#commit-ish
git+http://user@hostname/project/blah.git#commit-ish
git+https://user@hostname/project/blah.git#commit-ish

The commit-ish can be any tag, sha, or branch which can be supplied as an argument to git checkout. The default is master.

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

In my case this was the error.

Exception in thread "main" java.lang.AbstractMethodError: oracle.jdbc.driver.T4CConnection.isValid(I)Z at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:917) at org.apache.tomcat.dbcp.dbcp2.PoolableConnection.validate(PoolableConnection.java:282) at org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:356) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2306) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2289) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2038) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1532) at beans.Test.main(Test.java:24)

Solution: I just change ojdbc14.jar to ojdbc6.jar

Maximum Length of Command Line String

In Windows 10, it's still 8191 characters...at least on my machine.

It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.

Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.

echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat

How do I hide an element on a click event anywhere outside of the element?

This doesn't work - it hides the .myDIV when you click inside of it.

$('.openDiv').click(function(e) {
$('.myDiv').show(); 
e.stopPropagation();
})

$(document).click(function(){  
$('.myDiv').hide(); 

});

});

<a class="openDiv">DISPLAY DIV</a>

<div class="myDiv">HIDE DIV</div>

header('HTTP/1.0 404 Not Found'); not doing anything

You could try specifying an HTTP response code using an optional parameter:

header('HTTP/1.0 404 Not Found', true, 404);

Initializing default values in a struct

You can do it by using a constructor, like this:

struct Date
{
int day;
int month;
int year;

Date()
{
    day=0;
    month=0;
    year=0;
}
};

or like this:

struct Date
{
int day;
int month;
int year;

Date():day(0),
       month(0),
       year(0){}
};

In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).

How do I use CREATE OR REPLACE?

I would do something like this

  begin
     for i in (select table_name from user_tables where table_name = 'FOO') loop
        execute immediate 'drop table '||i.table_name;
     end loop;
  end;

  execute immediate 'CREATE TABLE FOO (id NUMBER,
                                       title VARCHAR2(4000)) ';

How to install the current version of Go in Ubuntu Precise

On recent Ubuntu (20.10) sudo apt-get install golang works fine; it will install version 1.14.

How do I make a semi transparent background?

This is simple and sort. Use hsla css function like below

.transparent {
   background-color: hsla(0,0%,4%,.4);
}

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

SQL - Rounding off to 2 decimal places

What ever you use in denomination should be in decimal, for example 1548/100 will give 15.00

If we replace 100 with 100.0 in our example the we will get 15.48

select 1548/100 
15.00000

select 1548/100.0
15.4800

0

PHPmailer sending HTML CODE

or if you have still problems you can use this

$mail->Body =  html_entity_decode($Body);

Javascript variable access in HTML

The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph). Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.

Example:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <body>_x000D_
        <!--\|/id here-->_x000D_
        <p id="myText"></p>_x000D_
        <p id="myTextTag"></p>_x000D_
        <script>_x000D_
            <!--Here we retrieve the text and show what we want to write..._x000D_
            var text = document.getElementById("myText");_x000D_
            var tag = document.getElementById("myTextTag");_x000D_
            var toWrite = "Hello"_x000D_
            var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"_x000D_
            <!--...and here we are actually affecting the text.-->_x000D_
            text.innerHTML = toWrite_x000D_
            tag.innerHTML = toWriteTag_x000D_
        </script>_x000D_
    <body>_x000D_
<html>
_x000D_
_x000D_
_x000D_

SQL split values to multiple rows

My variant: stored procedure that takes table name, field names and delimiter as arguments. Inspired by post http://www.marcogoncalves.com/2011/03/mysql-split-column-string-into-rows/

delimiter $$

DROP PROCEDURE IF EXISTS split_value_into_multiple_rows $$
CREATE PROCEDURE split_value_into_multiple_rows(tablename VARCHAR(20),
    id_column VARCHAR(20), value_column VARCHAR(20), delim CHAR(1))
  BEGIN
    DECLARE id INT DEFAULT 0;
    DECLARE value VARCHAR(255);
    DECLARE occurrences INT DEFAULT 0;
    DECLARE i INT DEFAULT 0;
    DECLARE splitted_value VARCHAR(255);
    DECLARE done INT DEFAULT 0;
    DECLARE cur CURSOR FOR SELECT tmp_table1.id, tmp_table1.value FROM 
        tmp_table1 WHERE tmp_table1.value IS NOT NULL AND tmp_table1.value != '';
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    SET @expr = CONCAT('CREATE TEMPORARY TABLE tmp_table1 (id INT NOT NULL, value VARCHAR(255)) ENGINE=Memory SELECT ',
        id_column,' id, ', value_column,' value FROM ',tablename);
    PREPARE stmt FROM @expr;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    DROP TEMPORARY TABLE IF EXISTS tmp_table2;
    CREATE TEMPORARY TABLE tmp_table2 (id INT NOT NULL, value VARCHAR(255) NOT NULL) ENGINE=Memory;

    OPEN cur;
      read_loop: LOOP
        FETCH cur INTO id, value;
        IF done THEN
          LEAVE read_loop;
        END IF;

        SET occurrences = (SELECT CHAR_LENGTH(value) -
                           CHAR_LENGTH(REPLACE(value, delim, '')) + 1);
        SET i=1;
        WHILE i <= occurrences DO
          SET splitted_value = (SELECT TRIM(SUBSTRING_INDEX(
              SUBSTRING_INDEX(value, delim, i), delim, -1)));
          INSERT INTO tmp_table2 VALUES (id, splitted_value);
          SET i = i + 1;
        END WHILE;
      END LOOP;

      SELECT * FROM tmp_table2;
    CLOSE cur;
    DROP TEMPORARY TABLE tmp_table1;
  END; $$

delimiter ;

Usage example (normalization):

CALL split_value_into_multiple_rows('my_contacts', 'contact_id', 'interests', ',');

CREATE TABLE interests (
  interest_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  interest VARCHAR(30) NOT NULL
) SELECT DISTINCT value interest FROM tmp_table2;

CREATE TABLE contact_interest (
  contact_id INT NOT NULL,
  interest_id INT NOT NULL,
  CONSTRAINT fk_contact_interest_my_contacts_contact_id FOREIGN KEY (contact_id) REFERENCES my_contacts (contact_id),
  CONSTRAINT fk_contact_interest_interests_interest_id FOREIGN KEY (interest_id) REFERENCES interests (interest_id)
) SELECT my_contacts.contact_id, interests.interest_id
    FROM my_contacts, tmp_table2, interests
    WHERE my_contacts.contact_id = tmp_table2.id AND interests.interest = tmp_table2.value;

How to delete rows from a pandas DataFrame based on a conditional expression

You can assign the DataFrame to a filtered version of itself:

df = df[df.score > 50]

This is faster than drop:

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test[test.x < 0]
# 54.5 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test.drop(test[test.x > 0].index, inplace=True)
# 201 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test.drop(test[test.x > 0].index)
# 194 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

CURRENT_TIMESTAMP in milliseconds

In mysql, it is possible to use the uuid function to extract milliseconds.

select conv( 
            concat(
                   substring(uid,16,3), 
                   substring(uid,10,4), 
                   substring(uid,1,8))
                   ,16,10) 
            div 10000 
            - (141427 * 24 * 60 * 60 * 1000) as current_mills
from (select uuid() uid) as alias;

Result:

+---------------+
| current_mills |
+---------------+
| 1410954031133 |
+---------------+

It also works in older mysql versions!

Thank you to this page: http://rpbouman.blogspot.com.es/2014/06/mysql-extracting-timstamp-and-mac.html

Getting time elapsed in Objective-C

For percise time measurements (like GetTickCount), also take a look at mach_absolute_time and this Apple Q&A: http://developer.apple.com/qa/qa2004/qa1398.html.

Wait some seconds without blocking UI execution

This is a good case for using another thread:

// Call some method
this.Method();

Task.Factory.StartNew(() =>
{
    Thread.Sleep(20000);

    // Do things here.
    // NOTE: You may need to invoke this to your main thread depending on what you're doing
});

The above code expects .NET 4.0 or above, otherwise try:

ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
{
    Thread.Sleep(20000);

    // Do things here
}));

Allow a div to cover the whole page instead of the area within the container

please try with setting margin and padding to 0 on body.

<body style="margin: 0 0 0 0; padding: 0 0 0 0;">

How to unlock android phone through ADB

if the device is locked with black screen run the following:

  1. adb shell input keyevent 26 - this will turn screen on
  2. adb shell input keyevent 82 - this will unlock and ask for pin
  3. adb shell input text xxxx && adb shell input keyevent 66 - this will input your pin and press enter, unlocking device to home screen

Regex expressions in Java, \\s vs. \\s+

The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times

Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}?   X, exactly n times
X{n,}?  X, at least n times
X{n,m}? X, at least n but not more than m times

Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+   X, exactly n times
X{n,}+  X, at least n times
X{n,m}+ X, at least n but not more than m times

What does enctype='multipart/form-data' mean?

Set the method attribute to POST because file content can't be put inside a URL parameter using a form.

Set the value of enctype to multipart/form-data because the data will be split into multiple parts, one for each file plus one for the text of the form body that may be sent with them.

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

Recently I faced the issue while working on some legacy code. After googling I found that the issue is everywhere but without any concrete resolution. I worked on various parts of the exception message and analyzed below.

Analysis:

  1. SSLException: exception happened with the SSL (Secure Socket Layer), which is implemented in javax.net.ssl package of the JDK (openJDK/oracleJDK/AndroidSDK)
  2. Read error ssl=# I/O error during system call: Error occured while reading from the Secure socket. It happened while using the native system libraries/driver. Please note that all the platforms solaris, Windows etc. have their own socket libraries which is used by the SSL. Windows uses WINSOCK library.
  3. Connection reset by peer: This message is reported by the system library (Solaris reports ECONNRESET, Windows reports WSAECONNRESET), that the socket used in the data transfer is no longer usable because an existing connection was forcibly closed by the remote host. One needs to create a new secure path between the host and client

Reason:

Understanding the issue, I try finding the reason behind the connection reset and I came up with below reasons:

  • The peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close.
  • This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with Network dropped connection on reset(On Windows(WSAENETRESET)) and Subsequent operations fail withConnection reset by peer(On Windows(WSAECONNRESET)).
  • If the target server is protected by Firewall, which is true in most of the cases, the Time to live (TTL) or timeout associated with the port forcibly closes the idle connection at given timeout. this is something of our interest

Resolution:

  1. Events on the server side such as sudden service stop, rebooted, network interface disabled can not be handled by any means.
  2. On the server side, Configure firewall for the given port with the higher Time to Live (TTL) or timeout values such as 3600 secs.
  3. Clients can "try" keeping the network active to avoid or reduce the Connection reset by peer.
  4. Normally on going network traffic keeps the connection alive and problem/exception is not seen frequently. Strong Wifi has least chances of Connection reset by peer.
  5. With the mobile networks 2G, 3G and 4G where the packet data delivery is intermittent and dependent on the mobile network availability, it may not reset the TTL timer on the server side and results into the Connection reset by peer.

Here are the terms suggested to set on various forums to resolve the issue

  • ConnectionTimeout: Used only at the time out making the connection. If host takes time to connection higher value of this makes the client wait for the connection.
  • SoTimeout: Socket timeout-It says the maximum time within which the a data packet is received to consider the connection as active.If no data received within the given time, the connection is assumed as stalled/broken.
  • Linger: Upto what time the socket should not be closed when data is queued to be sent and the close socket function is called on the socket.
  • TcpNoDelay: Do you want to disable the buffer that holds and accumulates the TCP packets and send them once a threshold is reached? Setting this to true will skip the TCP buffering so that every request is sent immediately. Slowdowns in the network may be caused by an increase in network traffic due to smaller and more frequent packet transmission.

So none of the above parameter helps keeping the network alive and thus ineffective.

I found one setting that may help resolving the issue which is this functions

setKeepAlive(true)
setSoKeepalive(HttpParams params, enableKeepalive="true") 

How did I resolve my issue?

  • Set the HttpConnectionParams.setSoKeepAlive(params, true)
  • Catch the SSLException and check for the exception message for Connection reset by peer
  • If exception is found, store the download/read progress and create a new connection.
  • If possible resume the download/read else restart the download

I hope the details help. Happy Coding...

How to upgrade Git to latest version on macOS?

I did it in this way:

  1. Open GitHub application installed on Mac
  2. Click on Advanced tab → Install command line tools
  3. Once you get a message that all commands have been installed close your terminal and reopen it.
  4. Now check git --version, it should give you the latest version.

Setting width/height as percentage minus pixels

Thanks, i solved mine with your help, tweaking it a little since i want a div 100% width 100% heigth (less height of a bottom bar) and no scroll on body (without hack / hiding scroll bars).

For CSS:

 html{
  width:100%;height:100%;margin:0px;border:0px;padding:0px;
 }
 body{
  position:relative;width:100%;height:100%;margin:0px;border:0px;padding:0px;
 }
 div.adjusted{
  position:absolute;width:auto;height:auto;left:0px;right:0px;top:0px;bottom:36px;margin:0px;border:0px;padding:0px;
 }
 div.the_bottom_bar{
  width:100%;height:31px;margin:0px;border:0px;padding:0px;
}

For HTML:

<body>
<div class="adjusted">
 // My elements that go on dynamic size area
 <div class="the_bottom_bar">
  // My elements that goes on bottom bar (fixed heigh of 31 pixels)
 </div>  
</div>  

That did the trick, oh yes i put a value little greatter on div.adjusted for bottom than for bottom bar height, else the vertical scrollbar appears, i adjusted to be the nearest value.

That difference is because one of the elements on dynamic area is adding an extra bottom hole that i do not know how to get rid of... it is a video tag (HTML5), please note i put that video tag with this css (so there is no reason for it to make a bottom hole, but it does):

 video{
  width:100%;height:100%;margin:0px;border:0px;padding:0px;
 }

The objetive: Have a video that takes the 100% of the brower (and resizes dynamically when browser is resized, but without altering the aspect ratio) less a bottom space that i use for a div with some texts, buttons, etc (and validators w3c & css of course).

EDIT: I found the reason, video tag is like text, not a block element, so i fixed it with this css:

 video{
  display:block;width:100%;height:100%;margin:0px;border:0px;padding:0px;
 }

Note the display:block; on video tag.

Powershell equivalent of bash ampersand (&) for forking/running background processes

ps2> start-job {start-sleep 20}

i have not yet figured out how to get stdout in realtime, start-job requires you to poll stdout with get-job

update: i couldn't start-job to easily do what i want which is basically the bash & operator. here's my best hack so far

PS> notepad $profile #edit init script -- added these lines
function beep { write-host `a }
function ajp { start powershell {ant java-platform|out-null;beep} } #new window, stderr only, beep when done
function acjp { start powershell {ant clean java-platform|out-null;beep} }
PS> . $profile #re-load profile script
PS> ajp

Constructor of an abstract class in C#

I too want to make some shine on abstract surface All answer has covered almost all the things. Still my 2 cents

abstract classes are normal classes with A few exceptions

  1. You any client/Consumer of that class can't create object of that class, It never means that It's constructor will never call. Its derived class can choose which constructor to call.(as depicted in some answer)
  2. It may has abstract function.

Pull all images from a specified directory and then display them

In case anyone is looking for recursive.

<?php

echo scanDirectoryImages("images");

/**
 * Recursively search through directory for images and display them
 * 
 * @param  array  $exts
 * @param  string $directory
 * @return string
 */
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
    if (substr($directory, -1) == '/') {
        $directory = substr($directory, 0, -1);
    }
    $html = '';
    if (
        is_readable($directory)
        && (file_exists($directory) || is_dir($directory))
    ) {
        $directoryList = opendir($directory);
        while($file = readdir($directoryList)) {
            if ($file != '.' && $file != '..') {
                $path = $directory . '/' . $file;
                if (is_readable($path)) {
                    if (is_dir($path)) {
                        return scanDirectoryImages($path, $exts);
                    }
                    if (
                        is_file($path)
                        && in_array(end(explode('.', end(explode('/', $path)))), $exts)
                    ) {
                        $html .= '<a href="' . $path . '"><img src="' . $path
                            . '" style="max-height:100px;max-width:100px" /></a>';
                    }
                }
            }
        }
        closedir($directoryList);
    }
    return $html;
}

What does 'public static void' mean in Java?

Public - means that the class (program) is available for use by any other class.

Static - creates a class. Can also be applied to variables and methods,making them class methods/variables instead of just local to a particular instance of the class.

Void - this means that no product is returned when the class completes processing. Compare this with helper classes that provide a return value to the main class,these operate like functions; these do not have void in the declaration.

How to get a list of images on docker registry v2

If some on get this far.

Taking what others have already said above. Here is a one-liner that puts the answer into a text file formatted, json.

curl "http://mydocker.registry.domain/v2/_catalog?n=2000" | jq . - > /tmp/registry.lst

This looks like

{
  "repositories": [
    "somerepo/somecontiner",
    "somerepo_other/someothercontiner",
 ...
  ]
}

You might need to change the `?n=xxxx' to match how many containers you have.

Next is a way to automatically remove old and unused containers.

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Generating random, unique values C#

And here my version of finding N random unique numbers using HashSet. Looks pretty simple, since HashSet can contain only different items. It's interesting - would it be faster then using List or Shuffler?

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class RnDHash
    {
        static void Main()
        {
            HashSet<int> rndIndexes = new HashSet<int>();
            Random rng = new Random();
            int maxNumber;
            Console.Write("Please input Max number: ");
            maxNumber = int.Parse(Console.ReadLine());
            int iter = 0;
            while (rndIndexes.Count != maxNumber)
            {
                int index = rng.Next(maxNumber);
                rndIndexes.Add(index);
                iter++;
            }
            Console.WriteLine("Random numbers were found in {0} iterations: ", iter);
            foreach (int num in rndIndexes)
            {
                Console.WriteLine(num);
            }
            Console.ReadKey();
        }
    }
}

How do I configure the proxy settings so that Eclipse can download new plugins?

Just to add to the thread as a POSSIBLE solution, I faced a similar issue when developing on a Linux system that was behind a company firewall. However, using a Windows XP machine, Eclipse was able to access different update sites just fine as both the manual and native network connection providers worked just fine using the company proxy.

After stumbling around for some time, I came across a discussion about using NTLMv2 and an implementation to be found at http://cntlm.sourceforge.net/. To whomever posted this, I give much credit to as it helped me get past the issue running on Linux. As a side note, I was using Eclipse 3.6.2 / Helios on both the Linux and Windows distros.

Best of luck on finding a solution!

How do you rotate a two dimensional array?

Here is a C# static generic method that does the work for you. Variables are well-named, so you can easily catch the idea of the algorythm.

private static T[,] Rotate180 <T> (T[,] matrix)
{
    var height = matrix.GetLength (0);
    var width = matrix.GetLength (1);
    var answer = new T[height, width];

    for (int y = 0; y < height / 2; y++)
    {
        int topY = y;
        int bottomY = height - 1 - y;
        for (int topX = 0; topX < width; topX++)
        {
            var bottomX = width - topX - 1;
            answer[topY, topX] = matrix[bottomY, bottomX];
            answer[bottomY, bottomX] = matrix[topY, topX];
        }
    }

    if (height % 2 == 0)
        return answer;

    var centerY = height / 2;
    for (int leftX = 0; leftX < Mathf.CeilToInt(width / 2f); leftX++)
    {
        var rightX = width - 1 - leftX;
        answer[centerY, leftX] = matrix[centerY, rightX];
        answer[centerY, rightX] = matrix[centerY, leftX];
    }

    return answer;
}

Git resolve conflict using --ours/--theirs for all files

In case anyone else is looking to simply overwrite everything from one branch (say master) with the contents of another, there's an easier way:

git merge origin/master --strategy=ours

Thanks to https://stackoverflow.com/a/1295232/560114

Or for the other way around, see Is there a "theirs" version of "git merge -s ours"?

SQL DROP TABLE foreign key constraint

Here is another way to drop all tables correctly, using sp_MSdropconstraints procedure. The shortest code I could think of:

exec sp_MSforeachtable "declare @name nvarchar(max); set @name = parsename('?', 1); exec sp_MSdropconstraints @name";
exec sp_MSforeachtable "drop table ?";

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

For rails6, I was facing the same problem, as I was missing following files, once I added them, the issue resolved:

1. config/master.key
2. config/credentials.yml.enc

Make sure you have this files.!!!

How to launch html using Chrome at "--allow-file-access-from-files" mode?

As of this writing, in OS X, it will usually look like this

"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files

If you are a freak like me, and put your apps in ~/Applications, then it will be

"/Users/yougohere/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files

If neither of those are working, then type chrome://version in your Chrome address bar, and it will tell you what "command line" invocation you should be using. Just add --allow-file-access-from-files to that.

How to add minutes to my Date

tl;dr

LocalDateTime.parse( 
    "2016-01-23 12:34".replace( " " , "T" )
)
.atZone( ZoneId.of( "Asia/Karachi" ) )
.plusMinutes( 10 )

java.time

Use the excellent java.time classes for date-time work. These classes supplant the troublesome old date-time classes such as java.util.Date and java.util.Calendar.

ISO 8601

The java.time classes use standard ISO 8601 formats by default for parsing/generating strings of date-time values. To make your input string comply, replace the SPACE in the middle with a T.

String input = "2016-01-23 12:34" ;
String inputModified = input.replace( " " , "T" );

LocalDateTime

Parse your input string as a LocalDateTime as it lacks any info about time zone or offset-from-UTC.

LocalDateTime ldt = LocalDateTime.parse( inputModified );

Add ten minutes.

LocalDateTime ldtLater = ldt.plusMinutes( 10 );

ldt.toString(): 2016-01-23T12:34

ldtLater.toString(): 2016-01-23T12:44

See live code in IdeOne.com.

That LocalDateTime has no time zone, so it does not represent a point on the timeline. Apply a time zone to translate to an actual moment. Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland, or Asia/Karachi. Never use the 3-4 letter abbreviation such as EST or IST or PKT as they are not true time zones, not standardized, and not even unique(!).

ZonedDateTime

If you know the intended time zone for this value, apply a ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "Asia/Karachi" );
ZonedDateTime zdt = ldt.atZone( z );

zdt.toString(): 2016-01-23T12:44+05:00[Asia/Karachi]

Anomalies

Think about whether to add those ten minutes before or after adding a time zone. You may get a very different result because of anomalies such as Daylight Saving Time (DST) that shift the wall-clock time.

Whether you should add the 10 minutes before or after adding the zone depends on the meaning of your business scenario and rules.

Tip: When you intend a specific moment on the timeline, always keep the time zone information. Do not lose that info, as done with your input data. Is the value 12:34 meant to be noon in Pakistan or noon in France or noon in Québec? If you meant noon in Pakistan, say so by including at least the offset-from-UTC (+05:00), and better still, the name of the time zone (Asia/Karachi).

Instant

If you want the same moment as seen through the lens of UTC, extract an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant();

Convert

Avoid the troublesome old date-time classes whenever possible. But if you must, you can convert. Call new methods added to the old classes.

java.util.Date utilDate = java.util.Date.from( instant );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to modify PATH for Homebrew?

There are many ways to update your path. Jun1st answer works great. Another method is to augment your .bash_profile to have:

export PATH="/usr/local/bin:/usr/local/sbin:~/bin:$PATH"

The line above places /usr/local/bin and /usr/local/sbin in front of your $PATH. Once you source your .bash_profile or start a new terminal you can verify your path by echo'ing it out.

$ echo $PATH
/usr/local/bin:/usr/local/sbin:/Users/<your account>/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

Once satisfied with the result running $ brew doctor again should no longer produce your error.

This blog post helped me out in resolving issues I ran into. http://moncefbelyamani.com/how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/

curl_exec() always returns false

In my case I need to set VERIFYHOST and VERIFYPEER to false, like this:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

before the call to curl_exec($ch).

Because i am working between two development environments with self-assigned certificates. With valid certificates there is no need to set VERIFYHOST and VERIFYPEER to false because the curl_exec($ch) method will work and return the response you expect.

Get first date of current month in java

In order to get a Date (that can be used in JPA later on), I did

Date startOfMonth = Date.from(LocalDate.now().withDayOfMonth(1).atStartOfDay().toInstant(ZoneOffset.UTC));
  • I take current date LocalDate.now()
  • Move it to first day of the month withDayOfMonth(1)
  • Move it to the sart of the day atStartOfDay() to get rid of hours and minutes
  • and deal with the TimeZone issues by changing it into an Instant with the "right" ZoneOffset.

Magento addFieldToFilter: Two fields, match as OR, not AND

Thanks Anda, your post has been a great help!! However the OR sentence didnt' quite work for me and I was getting an error: getCollection() "invalid argument supplied for foreach".

So this is what I ended with (notice the attribute being specified 3 times instead of 2 in this case):

  $collection->addFieldToFilter('attribute', array(  
    array('attribute'=>'my_field1','eq'=>'my_value1'),            
    array('attribute'=>'my_field2','eq'=>'my_value2') ));

addFieldToFilter first requires a field and then condition -> link.

How to add a ListView to a Column in Flutter?

Reason for the error:

Column expands to the maximum size in main axis direction (vertical axis), and so does the ListView.

Solutions

So, you need to constrain the height of the ListView. There are many ways of doing it, you can choose that best suits your need.


  1. If you want to allow ListView to take up all remaining space inside Column use Expanded.

    Column(
      children: <Widget>[
        Expanded(
          child: ListView(...),
        )
      ],
    )
    

  1. If you want to limit your ListView to certain height, you can use SizedBox.

    Column(
      children: <Widget>[
        SizedBox(
          height: 200, // constrain height
          child: ListView(),
        )
      ],
    )
    

  1. If your ListView is small, you may try shrinkWrap property on it.

    Column(
      children: <Widget>[
        ListView(
          shrinkWrap: true, // use it
        )
      ],
    )
    

Get current url in Angular

other.component.ts

So final correct solution is :

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router'; 

/* 'router' it must be in small case */

    @Component({
      selector: 'app-other',
      templateUrl: './other.component.html',
      styleUrls: ['./other.component.css']
    })

    export class OtherComponent implements OnInit {

        public href: string = "";
        url: string = "asdf";

        constructor(private router : Router) {} // make variable private so that it would be accessible through out the component

        ngOnInit() {
            this.href = this.router.url;
            console.log(this.router.url);
        }
    }

how to destroy bootstrap modal window completely?

My approach would be to use the clone() method of jQuery. It creates a copy of your element, and that's what you want : a copy of your first unaltered modal, that you can replace at your wish : Demo (jsfiddle)

var myBackup = $('#myModal').clone();

// Delegated events because we make a copy, and the copied button does not exist onDomReady
$('body').on('click','#myReset',function() {
    $('#myModal').modal('hide').remove();
    var myClone = myBackup.clone();
    $('body').append(myClone);
});

The markup I used is the most basic, so you just need to bind on the right elements / events, and you should have your wizard reset.

Be careful to bind with delegated events, or rebind at each reset the inner elements of your modal so that each new modal behave the same way.

Set the maximum character length of a UITextField in Swift

Just in case, don't forget to guard range size before applying it to the string. Otherwise, you will get crash if the user will do this:

Type maximum length text Insert something (Nothing will be inserted due to length limitation, but iOS doesn't know about it) Undo insertion (You get crash, cause range will be greater than actual string size)

Also, using iOS 13 users can accidentally trigger this by gestures

I suggest you add to your project this

extension String {
    func replace(with text: String, in range: NSRange) -> String? {
        guard range.location + range.length <= self.count else { return nil }
        return (self as NSString).replacingCharacters(in: range, with: text)
    }
}

And use it like this:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    guard let newText = textView.text.replace(with: text, in: range) else { return false }
    return newText.count < maxNumberOfCharacters
}

Otherwise, you will constantly be getting crashed in your app

How to use Google Translate API in my Java application?

Generate your own API key here. Check out the documentation here.

You may need to set up a billing account when you try to enable the Google Cloud Translation API in your account.

Below is a quick start example which translates two English strings to Spanish:

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;

public class QuickstartSample
{
    public static void main(String[] arguments) throws IOException, GeneralSecurityException
    {
        Translate t = new Translate.Builder(
                GoogleNetHttpTransport.newTrustedTransport()
                , GsonFactory.getDefaultInstance(), null)
                // Set your application name
                .setApplicationName("Stackoverflow-Example")
                .build();
        Translate.Translations.List list = t.new Translations().list(
                Arrays.asList(
                        // Pass in list of strings to be translated
                        "Hello World",
                        "How to use Google Translate from Java"),
                // Target language
                "ES");

        // TODO: Set your API-Key from https://console.developers.google.com/
        list.setKey("your-api-key");
        TranslationsListResponse response = list.execute();
        for (TranslationsResource translationsResource : response.getTranslations())
        {
            System.out.println(translationsResource.getTranslatedText());
        }
    }
}

Required maven dependencies for the code snippet:

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-translate</artifactId>
    <version>LATEST</version>
</dependency>

<dependency>
    <groupId>com.google.http-client</groupId>
    <artifactId>google-http-client-gson</artifactId>
    <version>LATEST</version>
</dependency>

Best ways to teach a beginner to program?

If he's interested, aren't the minor details the good parts? Using python, you've already cut the GUI off of it so that confusion is gone. Why not pick a project, a game or something, and implement it. The classic hi-lo number guessing game can be simply implemented from the command line in 20-30 lines of code (depending on language of course) and gives you variables, conditions, loops, and user input.

How to access child's state in React?

Now You can access the InputField's state which is the child of FormEditor .

Basically whenever there is a change in the state of the input field(child) we are getting the value from the event object and then passing this value to the Parent where in the state in the Parent is set.

On button click we are just printing the state of the Input fields.

The key point here is that we are using the props to get the Input Field's id/value and also to call the functions which are set as attributes on the Input Field while we generate the reusable child Input fields.

class InputField extends React.Component{
  handleChange = (event)=> {
    const val = event.target.value;
    this.props.onChange(this.props.id , val);
  }

  render() {
    return(
      <div>
        <input type="text" onChange={this.handleChange} value={this.props.value}/>
        <br/><br/>
      </div>
    );
  }
}       


class FormEditorParent extends React.Component {
  state = {};
  handleFieldChange = (inputFieldId , inputFieldValue) => {
    this.setState({[inputFieldId]:inputFieldValue});
  }
  //on Button click simply get the state of the input field
  handleClick = ()=>{
    console.log(JSON.stringify(this.state));
  }

  render() {
    const fields = this.props.fields.map(field => (
      <InputField
        key={field}
        id={field}
        onChange={this.handleFieldChange}
        value={this.state[field]}
      />
    ));

    return (
      <div>
        <div>
          <button onClick={this.handleClick}>Click Me</button>
        </div>
        <div>
          {fields}
        </div>
      </div>
    );
  }
}

const App = () => {
  const fields = ["field1", "field2", "anotherField"];
  return <FormEditorParent fields={fields} />;
};

ReactDOM.render(<App/>, mountNode);

Detect merged cells in VBA Excel with MergeArea

There are several helpful bits of code for this.

Place your cursor in a merged cell and ask these questions in the Immidiate Window:

Is the activecell a merged cell?

? Activecell.Mergecells
 True

How many cells are merged?

? Activecell.MergeArea.Cells.Count
 2

How many columns are merged?

? Activecell.MergeArea.Columns.Count
 2

How many rows are merged?

? Activecell.MergeArea.Rows.Count
  1

What's the merged range address?

? activecell.MergeArea.Address
  $F$2:$F$3

Combine two tables for one output

In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:

Select  ChargeNum, CategoryId, Sum(Hours)
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

And here is the output:

ChargeNum  CategoryId 
---------- ---------- ----------------------
111111     1          40
111111     2          50
111111     Unknown    70
222222     1          40
222222     Unknown    25.5

Abstract class in Java

An abstract class is one that isn't fully implemented but provides something of a blueprint for subclasses. It may be partially implemented in that it contains fully-defined concrete methods, but it can also hold abstract methods. These are methods with a signature but no method body. Any subclass must define a body for each abstract method, otherwise it too must be declared abstract. Because abstract classes cannot be instantiated, they must be extended by at least one subclass in order to be utilized. Think of the abstract class as the generic class, and the subclasses are there to fill in the missing information.

Class Not Found: Empty Test Suite in IntelliJ

First thing, we need to understand why this is happening and the error message is clear:

Process finished with exit code 1 Class not found: "edu.macalester.comp124.hw0.AreaTest"Empty test suite.

So this mainly occurs when after the unit test class was created we run the methods (tests) individually before running them from the class level. That is all

How do I clear my Jenkins/Hudson build history?

If using the Script Console method then try using the following instead to take into account if jobs are being grouped into folder containers.

def jobName = "Your Job Name"
def job = Jenkins.instance.getItemByFullName(jobName)

or

def jobName = "My Folder/Your Job Name
def job = Jenkins.instance.getItemByFullName(jobName)

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I found this MSDN forum post which suggests two solutions to your problem.

First solution (not recommended):

Find the .Net Framework 3.5 and 2.0 folder

Copy System.Web.Extensions.dll from 3.5 and System.Web.dll from 2.0 to the application folder

Add the reference to these two assemblies

Change the referenced assemblies property, setting "Copy Local" to true And build to test your application to ensure all code can work

Second solution (Use a different class / library):

The user who had posted the question claimed that Uri.EscapeUriString and How to: Serialize and Deserialize JSON Data helped him replicate the behavior of JavaScriptSerializer.

You could also try to use Json.Net. It's a third party library and pretty powerful.

CASE .. WHEN expression in Oracle SQL

Following syntax would work :

....
where x.p_NBR =to_number(substr(y.k_str,11,5))
and x.q_nbr = 
 (case 
 when instr(substr(y.m_str,11,9),'_') = 6   then  to_number(substr(y.m_str,11,5))
 when instr(substr(y.m_str,11,9),'_') = 0   then  to_number(substr(y.m_str,11,9))
  else 
       1
  end
)

Filter by Dates in SQL

WHERE dates BETWEEN (convert(datetime, '2012-12-12',110) AND (convert(datetime, '2012-12-12',110))

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

How to convert between bytes and strings in Python 3?

TRY THIS:

StringVariable=ByteVariable.decode('UTF-8','ignore')

TO TEST TYPE:

print(type(StringVariable))

Here 'StringVariable' represented as a string. 'ByteVariable' represent as Byte. Its not relevent to question Variables..

Pass by pointer & Pass by reference

A reference is semantically the following:

T& <=> *(T * const)

const T& <=> *(T const * const)

T&& <=> [no C equivalent] (C++11)

As with other answers, the following from the C++ FAQ is the one-line answer: references when possible, pointers when needed.

An advantage over pointers is that you need explicit casting in order to pass NULL. It's still possible, though. Of the compilers I've tested, none emit a warning for the following:

int* p() {
    return 0;
}
void x(int& y) {
  y = 1;
}
int main() {
   x(*p());
}

Is there a C++ decompiler?

Depending on how large and how well-written the original code was, it might be worth starting again in your favourite language (which might still be C++) and learning from any mistakes made in the last version. Didn't someone once say about writing one to throw away?

n.b. Clearly if this is a huge product, then it may not be worth the time.

How can I get the assembly file version

Use this:

((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
    Assembly.GetExecutingAssembly(), 
    typeof(AssemblyFileVersionAttribute), false)
).Version;

Or this:

new Version(System.Windows.Forms.Application.ProductVersion);

Java Object Null Check for method

If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]); - to check if the parameter is null. To check if each element is not null just use

if(null != books[i]){/*do stuff*/}

Example:

public static double calculateInventoryTotal(Book[] books){
    Objects.requireNotNull(books, "Books must not be null");

    double total = 0;

    for (int i = 0; i < books.length; i++){
        if(null != book[i]){
            total += books[i].getPrice();
        }
    }

    return total;
}

Difference between 'struct' and 'typedef struct' in C++?

There is no difference in C++, but I believe in C it would allow you to declare instances of the struct Foo without explicitly doing:

struct Foo bar;

Can I change the checkbox size using CSS?

you can chnage the height and width in the code below

_x000D_
_x000D_
.checkmark {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    height: 20px;_x000D_
    width: 20px;_x000D_
    border-radius:5px;_x000D_
    border:1px solid #ff7e02;_x000D_
}
_x000D_
<div class="check">_x000D_
_x000D_
     <label class="container1">Architecture/Landscape_x000D_
            _x000D_
_x000D_
    <input type="checkbox" checked="checked">_x000D_
            _x000D_
_x000D_
    <span class="checkmark"></span>_x000D_
         _x000D_
_x000D_
 </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What's the best way to trim std::string?

Try this, it works for me.

inline std::string trim(std::string& str)
{
    str.erase(0, str.find_first_not_of(' '));       //prefixing spaces
    str.erase(str.find_last_not_of(' ')+1);         //surfixing spaces
    return str;
}

How do you make an element "flash" in jQuery

Would a pulse effect(offline) JQuery plugin be appropriate for what you are looking for ?

You can add a duration for limiting the pulse effect in time.


As mentioned by J-P in the comments, there is now his updated pulse plugin.
See his GitHub repo. And here is a demo.

jQuery to loop through elements with the same class

$('.testimonal').each(function(i,v){
  if (condition) {
    doSomething();
  }
});

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

A static variable shares the value of it among all instances of the class.

Example without declaring it static:

public class Variable
{
    public int i = 5;
    public void test()
    {
        i = i + 5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

Explanation: If you look at the above example, I just declare the int variable. When I run this code the output will be 10 and 10. Its simple.

Now let's look at the static variable here; I am declaring the variable as a static.

Example with static variable:

public class Variable
{
    public static int i = 5;
    public void test()
    {
        i = i + 5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

Now when I run above code, the output will be 10 and 15. So the static variable value is shared among all instances of that class.

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

For Windows users:

Set-ExecutionPolicy RemoteSigned -scope CurrentUser
iex (new-object net.webclient).downloadstring('https://get.scoop.sh')
scoop install gradle

How to retrieve a file from a server via SFTP?

The best solution I've found is Paramiko. There's a Java version.

Setting the default page for ASP.NET (Visual Studio) server configuration

Similar to zproxy's answer above I have used the folowing code in the Gloabal.asax.cs to achieve this:

public class Global : System.Web.HttpApplication
{
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.Url.AbsolutePath.EndsWith("/"))
        {
            Server.Transfer(Request.Url.AbsolutePath + "index.aspx");
        }
    }
}

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Instead of

$("form").submit()

try this

 $("<input type='submit' id='btn_tmpSubmit'/>").css('display','none').appendTo('form');
 $("#btn_tmpSubmit").click();

Best way to unselect a <select> in jQuery?

It's a been a while since asked, and I haven't tested this on older browsers but it seems to me a much simpler answer is

$("#selectID").val([]);

.val() works for select as well http://api.jquery.com/val/

JSON - Iterate through JSONArray

for(int i = 0; i < getArray.size(); i++){
      Object object = getArray.get(i);
      // now do something with the Object
}

You need to check for the type:

The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. [Source]

In your case, the elements will be of type JSONObject, so you need to cast to JSONObject and call JSONObject.names() to retrieve the individual keys.

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

How do I pause my shell script for a second before continuing?

In Python (question was originally tagged Python) you need to import the time module

import time
time.sleep(1)

or

from time import sleep
sleep(1)

For shell script is is just

sleep 1

Which executes the sleep command. eg. /bin/sleep

How can I display a pdf document into a Webview?

If you use the view only url the user is not propted to login to there google account.

https://docs.google.com/viewer?url=http://my.domain.com/yourPdfUrlHere.pdf

What's default HTML/CSS link color?

  • standard link - #0000FF //blue
  • visited link - #800080 //purple
  • active link - #FF0000 //red

that was a standard but heavily differs per browser now. (since Nielsen gave it up ;)

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

In CentOS releases suexec is compiled to run only in /var/www. If you try to set a DocumentRoot somewhere else you have to recompile it - the error in apache log are: (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server Premature end of script headers: php5.fcgi

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Why ModelState.IsValid always return false in mvc

As Brad Wilson states in his answer here:

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

Try using :-

if (!ModelState.IsValid)
{
    var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

    // Breakpoint, Log or examine the list with Exceptions.
}

If it helps catching you the error. Courtesy this and this

How to generate range of numbers from 0 to n in ES2015 only?

Range with step ES6, that works similar to python list(range(start, stop[, step])):

const range = (start, stop, step = 1) => {
  return [...Array(stop - start).keys()]
    .filter(i => !(i % Math.round(step)))
    .map(v => start + v)
}

Examples:

range(0, 8) // [0, 1, 2, 3, 4, 5, 6, 7]
range(4, 9) // [4, 5, 6, 7, 8]
range(4, 9, 2) // [4, 6, 8] 
range(4, 9, 3) // [4, 7]

How do I multiply each element in a list by a number?

You can do it in-place like so:

 l = [1, 2, 3, 4, 5]
 l[:] = [x * 5 for x in l]

This requires no additional imports and is very pythonic.

What is the best way to convert an array to a hash in Ruby

if you have array that looks like this -

data = [["foo",1,2,3,4],["bar",1,2],["foobar",1,"*",3,5,:foo]]

and you want the first elements of each array to become the keys for the hash and the rest of the elements becoming value arrays, then you can do something like this -

data_hash = Hash[data.map { |key| [key.shift, key] }]

#=>{"foo"=>[1, 2, 3, 4], "bar"=>[1, 2], "foobar"=>[1, "*", 3, 5, :foo]}

Difference between "read commited" and "repeatable read"

My observation on initial accepted solution.

Under RR (default mysql) - If a tx is open and a SELECT has been fired, another tx can NOT delete any row belonging to previous READ result set until previous tx is committed (in fact delete statement in the new tx will just hang), however the next tx can delete all rows from the table without any trouble. Btw, a next READ in previous tx will still see the old data until it is committed.

PostgreSQL ERROR: canceling statement due to conflict with recovery

It might be too late for the answer but we face the same kind of issue on the production. Earlier we have only one RDS and as the number of users increases on the app side, we decided to add Read Replica for it. Read replica works properly on the staging but once we moved to the production we start getting the same error.

So we solve this by enabling hot_standby_feedback property in the Postgres properties. We referred the following link

https://aws.amazon.com/blogs/database/best-practices-for-amazon-rds-postgresql-replication/

I hope it will help.

What is the correct format to use for Date/Time in an XML file

If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ")); That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.

Make a bucket public in Amazon S3

Amazon provides a policy generator tool:

https://awspolicygen.s3.amazonaws.com/policygen.html

After that, you can enter the policy requirements for the bucket on the AWS console:

https://console.aws.amazon.com/s3/home

MySQL search and replace some text in a field

In my experience, the fastest method is

UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE field LIKE '%foo%';

The INSTR() way is the second-fastest and omitting the WHERE clause altogether is slowest, even if the column is not indexed.

Conda: Installing / upgrading directly from github

The answers are outdated. You simply have to conda install pip and git. Then you can use pip normally:

  1. Activate your conda environment source activate myenv

  2. conda install git pip

  3. pip install git+git://github.com/scrappy/scrappy@master

Python append() vs. + operator on lists, why do these give different results?

append is appending an element to a list. if you want to extend the list with the new list you need to use extend.

>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

What does .pack() do?

The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.

Can I make a function available in every controller in angular?

Though the first approach is advocated as 'the angular like' approach, I feel this adds overheads.

Consider if I want to use this myservice.foo function in 10 different controllers. I will have to specify this 'myService' dependency and then $scope.callFoo scope property in all ten of them. This is simply a repetition and somehow violates the DRY principle.

Whereas, if I use the $rootScope approach, I specify this global function gobalFoo only once and it will be available in all my future controllers, no matter how many.

find: missing argument to -exec

A -exec command must be terminated with a ; (so you usually need to type \; or ';' to avoid interpretion by the shell) or a +. The difference is that with ;, the command is called once per file, with +, it is called just as few times as possible (usually once, but there is a maximum length for a command line, so it might be split up) with all filenames. See this example:

$ cat /tmp/echoargs
#!/bin/sh
echo $1 - $2 - $3
$ find /tmp/foo -exec /tmp/echoargs {} \;
/tmp/foo - -
/tmp/foo/one - -
/tmp/foo/two - -
$ find /tmp/foo -exec /tmp/echoargs {} +
/tmp/foo - /tmp/foo/one - /tmp/foo/two

Your command has two errors:

First, you use {};, but the ; must be a parameter of its own.

Second, the command ends at the &&. You specified “run find, and if that was successful, remove the file named {};.“. If you want to use shell stuff in the -exec command, you need to explicitly run it in a shell, such as -exec sh -c 'ffmpeg ... && rm'.

However you should not add the {} inside the bash command, it will produce problems when there are special characters. Instead, you can pass additional parameters to the shell after -c command_string (see man sh):

$ ls
$(echo damn.)
$ find * -exec sh -c 'echo "{}"' \;
damn.
$ find * -exec sh -c 'echo "$1"' - {} \;
$(echo damn.)

You see the $ thing is evaluated by the shell in the first example. Imagine there was a file called $(rm -rf /) :-)

(Side note: The - is not needed, but the first variable after the command is assigned to the variable $0, which is a special variable normally containing the name of the program being run and setting that to a parameter is a little unclean, though it won't cause any harm here probably, so we set that to just - and start with $1.)

So your command could be something like

find -exec bash -c 'ffmpeg -i "$1" -sameq "$1".mp3 && rm "$1".mp3' - {} \;

But there is a better way. find supports and and or, so you may do stuff like find -name foo -or -name bar. But that also works with -exec, which evaluates to true if the command exits successfully, and to false if not. See this example:

$ ls
false  true
$ find * -exec {} \; -and -print
true

It only runs the print if the command was successfully, which it did for true but not for false.

So you can use two exec statements chained with an -and, and it will only execute the latter if the former was run successfully.

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

What is Bootstrap?

Bootstrap, as I know it, is a well defined CSS. Although using Bootstrap you could also use JavaScript, jQuery etc. But the main difference is that, using Bootstrap you can just call the class name and then you get the output on the HTML form. for eg. coloring of buttons shaping of text, using layouts. For all this you do not have to write a CSS file rather you just have to use the correct class name for shaping your HTML form.

Google Geocoding API - REQUEST_DENIED

I had this problem and I realized that I was assuming that Geocoding came with the JS maps API. However, it is a separate API which I hadn't enabled in the cloud console. Enabling it fixed it right away.

How do I execute a command and get the output of the command within C++ using POSIX?

The following might be a portable solution. It follows standards.

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <sstream>

std::string ssystem (const char *command) {
    char tmpname [L_tmpnam];
    std::tmpnam ( tmpname );
    std::string scommand = command;
    std::string cmd = scommand + " >> " + tmpname;
    std::system(cmd.c_str());
    std::ifstream file(tmpname, std::ios::in | std::ios::binary );
    std::string result;
    if (file) {
        while (!file.eof()) result.push_back(file.get())
            ;
        file.close();
    }
    remove(tmpname);
    return result;
}

// For Cygwin

int main(int argc, char *argv[])
{
    std::string bash = "FILETWO=/cygdrive/c/*\nfor f in $FILETWO\ndo\necho \"$f\"\ndone ";
    std::string in;
    std::string s = ssystem(bash.c_str());
    std::istringstream iss(s);
    std::string line;
    while (std::getline(iss, line))
    {
        std::cout << "LINE-> " + line + "  length: " << line.length() << std::endl;
    }
    std::cin >> in;
    return 0;
}

How do you stash an untracked file?

I was able to stash just the untracked files by doing:

git stash save "tracked files I'm working on"
git stash save -u "untracked files I'm trying to stash"
git stash pop stash@{1}

The last one pops the stash of the tracked files, thus leaving only the untracked files stashed.

Cannot make a static reference to the non-static method

You can either make your variable non static

public final String TTT =  (String) getText(R.string.TTT);

or make the "getText" method static (if at all possible)

Why use def main()?

if the content of foo.py

print __name__
if __name__ == '__main__':
    print 'XXXX'

A file foo.py can be used in two ways.

  • imported in another file : import foo

In this case __name__ is foo, the code section does not get executed and does not print XXXX.

  • executed directly : python foo.py

When it is executed directly, __name__ is same as __main__ and the code in that section is executed and prints XXXX

One of the use of this functionality to write various kind of unit tests within the same module.

How can I print using JQuery

There is a jquery print area. I've been using it for some time now.

$(".printMe").click(function(){
   $("#outprint").printArea({ mode: 'popup', popClose: true });
});

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

This is not a new answer but will help somebody who's not sure how to set primary key for their table. Use this in a new query and run. This will set UniqueID column as primary key.

USE [YourDatabaseName]
GO

Alter table  [dbo].[YourTableNname]
Add Constraint PK_YourTableName_UniqueID Primary Key Clustered (UniqueID);
GO

Create a copy of a table within the same database DB2

CREATE TABLE NEW_TABLENAME LIKE OLD_TABLENAME;

Works for DB2 V 9.7

Use cell's color as condition in if statement (function)

I don't believe there's any way to get a cell's color from a formula. The closest you can get is the CELL formula, but (at least as of Excel 2003), it doesn't return the cell's color.

It would be pretty easy to implement with VBA:

Public Function myColor(r As Range) As Integer
    myColor = r.Interior.ColorIndex
End Function

Then in the worksheet:

=mycolor(A1)

How to use a SQL SELECT statement with Access VBA

If you wish to use the bound column value, you can simply refer to the combo:

sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo

You can also refer to the column property:

sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"

Dim rs As DAO.Recordset     
Set rs = CurrentDB.OpenRecordset(sSQL)

strText = rs!AText
strText = rs.Fields(1)

In a textbox:

= DlookUp("AText","MyTable","ID=" & MyCombo)

*edited

How to add RSA key to authorized_keys file?

I know I am replying too late but for anyone else who needs this, run following command from your local machine

cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

this has worked perfectly fine. All you need to do is just to replace

[email protected]

with your own user for that particular host

Best way to parse command line arguments in C#?

You may like my one Rug.Cmd

Easy to use and expandable command line argument parser. Handles: Bool, Plus / Minus, String, String List, CSV, Enumeration.

Built in '/?' help mode.

Built in '/??' and '/?D' document generator modes.

static void Main(string[] args) 
{            
    // create the argument parser
    ArgumentParser parser = new ArgumentParser("ArgumentExample", "Example of argument parsing");

    // create the argument for a string
    StringArgument StringArg = new StringArgument("String", "Example string argument", "This argument demonstrates string arguments");

    // add the argument to the parser 
    parser.Add("/", "String", StringArg);

    // parse arguemnts
    parser.Parse(args);

    // did the parser detect a /? argument 
    if (parser.HelpMode == false) 
    {
        // was the string argument defined 
        if (StringArg.Defined == true)
        {
            // write its value
            RC.WriteLine("String argument was defined");
            RC.WriteLine(StringArg.Value);
        }
    }
}

Edit: This is my project and as such this answer should not be seen as an endorsement from a third party. That said I do use it for every command line based program I write, it is open source and it is my hope that others may benefit from it.

How to refresh app upon shaking the device?

I really liked Peterdk's answer. I took it upon myself to make a coulpe of tweaks to his code .

file: ShakeDetector.java

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.FloatMath;

public class ShakeDetector implements SensorEventListener {

    // The gForce that is necessary to register as shake. Must be greater than 1G (one earth gravity unit)
    private static final float SHAKE_THRESHOLD_GRAVITY = 2.7F;
    private static final int SHAKE_SLOP_TIME_MS = 500;
    private static final int SHAKE_COUNT_RESET_TIME_MS = 3000;

    private OnShakeListener mListener;
    private long mShakeTimestamp;
    private int mShakeCount;

    public void setOnShakeListener(OnShakeListener listener) {
        this.mListener = listener;
    }

    public interface OnShakeListener {
        public void onShake(int count);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // ignore
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        if (mListener != null) {
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            float gX = x / SensorManager.GRAVITY_EARTH;
            float gY = y / SensorManager.GRAVITY_EARTH;
            float gZ = z / SensorManager.GRAVITY_EARTH;

            // gForce will be close to 1 when there is no movement.
            float gForce = FloatMath.sqrt(gX * gX + gY * gY + gZ * gZ);

            if (gForce > SHAKE_THRESHOLD_GRAVITY) {
                final long now = System.currentTimeMillis();
                // ignore shake events too close to each other (500ms)
                if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now ) {
                    return;
                }

                // reset the shake count after 3 seconds of no shakes
                if (mShakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now ) {
                    mShakeCount = 0;
                }

                mShakeTimestamp = now;
                mShakeCount++;

                mListener.onShake(mShakeCount);
            }
        }
    }
}

Also, don't forget that you need to register an instance of the ShakeDetector with the SensorManager.

// ShakeDetector initialization
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();
mShakeDetector.setOnShakeListener(new OnShakeListener() {

    @Override
    public void onShake(int count) {
            handleShakeEvent(count); 
        }
    });

mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);

bash, extract string before a colon

Another pure BASH way:

> s='/some/random/file.csv:some string'
> echo "${s%%:*}"
/some/random/file.csv

Returning a value from callback function in Node.js

If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:

Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.

Basically, you can do something like this:

function doCall(urlToCall) {
  return co(function *(){
    var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.                             
    var statusCode = response.statusCode;
    finalData = getResponseJson(statusCode, data.toString());
    return finalData;
  });
}

Then,

var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.

By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.

Sum of values in an array using jQuery

You can use reduce which works in all browser except IE8 and lower.

["20","40","80","400"].reduce(function(a, b) {
    return parseInt(a, 10) + parseInt(b, 10);
})

Are there any standard exit status codes in Linux?

There are no standard exit codes, aside from 0 meaning success. Non-zero doesn't necessarily mean failure either.

stdlib.h does define EXIT_FAILURE as 1 and EXIT_SUCCESS as 0, but that's about it.

The 11 on segfault is interesting, as 11 is the signal number that the kernel uses to kill the process in the event of a segfault. There is likely some mechanism, either in the kernel or in the shell, that translates that into the exit code.

CSS 3 slide-in from left transition

Use CSS3 2D transform to avoid performance issues (mobile)

A common pitfall is to animate left/top/right/bottom properties instead of using to achieve the same effect. For a variety of reasons, the semantics of transforms make them easier to offload, but left/top/right/bottom are much more difficult.

Source: Mozilla Developer Network (MDN)


Demo:

_x000D_
_x000D_
var $slider = document.getElementById('slider');
var $toggle = document.getElementById('toggle');

$toggle.addEventListener('click', function() {
    var isOpen = $slider.classList.contains('slide-in');

    $slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');
});
_x000D_
#slider {
    position: absolute;
    width: 100px;
    height: 100px;
    background: blue;
    transform: translateX(-100%);
    -webkit-transform: translateX(-100%);
}

.slide-in {
    animation: slide-in 0.5s forwards;
    -webkit-animation: slide-in 0.5s forwards;
}

.slide-out {
    animation: slide-out 0.5s forwards;
    -webkit-animation: slide-out 0.5s forwards;
}
    
@keyframes slide-in {
    100% { transform: translateX(0%); }
}

@-webkit-keyframes slide-in {
    100% { -webkit-transform: translateX(0%); }
}
    
@keyframes slide-out {
    0% { transform: translateX(0%); }
    100% { transform: translateX(-100%); }
}

@-webkit-keyframes slide-out {
    0% { -webkit-transform: translateX(0%); }
    100% { -webkit-transform: translateX(-100%); }
}
_x000D_
<div id="slider" class="slide-in">
    <ul>
        <li>Lorem</li>
        <li>Ipsum</li>
        <li>Dolor</li>
    </ul>
</div>

<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
_x000D_
_x000D_

Limit String Length

In another way to limit a string in php and add on readmore text or like '...' using below code

if (strlen(preg_replace('#^https?://#', '', $string)) > 30) { 
    echo substr(preg_replace('#^https?://#', '', $string), 0, 35).'&hellip;'; 
}

How to get document height and width without using jquery

This should work for all browsers/devices:

function getActualWidth()
{
    var actualWidth = window.innerWidth ||
                      document.documentElement.clientWidth ||
                      document.body.clientWidth ||
                      document.body.offsetWidth;

    return actualWidth;
}

batch file to copy files to another location?

Two approaches:

  • When you login: you can to create a copy_my_files.bat file into your All Programs > Startup folder with this content (its a plain text document):

    • xcopy c:\folder\*.* d:\another_folder\.

    Use xcopy c:\folder\*.* d:\another_folder\. /Y to overwrite the file without any prompt.

  • Everytime a folder changes: if you can to use C#, you can to create a program using FileSystemWatcher

How to check if a value exists in an object using JavaScript

Use a for...in loop:

for (let k in obj) {
    if (obj[k] === "test1") {
        return true;
    }
}

Is there any way to wait for AJAX response and halt execution?

New, using jquery's promise implementation:

function functABC(){

  // returns a promise that can be used later. 

  return $.ajax({
    url: 'myPage.php',
    data: {id: id}
  });
}


functABC().then( response => 
  console.log(response);
);

Nice read e.g. here.

This is not "synchronous" really, but I think it achieves what the OP intends.

Old, (jquery's async option has since been deprecated):

All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify

async: false 

like described here

Note, however, that in most cases asynchronous execution (via callback on success) is just fine.

MacOSX homebrew mysql root password

None of these worked for me. I think i already had mysql somewhere on my computer so a password was set there or something. After spending hours trying every solution out there this is what worked for me:

$ brew services stop mysql
$ pkill mysqld
$ rm -rf /usr/local/var/mysql/ # NOTE: this will delete your existing database!!!
$ brew postinstall mysql
$ brew services restart mysql
$ mysql -uroot

all credit to @Ghrua

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

When I used --allow-unrelated-histories, this command generated too many conflicts. There were conflicts in files which I didn't even work on. To get over the error " Refusing to merge unrelated histories", I used following rebase command:

git pull --rebase=preserve --allow-unrelated-histories

After this commit the uncommitted changes with a commit message. Finally, run the following command:

git rebase --continue

After this, my working copy was up-to-date with the remote copy and I was able to push my changes as before. No more unrelated histories error while pulling.

Comparing results with today's date?

Not sure what your asking!

However

SELECT  GETDATE()

Will get you the current date and time

SELECT  DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

Will get you just the date with time set to 00:00:00

How to detect string which contains only spaces?

if(!str.trim()){
  console.log('string is empty or only contains spaces');
}

Removing the whitespace from a string can be done using String#trim().

To check if a string is null or undefined, one can check if the string itself is falsey, in which case it is null, undefined, or an empty string. This first check is necessary, as attempting to invoke methods on null or undefined will result in an error. To check if it contains only spaces, one can check if the string is falsey after trimming, which means that it is an empty string at that point.

if(!str || !str.trim()){
   //str is null, undefined, or contains only spaces
}

This can be simplified using the optional chaining operator.

if(!str?.trim()){
   //str is null, undefined, or contains only spaces
}

If you are certain that the variable will be a string, only the second check is necessary.

if(!str.trim()){
   console.log("str is empty or contains only spaces");
}

How to declare a static const char* in your header file?

If you're using Visual C++, you can non-portably do this using hints to the linker...

// In foo.h...

class Foo
{
public:
   static const char *Bar;
};

// Still in foo.h; doesn't need to be in a .cpp file...

__declspec(selectany)
const char *Foo::Bar = "Blah";

__declspec(selectany) means that even though Foo::Bar will get declared in multiple object files, the linker will only pick up one.

Keep in mind this will only work with the Microsoft toolchain. Don't expect this to be portable.

What's the difference between a method and a function?

Function or a method is a named callable piece of code which performs some operations and optionally returns a value.

In C language the term function is used. Java & C# people would say it a method (and a function in this case is defined within a class/object).

A C++ programmer might call it a function or sometimes method (depending on if they are writing procedural style c++ code or are doing object oriented way of C++, also a C/C++ only programmer would likely call it a function because term 'method' is less often used in C/C++ literature).

You use a function by just calling it's name like,

result = mySum(num1, num2);


You would call a method by referencing its object first like,

result = MyCalc.mySum(num1,num2);

SQL Server - NOT IN

You're probably better off comparing the fields individually, rather than concatenating the strings.

SELECT t1.*
    FROM Table1 t1
        LEFT JOIN Table2 t2
            ON t1.MAKE = t2.MAKE
                AND t1.MODEL = t2.MODEL
                AND t1.[serial number] = t2.[serial number]
    WHERE t2.MAKE IS NULL

Ruby: Can I write multi-line string with no concatenation?

conn.exec = <<eos
  select attr1, attr2, attr3, attr4, attr5, attr6, attr7
  from table1, table2, table3, etc, etc, etc, etc, etc,
  where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos

Skip over a value in the range function in python

It depends on what you want to do. For example you could stick in some conditionals like this in your comprehensions:

# get the squares of each number from 1 to 9, excluding 2
myList = [i**2 for i in range(10) if i != 2]
print(myList)

# --> [0, 1, 9, 16, 25, 36, 49, 64, 81]

Get a specific bit from byte

Easy. Use a bitwise AND to compare your number with the value 2^bitNumber, which can be cheaply calculated by bit-shifting.

//your black magic
var bit = (b & (1 << bitNumber-1)) != 0;

EDIT: To add a little more detail because there are a lot of similar answers with no explanation:

A bitwise AND compares each number, bit-by-bit, using an AND join to produce a number that is the combination of bits where both the first bit and second bit in that place were set. Here's the logic matrix of AND logic in a "nibble" that shows the operation of a bitwise AND:

  0101
& 0011
  ----
  0001 //Only the last bit is set, because only the last bit of both summands were set

In your case, we compare the number you passed with a number that has only the bit you want to look for set. Let's say you're looking for the fourth bit:

  11010010
& 00001000
  --------
  00000000 //== 0, so the bit is not set

  11011010
& 00001000
  --------
  00001000 //!= 0, so the bit is set

Bit-shifting, to produce the number we want to compare against, is exactly what it sounds like: take the number, represented as a set of bits, and shift those bits left or right by a certain number of places. Because these are binary numbers and so each bit is one greater power-of-two than the one to its right, bit-shifting to the left is equivalent to doubling the number once for each place that is shifted, equivalent to multiplying the number by 2^x. In your example, looking for the fourth bit, we perform:

       1 (2^0) << (4-1) ==        8 (2^3)
00000001       << (4-1) == 00001000

Now you know how it's done, what's going on at the low level, and why it works.

Deserialize JSON with C#

You can use this extensions

public static class JsonExtensions
{
   public static T ToObject<T>(this string jsonText)
   {
       return JsonConvert.DeserializeObject<T>(jsonText);
   }

   public static string ToJson<T>(this T obj)
   {
       return JsonConvert.SerializeObject(obj);
   }
}

What is the best (idiomatic) way to check the type of a Python variable?

I think it might be preferred to actually do

if isinstance(x, str):
    do_something_with_a_string(x)
elif isinstance(x, dict):
    do_somethting_with_a_dict(x)
else:
    raise ValueError

2 Alternate forms, depending on your code one or the other is probably considered better than that even. One is to not look before you leap

try:
  one, two = tupleOrValue
except TypeError:
  one = tupleOrValue
  two = None

The other approach is from Guido and is a form of function overloading which leaves your code more open ended.

http://www.artima.com/weblogs/viewpost.jsp?thread=155514

Split string with PowerShell and do something with each token

Another way to accomplish this is a combination of Justus Thane's and mklement0's answers. It doesn't make sense to do it this way when you look at a one liner example, but when you're trying to mass-edit a file or a bunch of filenames it comes in pretty handy:

$test = '   One      for the money   '
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$($test.split(' ',$option)).foreach{$_}

This will come out as:

One
for
the
money

Method List in Visual Studio Code

For PHP users :)

  1. Make sure you have 'PHP Symbol' plugin then you can get all methods and class in 'OUTLINE' Sidebar's Bottom.

  2. Press ? command + ? shift + O in "macOS" or Ctrl + Shift + O while using "Windows"

OUTLINE: enter image description here

@Symbol: enter image description here

dyld: Library not loaded ... Reason: Image not found

You can use the otool command with the -L option for the executable, which will display where the executable is expecting those libraries to be.

If the path to those need changing, use the install_name_tool command, which allows you to set the path to the libraries.

PHP, Get tomorrows date from date

here's working function

function plus_one_day($date){
 $date2 = formatDate4db($date);
 $date1 = str_replace('-', '/', $date2);
 $tomorrow = date('Y-m-d',strtotime($date1 . "+1 days"));
 return $tomorrow; }

Alter Table Add Column Syntax

The correct syntax for adding column into table is:

ALTER TABLE table_name
  ADD column_name column-definition;

In your case it will be:

ALTER TABLE Employees
  ADD EmployeeID int NOT NULL IDENTITY (1, 1)

To add multiple columns use brackets:

ALTER TABLE table_name
  ADD (column_1 column-definition,
       column_2 column-definition,
       ...
       column_n column_definition);

COLUMN keyword in SQL SERVER is used only for altering:

ALTER TABLE table_name
  ALTER COLUMN column_name column_type;

Getting indices of True values in a boolean list

If you have numpy available:

>>> import numpy as np
>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> np.where(states)[0]
array([4, 5, 7])

setting content between div tags using javascript

If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.

The innerHtml property did not work for me. So I experimented with ...

    <div id=successAndErrorMessages-1>100% OK</div>
    <div id=successAndErrorMessages-2>This is an error mssg!</div>

and toggled one of the two on/off ...

 $("#successAndErrorMessages-1").css('display', 'none')
 $("#successAndErrorMessages-2").css('display', '')

For some reason I had to fiddle around with the ordering before it worked in all types of browsers.

Making TextView scrollable on Android

All that is really necessary is the setMovementMethod(). Here's an example using a LinearLayout.

File main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:id="@+id/tv1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/hello"
    />
</LinearLayout>

File WordExtractTest.java

public class WordExtractTest extends Activity {

    TextView tv1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv1 = (TextView)findViewById(R.id.tv1);

        loadDoc();
    }

    private void loadDoc() {

        String s = "";

        for(int x=0; x<=100; x++) {
            s += "Line: " + String.valueOf(x) + "\n";
        }

        tv1.setMovementMethod(new ScrollingMovementMethod());

        tv1.setText(s);
    }
}

How to deserialize JS date using Jackson?

In addition to Varun Achar's answer, this is the Java 8 variant I came up with, that uses java.time.LocalDate and ZonedDateTime instead of the old java.util.Date classes.

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

    @Override
    public LocalDate deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException {

        String string = jsonparser.getText();

        if(string.length() > 20) {
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(string);
            return zonedDateTime.toLocalDate();
        }

        return LocalDate.parse(string);
    }
  }

Find all tables containing column with specified name - MS SQL Server

Like oracle you can find tables and columns with this:

select table_name, column_name
from user_tab_columns 
where column_name 
like '%myname%';

Extract value of attribute node via XPath

for all xml with namespace use local-name()

//*[local-name()='Parent'][@id='1']/*[local-name()='Children']/*[local-name()='child']/@name 

How do you use colspan and rowspan in HTML tables?

If anyone is looking for a rowspan on both the left AND on the right, here is how you can do it:

_x000D_
_x000D_
table { _x000D_
    border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
    padding: 20px; _x000D_
    border: 1px solid black; _x000D_
    text-align: center;_x000D_
}
_x000D_
<table>_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td rowspan="2">LEFT</td>_x000D_
        <td> 1 </td>_x000D_
        <td> 2 </td>_x000D_
        <td> 3 </td>_x000D_
        <td> 4 </td>_x000D_
        <td rowspan="2">RIGHT</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 5 </td>_x000D_
        <td> 6 </td>_x000D_
        <td> 7 </td>_x000D_
        <td> 8 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
    </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Alternatively, if you want to add the LEFT and RIGHT to an existing rowset, you can achieve the same result by throwing them in with a collapsed colspan in between:

_x000D_
_x000D_
table {_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
    padding: 20px; _x000D_
    border: 1px solid black; _x000D_
    text-align: center;_x000D_
}
_x000D_
<table>_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td rowspan="3">LEFT</td>_x000D_
        <td colspan="4" style="padding: 0; border-bottom: solid 1px transparent;"></td>_x000D_
        <td rowspan="3">RIGHT</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 1 </td>_x000D_
        <td> 2 </td>_x000D_
        <td> 3 </td>_x000D_
        <td> 4 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 5 </td>_x000D_
        <td> 6 </td>_x000D_
        <td> 7 </td>_x000D_
        <td> 8 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
    </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

First char to upper case

Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.

What replaceFirst() does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.

What you want to do is convert the string to an array using the String class' charAt() method, and then use Character.toUpperCase() to change the character to upper case (obviously). Your code would look like this:

char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);

Or, if you feel comfortable with more complex, one-lined java code:

betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);

Both of these do the same thing, which is converting the first character of userIdea to an upper case character.

Keyboard shortcut to comment lines in Sublime Text 3

In Windows use ctrl + shift + : to comment for Python.

Difference between web server, web container and application server

The main difference between the web containers and application server is that most web containers such as Apache Tomcat implements only basic JSR like Servlet, JSP, JSTL wheres Application servers implements the entire Java EE Specification. Every application server contains web container.

Ruby convert Object to Hash

class Gift
  def initialize
    @name = "book"
    @price = 15.95
  end
end

gift = Gift.new
hash = {}
gift.instance_variables.each {|var| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
p hash # => {"name"=>"book", "price"=>15.95}

Alternatively with each_with_object:

gift = Gift.new
hash = gift.instance_variables.each_with_object({}) { |var, hash| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
p hash # => {"name"=>"book", "price"=>15.95}

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

The following method is about 30 times faster than scipy.spatial.distance.pdist. It works pretty quickly on large matrices (assuming you have enough RAM)

See below for a discussion of how to optimize for sparsity.

# base similarity matrix (all dot products)
# replace this with A.dot(A.T).toarray() for sparse representation
similarity = numpy.dot(A, A.T)


# squared magnitude of preference vectors (number of occurrences)
square_mag = numpy.diag(similarity)

# inverse squared magnitude
inv_square_mag = 1 / square_mag

# if it doesn't occur, set it's inverse magnitude to zero (instead of inf)
inv_square_mag[numpy.isinf(inv_square_mag)] = 0

# inverse of the magnitude
inv_mag = numpy.sqrt(inv_square_mag)

# cosine similarity (elementwise multiply by inverse magnitudes)
cosine = similarity * inv_mag
cosine = cosine.T * inv_mag

If your problem is typical for large scale binary preference problems, you have a lot more entries in one dimension than the other. Also, the short dimension is the one whose entries you want to calculate similarities between. Let's call this dimension the 'item' dimension.

If this is the case, list your 'items' in rows and create A using scipy.sparse. Then replace the first line as indicated.

If your problem is atypical you'll need more modifications. Those should be pretty straightforward replacements of basic numpy operations with their scipy.sparse equivalents.