Programs & Examples On #Aot

In Microsoft Dynamics AX, application objects are defined in the Application Object Tree (AOT) and are instantiated at runtime. The AOT also contains application resources, references, and documentation. This section describes the AOT and its contents, how to use the AOT to define application objects, and how to import and export definitions of application objects.

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

I have faced the same issue in Ubuntu because the Angular app directory was having root permission. Changing the ownership to the local user solved the issue for me.

$ sudo -i
$ chown -R <username>:<group> <ANGULAR_APP>
$ exit 
$ cd <ANGULAR_APP>
$ ng serve

error: This is probably not a problem with npm. There is likely additional logging output above

I'm on Ubuntu 18.04. I fixed this problem by increasing the inotify max_user_watches using this command:

echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches

Can not find module “@angular-devkit/build-angular”

I've just encountered this problem and fixed it. I think the root cause of this problem is ng and current version of node.js (10.6.0) and accompanying npm are not in sync. I've installed the LTS version of node.js (8.11.3) and the problem disappeared.

Could not find module "@angular-devkit/build-angular"

Following commands works:

npm install
ng update

-You may see the message "We analyzed your package.json and everything seems to be in order. Good work!"

npm update

Then try dev build

ng build 

I got the error with type script, downgraded to

npm install typescript@">=3.1.1 <3.2

ng build --prod 

All success with prod build.

Below is the working combination

ng --version

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.11.0
@angular-devkit/build-angular     0.11.0
@angular-devkit/build-optimizer   0.11.0
@angular-devkit/build-webpack     0.11.0
@angular-devkit/core              7.1.0
@angular-devkit/schematics        7.1.0
@angular/cli                      7.1.0
@ngtools/webpack                  7.1.0
@schematics/angular               7.1.0
@schematics/update                0.11.0
rxjs                              6.3.3
typescript                        3.1.6
webpack                           4.23.1

No provider for HttpClient

In my case, the error occured when using a service from an angular module located in an npm package, where the service requires injection of HttpClient. When installing the npm package, a duplicate node_modules directory was created inside the package directory due to version conflict handling of npm (engi-sdk-client is the module containing the service):

enter image description here

Obviously, the dependency to HttpClient is not resolved correctly, as the locations of HttpClientModule injected into the service (lives in the duplicate node_modules directory) and the one injected in app.module (the correct node_modules) don't match.

I've also had this error in other setups containing a duplicate node_modules directory due to a wrong npm install call.

This defective setup also leads to the described runtime exception No provider for HttpClient!.

TL;DR; Check for duplicate node_modules directories, if none of the other solutions work!

How to decrease prod bundle size?

Update February 2020

Since this answer got a lot of traction, I thought it would be best to update it with newer Angular optimizations:

  1. As another answerer said, ng build --prod --build-optimizer is a good option for people using less than Angular v5. For newer versions, this is done by default with ng build --prod
  2. Another option is to use module chunking/lazy loading to better split your application into smaller chunks
  3. Ivy rendering engine comes by default in Angular 9, it offers better bundle sizes
  4. Make sure your 3rd party deps are tree shakeable. If you're not using Rxjs v6 yet, you should be.
  5. If all else fails, use a tool like webpack-bundle-analyzer to see what is causing bloat in your modules
  6. Check if you files are gzipped

Some claims that using AOT compilation can reduce the vendor bundle size to 250kb. However, in BlackHoleGalaxy's example, he uses AOT compilation and is still left with a vendor bundle size of 2.75MB with ng build --prod --aot, 10x larger than the supposed 250kb. This is not out of the norm for angular2 applications, even if you are using v4.0. 2.75MB is still too large for anyone who really cares about performance, especially on a mobile device.

There are a few things you can do to help the performance of your application:

1) AOT & Tree Shaking (angular-cli does this out of the box). With Angular 9 AOT is by default on prod and dev environment.

2) Using Angular Universal A.K.A. server-side rendering (not in cli)

3) Web Workers (again, not in cli, but a very requested feature)
see: https://github.com/angular/angular-cli/issues/2305

4) Service Workers
see: https://github.com/angular/angular-cli/issues/4006

You may not need all of these in a single application, but these are some of the options that are currently present for optimizing Angular performance. I believe/hope Google is aware of the out of the box shortcomings in terms of performance and plans to improve this in the future.

Here is a reference that talks more in depth about some of the concepts i mentioned above:

https://medium.com/@areai51/the-4-stages-of-perf-tuning-for-your-angular2-app-922ce5c1b294

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I solved this issue by removing all the NuGet packages from solution and reinstalling them. One of the NuGet Packages was dependent upon NewtonSoft and it was not showing in references

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

Include an SVG (hosted on GitHub) in MarkDown

This will work. Link to your SVG using the following pattern:

https://cdn.rawgit.com/<repo-owner>/<repo>/<branch>/path/to.svg

The downside is hardcoding the owner and repo in the path, meaning the svg will break if either of those are renamed.

Annotation @Transactional. How to rollback?

You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.

I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.

The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.

and note that:

please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

The following code can cause similar error:

  using (var session = SessionFactory.OpenSession())
  using (var tx = session.BeginTransaction())
  {
      movie = session.Get<Movie>(movieId);
      tx.Commit();
  }
  Assert.That(movie.Actors.Count == 1);

You can fix it simply:

  using (var session = SessionFactory.OpenSession())
  using (var tx = session.BeginTransaction())
  {
      movie = session.Get<Movie>(movieId);
      Assert.That(movie.Actors.Count == 1);
      tx.Commit();
  }

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

Eclipse - java.lang.ClassNotFoundException

I've run into a same error in Eclipse recently, i.e., the Eclipse IDE couldn't find the Unit test class no matter how I change the configurations. Learning from the previous posts here and in other web sites, I've double checked and triple checked the classpath and source info, and move up and down the source folder and libraries, in both the "Run Configuration" and the "Java Build Path" config windows, and I've also cleaned the Project and rebuilt it, but none of the tricks work for me. The specific Java project is an old ANT compiled project and have lots of jars included in Eclipse library.

Then, I changed the unit test class to add a main() method and right click it to "Run As" a Java Application instead of JUnit test, and suddenly, Eclipse seems to wake up and identified the class correctly. Afterwards, I switched it back to a Unit test application, and it is still working.

This seems to be a bug in Eclipse, I am guessing the large number of libraries (>260) may confused the JVM's ability to locate my JUnit class.

Cause of No suitable driver found for

In some cases check permissions (ownership).

How do I get the path of the assembly the code is in?

string path = Path.GetDirectoryName(typeof(DaoTests).Module.FullyQualifiedName);

HTML5 Canvas 100% Width Height of Viewport?

http://jsfiddle.net/mqFdk/10/

<!DOCTYPE html>
<html>
<head>
    <title>aj</title>
</head>
<body>

    <canvas id="c"></canvas>

</body>
</html>

with CSS

body { 
       margin: 0; 
       padding: 0
     }
#c { 
     position: absolute; 
     width: 100%; 
     height: 100%; 
     overflow: hidden
   }

How to avoid the "Circular view path" exception with Spring MVC test

For Thymeleaf:

I just began using spring 4 and thymeleaf, when I encountered this error it was resolved by adding:

<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
  <property name="templateEngine" ref="templateEngine" />
  <property name="order" value="0" />
</bean> 

How to get cookie's expire time

To get cookies expire time, use this simple method.

<?php

//#############PART 1#############
//expiration time (a*b*c*d) <- change D corresponding to number of days for cookie expiration
$time = time()+(60*60*24*365);
$timeMemo = (string)$time;

//sets cookie with expiration time defined above
setcookie("testCookie", "" . $timeMemo . "", $time);

//#############PART 2#############
//this function will convert seconds to days.
function secToDays($sec){

    return ($sec / 60 / 60 / 24);

}
//checks if cookie is set and prints out expiration time in days
if(isset($_COOKIE['testCookie'])){

    echo "Cookie is set<br />";
    if(round(secToDays((intval($_COOKIE['testCookie']) - time())),1) < 1){
        echo "Cookie will expire today.";
    }else{
        echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['testCookie']) - time())),1) . " day(s)";
    }

}else{
    echo "not set...";
}

?>

You need to keep Part 1 and Part 2 in different files, otherwise you will get the same expire date everytime.

How to set time to midnight for current day?

Try this:

DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
   .AddSeconds(-DateTime.Now.Second);

Output will be like:

07/29/2015 00:00:00

JavaScript: Object Rename Key

You could wrap the work in a function and assign it to the Object prototype. Maybe use the fluent interface style to make multiple renames flow.

Object.prototype.renameProperty = function (oldName, newName) {
     // Do nothing if the names are the same
     if (oldName === newName) {
         return this;
     }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (this.hasOwnProperty(oldName)) {
        this[newName] = this[oldName];
        delete this[oldName];
    }
    return this;
};

ECMAScript 5 Specific

I wish the syntax wasn't this complex but it is definitely nice having more control.

Object.defineProperty(
    Object.prototype, 
    'renameProperty',
    {
        writable : false, // Cannot alter this property
        enumerable : false, // Will not show up in a for-in loop.
        configurable : false, // Cannot be deleted via the delete operator
        value : function (oldName, newName) {
            // Do nothing if the names are the same
            if (oldName === newName) {
                return this;
            }
            // Check for the old property name to 
            // avoid a ReferenceError in strict mode.
            if (this.hasOwnProperty(oldName)) {
                this[newName] = this[oldName];
                delete this[oldName];
            }
            return this;
        }
    }
);

Python functions call by reference

There are essentially three kinds of 'function calls':

  • Pass by value
  • Pass by reference
  • Pass by object reference

Python is a PASS-BY-OBJECT-REFERENCE programming language.

Firstly, it is important to understand that a variable, and the value of the variable (the object) are two seperate things. The variable 'points to' the object. The variable is not the object. Again:

THE VARIABLE IS NOT THE OBJECT

Example: in the following line of code:

>>> x = []

[] is the empty list, x is a variable that points to the empty list, but x itself is not the empty list.

Consider the variable (x, in the above case) as a box, and 'the value' of the variable ([]) as the object inside the box.

PASS BY OBJECT REFERENCE (Case in python):

Here, "Object references are passed by value."

def append_one(li):
    li.append(1)
x = [0]
append_one(x)
print x

Here, the statement x = [0] makes a variable x (box) that points towards the object [0].

On the function being called, a new box li is created. The contents of li are the SAME as the contents of the box x. Both the boxes contain the same object. That is, both the variables point to the same object in memory. Hence, any change to the object pointed at by li will also be reflected by the object pointed at by x.

In conclusion, the output of the above program will be:

[0, 1]

Note:

If the variable li is reassigned in the function, then li will point to a separate object in memory. x however, will continue pointing to the same object in memory it was pointing to earlier.

Example:

def append_one(li):
    li = [0, 1]
x = [0]
append_one(x)
print x

The output of the program will be:

[0]

PASS BY REFERENCE:

The box from the calling function is passed on to the called function. Implicitly, the contents of the box (the value of the variable) is passed on to the called function. Hence, any change to the contents of the box in the called function will be reflected in the calling function.

PASS BY VALUE:

A new box is created in the called function, and copies of contents of the box from the calling function is stored into the new boxes.

Hope this helps.

An Iframe I need to refresh every 30 seconds (but not the whole page)

I have a simpler solution. In your destination page (irc_online.php) add an auto-refresh tag in the header.

What is 'Context' on Android?

Just putting it out there for newbies;

So First understand Word Context :

In english-lib. it means:

"The circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood and assessed."

"The parts of something written or spoken that immediately precede and follow a word or passage and clarify its meaning."

Now take the same understanding to programming world:

context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).

To Get Context Anywhere in application use following code:

Create new class AppContext inside your android application

public class AppContext extends Application {

    private static Context context;

    public void onCreate(){
        super.onCreate();
        AppContext.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return AppContext.context;
    }
}

Now any time you want application context in non-activity class, call this method and you have application context.

Hope this help ;)

Angular js init ng-model from default values

I have a simple approach, because i have some heavy validations and masks in my forms. So, i used jquery to get my value again and fire the event "change" to validations:

$('#myidelement').val('123');
$('#myidelement').trigger( "change");

How do you change library location in R?

This post is just to mention an additional option. In case you need to set custom R libs in your Linux shell script you may easily do so by

export R_LIBS="~/R/lib"

See R admin guide on complete list of options.

contenteditable change events

A simple answer in JQuery, I just created this code and thought it will be helpful for others too

    var cont;

    $("div [contenteditable=true]").focus(function() {
        cont=$(this).html();
    });

    $("div [contenteditable=true]").blur(function() {
        if ($(this).html()!=cont) {
           //Here you can write the code to run when the content change
        }           
    });

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Resize to fit image in div, and center horizontally and vertically

SOLUTION

<style>
.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
    background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;

}

</style>

<div class='container'>
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>

Storage permission error in Marshmallow

In a simple way the permission can be granted using manifest.xml file, but it was ok till the api level 23 sdk version 6, after from here, if we want to get the permission we have to ask for the use to allow the permission which are needed.

Just add this code in the mainActivity.java

Override
            public void onClick(View view) {
                // Request the permission
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.CAMERA},
                        PERMISSION_REQUEST_CAMERA);

Replace CAMERA or add with WRITE_EXTERNAL_STORAGE if you want, and with the unique code.

                            new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    101);

This is the simple code to get permission.

Can iterators be reset in Python?

One possible option is to use itertools.cycle(), which will allow you to iterate indefinitely without any trick like .seek(0).

iterDic = itertools.cycle(csv.DictReader(open('file.csv')))

Class 'ViewController' has no initializers in swift

This issue usually appears when one of your variables has no value or when you forget to add "!" to force this variable to store nil until it is set.

In your case the problem is here:

var delegate: AppDelegate

It should be defined as var delegate: AppDelegate! to make it an optional that stores nil and do not unwrap the variable until the value is used.

It is sad that Xcode highlights the whole class as an error instead of highlighting the particular line of code that caused it, so it takes a while to figure it out.

Convert MySql DateTime stamp into JavaScript's Date format

You can use unix timestamp to direct:

SELECT UNIX_TIMESTAMP(date) AS epoch_time FROM table;

Then get the epoch_time into JavaScript, and it's a simple matter of:

var myDate = new Date(epoch_time * 1000);

The multiplying by 1000 is because JavaScript takes milliseconds, and UNIX_TIMESTAMP gives seconds.

WAMP 403 Forbidden message on Windows 7

Make sure you aren't using a Windows' directory separator character (backslash) in your path names in your .conf file, even if you are on Windows. Apache doesn't understand them but will still start up and then output a 403 Forbidden Message.

wrong:

<Directory "c:\websites\my-website\">

right:

<Directory "c:/websites/my-website/">

Programmatically obtain the phone number of the Android phone

Just want to add a bit here to above explanations in the above answers. Which will save time for others as well.

In my case this method didn't returned any mobile number, an empty string was returned. It was due to the case that I had ported my number on the new sim. So if I go into the Settings>About Phone>Status>My Phone Number it shows me "Unknown".

how to put focus on TextBox when the form load?

You can use either textBox1.select(); or the TabIndex in textbox setting. TabIndex=0 focoused first.

"for loop" with two variables?

I think you are looking for nested loops.

Example (based on your edit):

t1=[1,2,'Hello',(1,2),999,1.23]
t2=[1,'Hello',(1,2),999]

t3=[]

for it1, e1 in enumerate(t1):
    for it2, e2 in enumerate(t2):
        if e1==e2:
            t3.append((it1,it2,e1))

# t3=[(0, 0, 1), (2, 1, 'Hello'), (3, 2, (1, 2)), (4, 3, 999)]

Which can be reduced to a single comprehension:

[(it1,it2,e1) for it1, e1 in enumerate(t1) for it2, e2 in enumerate(t2) if e1==e2] 

But to find the common elements, you can just do:

print set(t1) & set(t2)
# set([(1, 2), 1, 'Hello', 999])

If your list contains non-hashable objects (like other lists, dicts) use a frozen set:

from collections import Iterable
s1=set(frozenset(e1) if isinstance(e1,Iterable) else e1 for e1 in t1)
s2=set(frozenset(e2) if isinstance(e2,Iterable) else e2 for e2 in t2)
print s1 & s2

align an image and some text on the same line without using div width?

I built on the last answer and used display:table for an outer div, and display:table-cell for inner divs.

This was the only thing that worked for me using CSS.

Running windows shell commands with python

The newer subprocess.check_output and similar commands are supposed to replace os.system. See this page for details. While I can't test this on Windows (because I don't have access to any Windows machines), the following should work:

from subprocess import check_output
check_output("dir C:", shell=True)

check_output returns a string of the output from your command. Alternatively, subprocess.call just runs the command and returns the status of the command (usually 0 if everything is okay).

Also note that, in python 3, that string output is now bytes output. If you want to change this into a string, you need something like

from subprocess import check_output
check_output("dir C:", shell=True).decode()

If necessary, you can tell it the kind of encoding your program outputs. The default is utf-8, which typically works fine, but other standard options are here.

Also note that @bluescorpion says in the comments that Windows 10 needs a trailing backslash, as in check_output("dir C:\\", shell=True). The double backslash is needed because \ is a special character in python, so it has to be escaped. (Also note that even prefixing the string with r doesn't help if \ is the very last character of the string — r"dir C:\" is a syntax error, though r"dir C:\ " is not.)

How to add 30 minutes to a JavaScript Date object?

You could do this:

_x000D_
_x000D_
let thirtyMinutes = 30 * 60 * 1000; // convert 30 minutes to milliseconds_x000D_
let date1 = new Date();_x000D_
let date2 = new Date(date1.getTime() + thirtyMinutes);_x000D_
console.log(date1);_x000D_
console.log(date2);
_x000D_
_x000D_
_x000D_

What is the purpose of flush() in Java streams?

In addition to other good answers here, this explanation made things crystal clear for me:

A buffer is a portion in memory that is used to store a stream of data (characters). These characters sometimes will only get sent to an output device (e.g. monitor) when the buffer is full or meets a certain number of characters. This can cause your system to lag if you just have a few characters to send to an output device. The flush() method will immediately flush the contents of the buffer to the output stream.

Source: https://www.youtube.com/watch?v=MjK3dZTc0Lg

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

this seems to do the trick:

function goBackOrGoToUrl() {    

    window.history.back();
    window.location = "http://example.com";

}

Call history.back() and then change the location. If the browser is able to go back in history it won't be able to get to the next statement. If it's not able to go back, it'll go to the location specified.

How to toggle a boolean?

Let's see this in action:

_x000D_
_x000D_
var b = true;_x000D_
_x000D_
console.log(b); // true_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // false_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // true
_x000D_
_x000D_
_x000D_

Anyways, there is no shorter way than what you currently have.

How can I get the count of line in a file in an efficient way?

Files.lines

Java 8+ has a nice and short way using NIO using Files.lines. Note that you have to close the stream using try-with-resources:

long lineCount;
try (Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8)) {
  lineCount = stream.count();
}

If you don't specify the character encoding, the default one used is UTF-8. You may specify an alternate encoding to match your particular data file as shown in the example above.

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

Storing Images in DB - Yea or Nay?

I have worked with many digital storage systems and they all store digital objects on the file system. They tend to use a branch approach, so there will be an archive tree on the file system, often starting with year of entry e.g. 2009, subdirectory will be month e.g. 8 for August, next directory will be day e.g. 11 and sometimes they will use hour as well, the file will then be named with the records persistent ID. Using BLOBS has its advantages and I have heard of it being used often in the IT parts of the chemical industry for storing thousands or millions of photographs and diagrams. It can provide more granular security, a single method of backup, potentially better data integrity and improved inter media searching, Oracle has many features for this within the package they used to call Intermedia (I think it is called something else now). The file system can also have granular security provided through a system such as XACML or another XML type security object. See D Space of Fedora Object Store for examples.

log4j configuration via JVM argument(s)?

The solution is using of the following JVM argument:

-Dlog4j.configuration={path to file}

If the file is NOT in the classpath (in WEB-INF/classes in case of Tomcat) but somewhere on you disk, use file:, like

-Dlog4j.configuration=file:C:\Users\me\log4j.xml

More information and examples here: http://logging.apache.org/log4j/1.2/manual.html

Creating your own header file in C

#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

int foo(char*);

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}

How to change or add theme to Android Studio?

  • Go to File > Settings,
  • now under IDE settings click on appearance and select the theme of your choice from the dropdown.
  • you can also install themes, they are the jar files by
  • File > Import Settings, select the file or your choice and select ok a pop up to restart the studio will open up click yes and studio will restart and your theme will be applied.

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

  1. Where I work we have 2 Sprints to an Iteration. The Iteration demo is before the business stakeholders that don't want to meet after every Sprint, but that is our interpretation of the terminology. Some places may have the terms having equally meaning, I'm just pointing out that where I work they aren't the same thing.

  2. No, sprints can have varying lengths. Where I work we had a half a Sprint to align our Sprints with the Iterations that others in the project from another department were using.

How to make an autocomplete TextBox in ASP.NET?

Try this: .aspx page

<td>  
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>  
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"  
   CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"  
   ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">  
      </asp:AutoCompleteExtender>  

Now To auto populate from database :

public static List<string> GetCompletionList(string prefixText, int count)  
    {  
        return AutoFillProducts(prefixText);  

    }  

    private static List<string> AutoFillProducts(string prefixText)  
    {  
        using (SqlConnection con = new SqlConnection())  
        {  
            con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;  
            using (SqlCommand com = new SqlCommand())  
            {  
                com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like @Search + '%'";  
                com.Parameters.AddWithValue("@Search", prefixText);  
                com.Connection = con;  
                con.Open();  
                List<string> countryNames = new List<string>();  
                using (SqlDataReader sdr = com.ExecuteReader())  
                {  
                    while (sdr.Read())  
                    {  
                        countryNames.Add(sdr["ProductName"].ToString());  
                    }  
                }  
                con.Close();  
                return countryNames;  
            }  
        }  
    }  

Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.

Create Procedure GetProductDet  
(  
@ProductName varchar(50)    
)  
as  
begin  
Select BrandName,warranty,Price from ProdcutMaster where ProductName=@ProductName  
End   

Create a function name to get product details ::

private void GetProductMasterDet(string ProductName)  
    {  
        connection();  
        com = new SqlCommand("GetProductDet", con);  
        com.CommandType = CommandType.StoredProcedure;  
        com.Parameters.AddWithValue("@ProductName", ProductName);  
        SqlDataAdapter da = new SqlDataAdapter(com);  
        DataSet ds=new DataSet();  
        da.Fill(ds);  
        DataTable dt = ds.Tables[0];  
        con.Close();  
        //Binding TextBox From dataTable  
        txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();  
        txtwarranty.Text = dt.Rows[0]["warranty"].ToString();  
        txtPrice.Text = dt.Rows[0]["Price"].ToString();   
    }

Auto post back should be true

<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

Now, Just call this function

protected void TextBox1_TextChanged(object sender, EventArgs e)  
  {  
      //calling method and Passing Values  
      GetProductMasterDet(TextBox1.Text);  
  } 

How do I install package.json dependencies in the current directory using npm

Running:

npm install

from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).

You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.

To prevent this, just create a symlink to the relocated node_modules from your app dir:

ln -s ../node_modules node_modules

What is the difference between cache and persist?

There is no difference. From RDD.scala.

/** Persist this RDD with the default storage level (`MEMORY_ONLY`). */
def persist(): this.type = persist(StorageLevel.MEMORY_ONLY)

/** Persist this RDD with the default storage level (`MEMORY_ONLY`). */
def cache(): this.type = persist()

Virtualbox "port forward" from Guest to Host

Network communication Host -> Guest

Connect to the Guest and find out the ip address:

ifconfig 

example of result (ip address is 10.0.2.15):

eth0      Link encap:Ethernet  HWaddr 08:00:27:AE:36:99
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0

Go to Vbox instance window -> Menu -> Network adapters:

  • adapter should be NAT
  • click on "port forwarding"
  • insert new record (+ icon)
    • for host ip enter 127.0.0.1, and for guest ip address you got from prev. step (in my case it is 10.0.2.15)
    • in your case port is 8000 - put it on both, but you can change host port if you prefer

Go to host system and try it in browser:

http://127.0.0.1:8000

or your network ip address (find out on the host machine by running: ipconfig).

Network communication Guest -> Host

In this case port forwarding is not needed, the communication goes over the LAN back to the host.

On the host machine - find out your netw ip address:

ipconfig

example of result:

IP Address. . . . . . . . . . . . : 192.168.5.1

On the guest machine you can communicate directly with the host, e.g. check it with ping:

# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...

Firewall issues?

@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):

sudo ufw allow 8000 

Extracting .jar file with command line

Given a file named Me.Jar:

  1. Go to cmd
  2. Hit Enter
  3. Use the Java jar command -- I am using jdk1.8.0_31 so I would type

    C:\Program Files (x86)\Java\jdk1.8.0_31\bin\jar xf me.jar

That should extract the file to the folder bin. Look for the file .class in my case my Me.jar contains a Valentine.class

Type java Valentine and press Enter and your message file will be opened.

C# : 'is' keyword and checking for Not

Why not just use the else ?

if (child is IContainer)
{
  //
}
else
{
  // Do what you want here
}

Its neat it familiar and simple ?

How to print out the method name and line number and conditionally disable NSLog?

building on top of above answers, here is what I plagiarized and came up with. Also added memory logging.

#import <mach/mach.h>

#ifdef DEBUG
#   define DebugLog(fmt, ...) NSLog((@"%s(%d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DebugLog(...)
#endif


#define AlwaysLog(fmt, ...) NSLog((@"%s(%d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);


#ifdef DEBUG
#   define AlertLog(fmt, ...)  { \
    UIAlertView *alert = [[UIAlertView alloc] \
            initWithTitle : [NSString stringWithFormat:@"%s(Line: %d) ", __PRETTY_FUNCTION__, __LINE__]\
                  message : [NSString stringWithFormat : fmt, ##__VA_ARGS__]\
                 delegate : nil\
        cancelButtonTitle : @"Ok"\
        otherButtonTitles : nil];\
    [alert show];\
}
#else
#   define AlertLog(...)
#endif



#ifdef DEBUG
#   define DPFLog NSLog(@"%s(%d)", __PRETTY_FUNCTION__, __LINE__);//Debug Pretty Function Log
#else
#   define DPFLog
#endif


#ifdef DEBUG
#   define MemoryLog {\
    struct task_basic_info info;\
    mach_msg_type_number_t size = sizeof(info);\
    kern_return_t e = task_info(mach_task_self(),\
                                   TASK_BASIC_INFO,\
                                   (task_info_t)&info,\
                                   &size);\
    if(KERN_SUCCESS == e) {\
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; \
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; \
        DebugLog(@"%@ bytes", [formatter stringFromNumber:[NSNumber numberWithInteger:info.resident_size]]);\
    } else {\
        DebugLog(@"Error with task_info(): %s", mach_error_string(e));\
    }\
}
#else
#   define MemoryLog
#endif

%i or %d to print integer in C using printf()?

d and i conversion specifiers behave the same with fprintf but behave differently for fscanf.

As some other wrote in their answer, the idiomatic way to print an int is using d conversion specifier.

Regarding i specifier and fprintf, C99 Rationale says that:

The %i conversion specifier was added in C89 for programmer convenience to provide symmetry with fscanf’s %i conversion specifier, even though it has exactly the same meaning as the %d conversion specifier when used with fprintf.

Can't install any packages in Node.js using "npm install"

The repository is not down, it looks like they've changed how they host files (I guess they have restored some old code):

Now you have to add the /package-name/ before the -

Eg:

http://registry.npmjs.org/-/npm-1.1.48.tgz
http://registry.npmjs.org/npm/-/npm-1.1.48.tgz

There are 3 ways to solve it:

  • Use a complete mirror:
  • Use a public proxy:

    --registry http://165.225.128.50:8000

  • Host a local proxy:

    https://github.com/hughsk/npm-quickfix

git clone https://github.com/hughsk/npm-quickfix.git
cd npm-quickfix
npm set registry http://localhost:8080/
node index.js

I'd personally go with number 3 and revert to npm set registry http://registry.npmjs.org/ as soon as this get resolved.

Stay tuned here for more info: https://github.com/isaacs/npm/issues/2694

How to execute INSERT statement using JdbcTemplate class from Spring Framework

Use jdbcTemplate.update(String sql, Object... args) method:

jdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
    var1, var2
);

or jdbcTemplate.update(String sql, Object[] args, int[] argTypes), if you need to map arguments to SQL types manually:

jdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
    new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2}
);

How to programmatically set drawableLeft on Android button?

Add a Kotlin Extension

If you are going to be doing this frequently, adding an extension makes your code more readable. Button extends TextView; use Button if you want to be more narrow.

fun TextView.leftDrawable(@DrawableRes id: Int = 0) {
    this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}

To use the extension, simply call

view.leftDrawable(R.drawable.my_drawable)

Anytime you need to clear, don't pass a param or make another extension called removeDrawables

What is the best IDE to develop Android apps in?

I advise Android bundle for TextMate: https://github.com/nesterow/Android.tmbundle It's lightweight and easy to use. There is no intellisense, but actually it just makes you remember namespaces better. :)

How do I convert array of Objects into one Object in JavaScript?

Using Underscore.js:

var myArray = [
  Object { key="11", value="1100", $$hashKey="00X"},
  Object { key="22", value="2200", $$hashKey="018"}
];
var myObj = _.object(_.pluck(myArray, 'key'), _.pluck(myArray, 'value'));

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

I wrote a simple library for manipulating the JavaScript date object. You can try this:

var dateString = timeSolver.getString(new Date(), "YYYY/MM/DD HH:MM:SS.SSS")

Library here: https://github.com/sean1093/timeSolver

How to update data in one table from corresponding data in another table in SQL Server 2005

UPDATE table1
SET column1 = (SELECT expression1
               FROM table2
               WHERE conditions)
[WHERE conditions];

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

How to install maven on redhat linux

Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file

Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:

wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz

And then proceed to install it.

UPDATE: Adding complete instructions (copied from the comment below)

  1. Run command above from the dir you want to extract maven to (e.g. /usr/local/apache-maven)
  2. run the following to extract the tar:

    tar xvf apache-maven-3.2.1-bin.tar.gz
    
  3. Next add the env varibles such as

    export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1

    export M2=$M2_HOME/bin

    export PATH=$M2:$PATH

  4. Verify

    mvn -version
    

How to gracefully handle the SIGKILL signal in Java

There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.

By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler) method call you are also able to register a signal handler, but probably not for signals like INT or TERM as they are used by the JVM.

To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.

What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid system call.

I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.

Error while trying to run project: Unable to start program. Cannot find the file specified

Deleting and restoring the entire solution from the repository resolved the issue for me. I didn't find this solution listed in any of the other answers, so thought it might help someone.

Xml serialization - Hide null values

It exists a property called XmlElementAttribute.IsNullable

If the IsNullable property is set to true, the xsi:nil attribute is generated for class members that have been set to a null reference.

The following example shows a field with the XmlElementAttribute applied to it, and the IsNullable property set to false.

public class MyClass
{
   [XmlElement(IsNullable = false)]
   public string Group;
}

You can have a look to other XmlElementAttribute for changing names in serialization etc.

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

How to find a string inside a entire database?

I usually use information_Schema.columns and information_schema.tables, although like @yuck said, sys.tables and sys.columns are shorter to type.

In a loop, concatenate these

@sql = @sql + 'select' + column_name + 
' from ' + table_name + 
' where ' + column_name ' like ''%''+value+''%' UNION

Then execute the resulting sql.

Why is HttpClient BaseAddress not working?

It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress and the relative URI passed to the GetAsync method -- or whichever other method of HttpClient -- only one permutation works. You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI, as in the following example.

using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
    client.BaseAddress = new Uri("http://something.com/api/");
    var response = await client.GetAsync("resource/7");
}

Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient.

How to hide a status bar in iOS?

I had the same problem, but its an easy fix! Just set

status bar is initially hidden = YES

then add an row by clicking on the plus right after the text status bar is initially hidden, then set the text to

view controller-based status bar appearance

by clicking the arrows, and set it to NO

Hope this helps!

css overflow - only 1 line of text

the best code for UX and UI is

white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
display: inherit;

How to determine the IP address of a Solaris system

/usr/sbin/ifconfig -a | awk 'BEGIN { count=0; } { if ( $1 ~ /inet/ ) { count++; if( count==2 ) { print $2; } } }'

This will list down the exact ip address for the machine

Cast IList to List

    public async Task<List<TimeAndAttendanceShift>> FindEntitiesByExpression(Expression<Func<TimeAndAttendanceShift, bool>> predicate)
    {
        IList<TimeAndAttendanceShift> result = await _dbContext.Set<TimeAndAttendanceShift>().Where(predicate).ToListAsync<TimeAndAttendanceShift>();

        return result.ToList<TimeAndAttendanceShift>();
    }

manage.py runserver

in flask using flask.ext.script, you can do it like this:

python manage.py runserver -h 127.0.0.1 -p 8000

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

How to check if IsNumeric

I think you need something a bit more generic. Try this:

public static System.Boolean IsNumeric (System.Object Expression)
{
    if(Expression == null || Expression is DateTime)
        return false;

    if(Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
        return true;

    try 
    {
        if(Expression is string)
            Double.Parse(Expression as string);
        else
            Double.Parse(Expression.ToString());
            return true;
        } catch {} // just dismiss errors but return false
        return false;
    }
}

Hope it helps!

Add jars to a Spark Job - spark-submit

When using spark-submit with --master yarn-cluster, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. URLs supplied after --jars must be separated by commas. That list is included in the driver and executor classpaths

Example :

spark-submit --master yarn-cluster --jars ../lib/misc.jar, ../lib/test.jar --class MainClass MainApp.jar

https://spark.apache.org/docs/latest/submitting-applications.html

Using Docker-Compose, how to execute multiple commands

try using ";" to separate the commands if you are in verions two e.g.

command: "sleep 20; echo 'a'"

Angular - How to apply [ngStyle] conditions

For a single style attribute, you can use the following syntax:

<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">

I assumed that the background color should not be set if neither style1 nor style2 is true.


Since the question title mentions ngStyle, here is the equivalent syntax with that directive:

<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">

Get text from pressed button

If you're sure that the OnClickListener instance is applied to a Button, then you could just cast the received view to a Button and get the text:

public void onClick(View view){
Button b = (Button)view;
String text = b.getText().toString();
}

How to run JUnit test cases from the command line

The answer that @lzap gave is a good solution. However, I would like to add that you should add . to the class path, so that your current directory is not left out, resulting in your own classes to be left out. This has happened to me on some platforms. So an updated version for JUnit 4.x would be:

java -cp .:/usr/share/java/junit.jar org.junit.runner.JUnitCore [test class name]

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

How can you get the first digit in an int (C#)?

int temp = i;
while (temp >= 10)
{
    temp /= 10;
}

Result in temp

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

This problem will happen if you are installing un-signed version of APK. Check if you are install correct APK.

JavaScript string and number conversion

Step (1) Concatenate "1", "2", "3" into "123"

 "1" + "2" + "3"

or

 ["1", "2", "3"].join("")

The join method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string ("").


Step (2) Convert "123" into 123

 parseInt("123")

Prior to ECMAScript 5, it was necessary to pass the radix for base 10: parseInt("123", 10)


Step (3) Add 123 + 100 = 223

 123 + 100


Step (4) Covert 223 into "223"

 (223).toString() 


Put It All Togther

 (parseInt("1" + "2" + "3") + 100).toString()

or

 (parseInt(["1", "2", "3"].join("")) + 100).toString()

Can git undo a checkout of unstaged files

In VSCODE ctrl+z (undo) worked for me

I did git checkout .instead of git add . and all my file changes were lost.

But Now using command + z in my mac , recovered the changes and saved a tone of work for me.

How to SELECT the last 10 rows of an SQL table which has no ID field?

That can be done using the limit function, this might not seem new but i have added something.The code should go:

SELECT * FROM table_name LIMIT 100,10;

for the above case assume that you have 110 rows from the table and you want to select the last ten, 100 is the row you want to start to print(if you are to print), and ten shows how many rows you want to pick from the table. For a more precised way you can start by selecting all the rows you want to print out and then you grab the last row id if you have an id column(i recommend you put one) then subtract ten from the last id number and that will be where you want to start, this will make your program to function autonomously and for any number of rows, but if you write the value directly i think you will have to change the code every time data is inserted into your table.I think this helps.Pax et Bonum.

Git pull after forced update

To receive the new commits

git fetch

Reset

You can reset the commit for a local branch using git reset.

To change the commit of a local branch:

git reset origin/master --hard

Be careful though, as the documentation puts it:

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

If you want to actually keep whatever changes you've got locally - do a --soft reset instead. Which will update the commit history for the branch, but not change any files in the working directory (and you can then commit them).

Rebase

You can replay your local commits on top of any other commit/branch using git rebase:

git rebase -i origin/master

This will invoke rebase in interactive mode where you can choose how to apply each individual commit that isn't in the history you are rebasing on top of.

If the commits you removed (with git push -f) have already been pulled into the local history, they will be listed as commits that will be reapplied - they would need to be deleted as part of the rebase or they will simply be re-included into the history for the branch - and reappear in the remote history on the next push.

Use the help git command --help for more details and examples on any of the above (or other) commands.

Random string generation with upper case letters and digits

Two methods :

import random, math

def randStr_1(chars:str, length:int) -> str:
    chars *= math.ceil(length / len(chars))
    chars = letters[0:length]
    chars = list(chars)
    random.shuffle(characters)

    return ''.join(chars)

def randStr_2(chars:str, length:int) -> str:
    return ''.join(random.choice(chars) for i in range(chars))


Benchmark :

from timeit import timeit

setup = """
import os, subprocess, time, string, random, math

def randStr_1(letters:str, length:int) -> str:
    letters *= math.ceil(length / len(letters))
    letters = letters[0:length]
    letters = list(letters)
    random.shuffle(letters)
    return ''.join(letters)

def randStr_2(letters:str, length:int) -> str:
    return ''.join(random.choice(letters) for i in range(length))
"""

print('Method 1 vs Method 2', ', run 10 times each.')

for length in [100,1000,10000,50000,100000,500000,1000000]:
    print(length, 'characters:')

    eff1 = timeit("randStr_1(string.ascii_letters, {})".format(length), setup=setup, number=10)
    eff2 = timeit("randStr_2(string.ascii_letters, {})".format(length), setup=setup, number=10)
    print('\t{}s : {}s'.format(round(eff1, 6), round(eff2, 6)))
    print('\tratio = {} : {}\n'.format(eff1/eff1, round(eff2/eff1, 2)))

Output :

Method 1 vs Method 2 , run 10 times each.

100 characters:
    0.001411s : 0.00179s
    ratio = 1.0 : 1.27

1000 characters:
    0.013857s : 0.017603s
    ratio = 1.0 : 1.27

10000 characters:
    0.13426s : 0.151169s
    ratio = 1.0 : 1.13

50000 characters:
    0.709403s : 0.855136s
    ratio = 1.0 : 1.21

100000 characters:
    1.360735s : 1.674584s
    ratio = 1.0 : 1.23

500000 characters:
    6.754923s : 7.160508s
    ratio = 1.0 : 1.06

1000000 characters:
    11.232965s : 14.223914s
    ratio = 1.0 : 1.27

The performance of first method is better.

Why doesn't "System.out.println" work in Android?

Of course, to see the result in logcat, you should set the Log level at least to "Info" (Log level in logcat); otherwise, as it happened to me, you won't see your output.

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

I have checked that the output redirection works with javaw:

javaw -cp ... mypath.MyClass ... arguments 1>log.txt 2>err.txt

It means, if the Java application prints out anything via System.out or System.err, it is written to those files, as also with using java (without w). Especially on starting java, the JRE may write starting errors (class not found) on the error output pipe. In this respect, it is essential to know about errors. I suggest to use the console redirection in any case if javaw is invoked.

In opposite if you use

start java .... 1>log.txt 2>err.txt

With the Windows console start command, the console output redirection does not work with java nor with javaw.

Explanation why it is so: I think that javaw opens an internal process in the OS (adequate using the java.lang.Process class), and transfers a known output redirection to this process. If no redirection is given on the command line, nothing is redirected and the internal started process for javaw doesn't have any console outputs. The behavior for java.lang.Process is similar. The virtual machine may use this internal feature for javaw too.

If you use 'start', the Windows console creates a new process for Windows to execute the command after start, but this mechanism does not use a given redirection for the started sub process, unfortunately.

For loop in multidimensional javascript array

JavaScript does not have such declarations. It would be:

var cubes = ...

regardless

But you can do:

for(var i = 0; i < cubes.length; i++)
{
  for(var j = 0; j < cubes[i].length; j++)
  {

  }
}

Note that JavaScript allows jagged arrays, like:

[
  [1, 2, 3],
  [1, 2, 3, 4]
]

since arrays can contain any type of object, including an array of arbitrary length.

As noted by MDC:

"for..in should not be used to iterate over an Array where index order is important"

If you use your original syntax, there is no guarantee the elements will be visited in numeric order.

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I resolved this by adding @Transactional to the base/generic Hibernate DAO implementation class (the parent class which implements the saveOrUpdate() method inherited by the DAO I use in the main program), i.e. the @Transactional needs to be specified on the actual class which implements the method. My assumption was instead that if I declared @Transactional on the child class then it included all of the methods that were inherited by the child class. However it seems that the @Transactional annotation only applies to methods implemented within a class and not to methods inherited by a class.

How can I copy the output of a command directly into my clipboard?

I wrote this little script that takes the guess work out of the copy/paste commands.

The Linux version of the script relies on xclip being already installed in your system. The script is called clipboard.

#!/bin/bash
# Linux version
# Use this script to pipe in/out of the clipboard
#
# Usage: someapp | clipboard     # Pipe someapp's output into clipboard
#        clipboard | someapp     # Pipe clipboard's content into someapp
#

if command -v xclip 1>/dev/null; then
    if [[ -p /dev/stdin ]] ; then
        # stdin is a pipe
        # stdin -> clipboard
        xclip -i -selection clipboard
    else
        # stdin is not a pipe
        # clipboard -> stdout
        xclip -o -selection clipboard
    fi
else
    echo "Remember to install xclip"
fi

The OS X version of the script relies on pbcopy and pbpaste which are preinstalled on all Macs.

#!/bin/bash
# OS X version
# Use this script to pipe in/out of the clipboard
#
# Usage: someapp | clipboard     # Pipe someapp's output into clipboard
#        clipboard | someapp     # Pipe clipboard's content into someapp
#

if [[ -p /dev/stdin ]] ; then
    # stdin is a pipe
    # stdin -> clipboard
    pbcopy
else
    # stdin is not a pipe
    # clipboard -> stdout
    pbpaste
fi

Using the script is very simple since you simply pipe in or out of clipboard as shown in these two examples.

$ cat file | clipboard

$ clipboard | less

read file in classpath

Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.

In your class, do something like this:

public void setSqlResource(Resource sqlResource) {
    this.sqlResource = sqlResource;
}

And then in your application context file, in the bean definition, just set a property:

<bean id="someBean" class="...">
    <property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>

And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.

You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I got the same error and ended up using a pre-built distribution of numpy available in SourceForge (similarly, a distribution of matplotlib can be obtained).

Builds for both 32-bit 2.7 and 3.3/3.4 are available.
PyCharm detected them straight away, of course.

What is the difference between require_relative and require in Ruby?

Summary

Use require for installed gems

Use require_relative for local files

require uses your $LOAD_PATH to find the files.
require_relative uses the current location of the file using the statement


require

Require relies on you having installed (e.g. gem install [package]) a package somewhere on your system for that functionality.

When using require you can use the "./" format for a file in the current directory, e.g. require "./my_file" but that is not a common or recommended practice and you should use require_relative instead.

require_relative

This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use

require_relative '../../../filename'

(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).

Note that require_relative uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative path "stable" as it always be relative to the file requiring it in the same way.

What's the difference between “mod” and “remainder”?

In C and C++ and many languages, % is the remainder NOT the modulus operator.

For example in the operation -21 / 4 the integer part is -5 and the decimal part is -.25. The remainder is the fractional part times the divisor, so our remainder is -1. JavaScript uses the remainder operator and confirms this

_x000D_
_x000D_
console.log(-21 % 4 == -1);
_x000D_
_x000D_
_x000D_

The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.

Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.

What's the difference between RANK() and DENSE_RANK() functions in oracle?

This article here nicely explains it. Essentially, you can look at it as such:

CREATE TABLE t AS
SELECT 'a' v FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'b'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'd'   FROM dual UNION ALL
SELECT 'e'   FROM dual;

SELECT
  v,
  ROW_NUMBER() OVER (ORDER BY v) row_number,
  RANK()       OVER (ORDER BY v) rank,
  DENSE_RANK() OVER (ORDER BY v) dense_rank
FROM t
ORDER BY v;

The above will yield:

+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a |          1 |    1 |          1 |
| a |          2 |    1 |          1 |
| a |          3 |    1 |          1 |
| b |          4 |    4 |          2 |
| c |          5 |    5 |          3 |
| c |          6 |    5 |          3 |
| d |          7 |    7 |          4 |
| e |          8 |    8 |          5 |
+---+------------+------+------------+

In words

  • ROW_NUMBER() attributes a unique value to each row
  • RANK() attributes the same row number to the same value, leaving "holes"
  • DENSE_RANK() attributes the same row number to the same value, leaving no "holes"

MySQL trigger if condition exists

I think you mean to update it back to the OLD password, when the NEW one is not supplied.

DROP TRIGGER IF EXISTS upd_user;

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '') THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

However, this means a user can never blank out a password.


If the password field (already encrypted) is being sent back in the update to mySQL, then it will not be null or blank, and MySQL will attempt to redo the Password() function on it. To detect this, use this code instead

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

How to get records randomly from the oracle database?

SELECT column FROM
( SELECT column, dbms_random.value FROM table ORDER BY 2 )
where rownum <= 20;

Possible heap pollution via varargs parameter

@SafeVarargs does not prevent it from happening, however it mandates that the compiler is stricter when compiling code that uses it.

http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html explains this in futher detail.

Heap pollution is when you get a ClassCastException when doing an operation on a generic interface and it contains another type than declared.

php how to go one level up on dirname(__FILE__)

dirname(__DIR__,level);
dirname(__DIR__,1);

level is how many times will you go back to the folder

How do I center this form in css?

Try adding this to your css

.form { width:985px; margin:0 auto }

and add width:100% to the body tag

Then put:

<div class="form">

before the tag.

Python, compute list difference

A = [1,2,3,4]
B = [2,5]

#A - B
x = list(set(A) - set(B))
#B - A 
y = list(set(B) - set(A))

print x
print y 

Simplest code for array intersection in javascript

not about efficiency, but easy to follow, here is an example of unions and intersections of sets, it handles arrays of sets and sets of sets.

http://jsfiddle.net/zhulien/NF68T/

// process array [element, element...], if allow abort ignore the result
function processArray(arr_a, cb_a, blnAllowAbort_a)
{
    var arrResult = [];
    var blnAborted = false;
    var intI = 0;

    while ((intI < arr_a.length) && (blnAborted === false))
    {
        if (blnAllowAbort_a)
        {
            blnAborted = cb_a(arr_a[intI]);
        }
        else
        {
            arrResult[intI] = cb_a(arr_a[intI]);
        }
        intI++;
    }

    return arrResult;
}

// process array of operations [operation,arguments...]
function processOperations(arrOperations_a)
{
    var arrResult = [];
    var fnOperationE;

    for(var intI = 0, intR = 0; intI < arrOperations_a.length; intI+=2, intR++) 
    {
        var fnOperation = arrOperations_a[intI+0];
        var fnArgs = arrOperations_a[intI+1];
        if (fnArgs === undefined)
        {
            arrResult[intR] = fnOperation();
        }
        else
        {
            arrResult[intR] = fnOperation(fnArgs);
        }
    }

    return arrResult;
}

// return whether an element exists in an array
function find(arr_a, varElement_a)
{
    var blnResult = false;

    processArray(arr_a, function(varToMatch_a)
    {
        var blnAbort = false;

        if (varToMatch_a === varElement_a)
        {
            blnResult = true;
            blnAbort = true;
        }

        return blnAbort;
    }, true);

    return blnResult;
}

// return the union of all sets
function union(arr_a)
{
    var arrResult = [];
    var intI = 0;

    processArray(arr_a, function(arrSet_a)
    {
        processArray(arrSet_a, function(varElement_a)
        {
            // if the element doesn't exist in our result
            if (find(arrResult, varElement_a) === false)
            {
                // add it
                arrResult[intI] = varElement_a;
                intI++;
            }
        });
    });

    return arrResult;
}

// return the intersection of all sets
function intersection(arr_a)
{
    var arrResult = [];
    var intI = 0;

    // for each set
    processArray(arr_a, function(arrSet_a)
    {
        // every number is a candidate
        processArray(arrSet_a, function(varCandidate_a)
        {
            var blnCandidate = true;

            // for each set
            processArray(arr_a, function(arrSet_a)
            {
                // check that the candidate exists
                var blnFoundPart = find(arrSet_a, varCandidate_a);

                // if the candidate does not exist
                if (blnFoundPart === false)
                {
                    // no longer a candidate
                    blnCandidate = false;
                }
            });

            if (blnCandidate)
            {
                // if the candidate doesn't exist in our result
                if (find(arrResult, varCandidate_a) === false)
                {
                    // add it
                    arrResult[intI] = varCandidate_a;
                    intI++;
                }
            }
        });
    });

    return arrResult;
}

var strOutput = ''

var arrSet1 = [1,2,3];
var arrSet2 = [2,5,6];
var arrSet3 = [7,8,9,2];

// return the union of the sets
strOutput = union([arrSet1, arrSet2, arrSet3]);
alert(strOutput);

// return the intersection of 3 sets
strOutput = intersection([arrSet1, arrSet2, arrSet3]);
alert(strOutput);

// of 3 sets of sets, which set is the intersecting set
strOutput = processOperations([intersection,[[arrSet1, arrSet2], [arrSet2], [arrSet2, arrSet3]]]);
alert(strOutput);

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Why is "using namespace std;" considered bad practice?

I do not think it is necessarily bad practice under all conditions, but you need to be careful when you use it. If you're writing a library, you probably should use the scope resolution operators with the namespace to keep your library from butting heads with other libraries. For application level code, I don't see anything wrong with it.

Android Layout Right Align

This is an example for a RelativeLayout:

RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(R.id.RelativeLayoutLeft);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                relativeLayout.setLayoutParams(params);

With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.

Get img thumbnails from Vimeo?

If you would like to use thumbnail through pure js/jquery no api, you can use this tool to capture a frame from the video and voila! Insert url thumb in which ever source you like.

Here is a code pen :

http://codepen.io/alphalink/pen/epwZpJ

<img src="https://i.vimeocdn.com/video/531141496_640.jpg"` alt="" />

Here is the site to get thumbnail:

http://video.depone.eu/

Why can't decimal numbers be represented exactly in binary?

Decimal numbers can be represented exactly, if you have enough space - just not by floating binary point numbers. If you use a floating decimal point type (e.g. System.Decimal in .NET) then plenty of values which can't be represented exactly in binary floating point can be exactly represented.

Let's look at it another way - in base 10 which you're likely to be comfortable with, you can't express 1/3 exactly. It's 0.3333333... (recurring). The reason you can't represent 0.1 as a binary floating point number is for exactly the same reason. You can represent 3, and 9, and 27 exactly - but not 1/3, 1/9 or 1/27.

The problem is that 3 is a prime number which isn't a factor of 10. That's not an issue when you want to multiply a number by 3: you can always multiply by an integer without running into problems. But when you divide by a number which is prime and isn't a factor of your base, you can run into trouble (and will do so if you try to divide 1 by that number).

Although 0.1 is usually used as the simplest example of an exact decimal number which can't be represented exactly in binary floating point, arguably 0.2 is a simpler example as it's 1/5 - and 5 is the prime that causes problems between decimal and binary.


Side note to deal with the problem of finite representations:

Some floating decimal point types have a fixed size like System.Decimal others like java.math.BigDecimal are "arbitrarily large" - but they'll hit a limit at some point, whether it's system memory or the theoretical maximum size of an array. This is an entirely separate point to the main one of this answer, however. Even if you had a genuinely arbitrarily large number of bits to play with, you still couldn't represent decimal 0.1 exactly in a floating binary point representation. Compare that with the other way round: given an arbitrary number of decimal digits, you can exactly represent any number which is exactly representable as a floating binary point.

Combining C++ and C - how does #ifdef __cplusplus work?

A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code

Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.

The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.

The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.

One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.

onNewIntent() lifecycle and registered listeners

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    setIntent(intent);
}

With all setup logic happening in onResume() by utilizing getIntent().

Using git to get just the latest revision

Alternate solution to doing shallow clone (git clone --depth=1 <URL>) would be, if remote side supports it, to use --remote option of git archive:

$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.

How to import an excel file in to a MySQL database

Another useful tool, and as a MySQL front-end replacement, is Toad for MySQL. Sadly, no longer supported by Quest, but a brilliant IDE for MySQL, with IMPORT and EXPORT wizards, catering for most file types.

Simplest way to detect a mobile device in PHP

<?php 

//-- Very simple way
$useragent = $_SERVER['HTTP_USER_AGENT']; 
$iPod = stripos($useragent, "iPod"); 
$iPad = stripos($useragent, "iPad"); 
$iPhone = stripos($useragent, "iPhone");
$Android = stripos($useragent, "Android"); 
$iOS = stripos($useragent, "iOS");
//-- You can add billion devices 

$DEVICE = ($iPod||$iPad||$iPhone||$Android||$iOS);

if (!$DEVICE) { ?>

<!-- What you want for all non-mobile devices. Anything with all HTML, PHP, CSS, even full page codes-->

<?php }else{ ?> 

<!-- What you want for all mobile devices. Anything with all HTML, PHP, CSS, even full page codes --> 

<?php } ?>

Handling back button in Android Navigation Component

This is 2 lines of code can listen for back press, from fragments, [TESTED and WORKING]

  requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {

            //setEnabled(false); // call this to disable listener
            //remove(); // call to remove listener
            //Toast.makeText(getContext(), "Listing for back press from this fragment", Toast.LENGTH_SHORT).show();
     }

How to get commit history for just one branch?

The git merge-base command can be used to find a common ancestor. So if my_experiment has not been merged into master yet and my_experiment was created from master you could:

git log --oneline `git merge-base my_experiment master`..my_experiment

Forward host port to docker container

If MongoDB and RabbitMQ are running on the Host, then the port should already exposed as it is not within Docker.

You do not need the -p option in order to expose ports from container to host. By default, all port are exposed. The -p option allows you to expose a port from the container to the outside of the host.

So, my guess is that you do not need -p at all and it should be working fine :)

align divs to the bottom of their container

The modern way to do this is with flexbox, adding align-items: flex-end; on the container.

With this content:

<div class="Container">
  <div>one</div>
  <div>two</div>
</div>

Use this style:

.Container {
  display: flex;
  align-items: flex-end;
}

https://codepen.io/rds/pen/gGMBbg

MySQL select one column DISTINCT, with corresponding other columns

Keep in mind when using the group by and order by that MySQL is the ONLY database that allows for columns to be used in the group by and/or order by piece that are not part of the select statement.

So for example: select column1 from table group by column2 order by column3

That will not fly in other databases like Postgres, Oracle, MSSQL, etc. You would have to do the following in those databases

select column1, column2, column3 from table group by column2 order by column3

Just some info in case you ever migrate your current code to another database or start working in another database and try to reuse code.

How to change pivot table data source in Excel?

In case of Excel 2007 You can change datasource in Options menu /Change Data Source

Python: importing a sub-package or sub-module

If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?

In version 2, instead of

from module import attribute1

you can do

attribute1 = module.attribute1

How to view/delete local storage in Firefox?

I could not use localStorage directly in the Firefox (v27) console. I got the error:

[Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: debugger eval code :: :: line 1" data: no]

What worked was:

window.content.localStorage

Correctly determine if date string is a valid date in that format

Tested Regex solution:

    function isValidDate($date)
    {
            if (preg_match("/^(((((1[26]|2[048])00)|[12]\d([2468][048]|[13579][26]|0[48]))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|[12]\d))))|((([12]\d([02468][1235679]|[13579][01345789]))|((1[1345789]|2[1235679])00))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|1\d|2[0-8])))))$/", $date)) {
                    return $date;
            }
            return null;
    }

This will return null if the date is invalid or is not yyyy-mm-dd format, otherwise it will return the date.

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

Why won't eclipse switch the compiler to Java 8?

I had the same problem even though I had:

  • a freshly downloaded JDK 1.8.0

  • JAVA_HOME is set

  • java -version on command line reports 1.8

  • Java in control panel is set to 1.8

  • downloaded Eclipse Mars

Eclipse only let me choose a compiler compliance level op to 1.7 in the compiler preferences, even though my installed JRE is 1.8.0. I also couldn't see a 1.8 in the Execution Environments underneath Installed JREs, only a JavaSE-1.7 (which I haven't even got installed!). When I clicked on that, it shows "jdk1.8.0" as a compatible JRE, so I selected that, but still no change.

Then I unzipped Eclipse Mars into a brand new directory, created a new project, and now I can select 1.8, hurrah! That greatly reduced the "Duplicate methods named spliterator..." errors I was getting when compiling my code under Java 1.8, however, there is still one left:

Duplicate default methods named spliterator with the parameters () and () are inherited from the types List and Set.

However, that's likely because I'm extending AbstractList and implementing Set, so I've fixed that for now by removing the implements Set because it doesn't really add anything in my case (other than signifying that my collection has only unique elements)

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

jQuery see if any or no checkboxes are selected

This is the best way to solve this problem.

  if($("#checkbox").is(":checked")){

  // Do something here /////

  };

Centering a Twitter Bootstrap button

Since you want to center the button, and not the text, what I've done in the past is add a class, then use that class to center the button:

<button class="btn btn-large btn-primary newclass" type="button">Submit</button>

and the CSS would be:

.btn.newclass {width:25%; display:block; margin: 0 auto;}

The "width" value is up to you, and you can play with that to get the right look.

Steve

Using PowerShell to remove lines from a text file if it contains a string

Escape the | character using a backtick

get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt

pass post data with window.location.href

it's as simple as this

$.post({url: "som_page.php", 
    data: { data1: value1, data2: value2 }
    ).done(function( data ) { 
        $( "body" ).html(data);
    });
});

I had to solve this to make a screen lock of my application where I had to pass sensitive data as user and the url where he was working. Then create a function that executes this code

How to link to apps on the app store

Edited on 2016-02-02

Starting from iOS 6 SKStoreProductViewController class was introduced. You can link an app without leaving your app. Code snippet in Swift 3.x/2.x and Objective-C is here.

A SKStoreProductViewController object presents a store that allows the user to purchase other media from the App Store. For example, your app might display the store to allow the user to purchase another app.


From News and Announcement For Apple Developers.

Drive Customers Directly to Your App on the App Store with iTunes Links With iTunes links you can provide your customers with an easy way to access your apps on the App Store directly from your website or marketing campaigns. Creating an iTunes link is simple and can be made to direct customers to either a single app, all your apps, or to a specific app with your company name specified.

To send customers to a specific application: http://itunes.com/apps/appname

To send customers to a list of apps you have on the App Store: http://itunes.com/apps/developername

To send customers to a specific app with your company name included in the URL: http://itunes.com/apps/developername/appname


Additional notes:

You can replace http:// with itms:// or itms-apps:// to avoid redirects.

Please note that itms:// will send the user to the iTunes store and itms-apps:// with send them to the App Store!

For info on naming, see Apple QA1633:

https://developer.apple.com/library/content/qa/qa1633/_index.html.

Edit (as of January 2015):

itunes.com/apps links should be updated to appstore.com/apps. See QA1633 above, which has been updated. A new QA1629 suggests these steps and code for launching the store from an app:

  1. Launch iTunes on your computer.
  2. Search for the item you want to link to.
  3. Right-click or control-click on the item's name in iTunes, then choose "Copy iTunes Store URL" from the pop-up menu.
  4. In your application, create an NSURL object with the copied iTunes URL, then pass this object to UIApplication' s openURL: method to open your item in the App Store.

Sample code:

NSString *iTunesLink = @"itms://itunes.apple.com/app/apple-store/id375380948?mt=8";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];

iOS10+:

 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink] options:@{} completionHandler:nil];

Swift 4.2

   let urlStr = "itms-apps://itunes.apple.com/app/apple-store/id375380948?mt=8"
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(URL(string: urlStr)!, options: [:], completionHandler: nil)
        
    } else {
        UIApplication.shared.openURL(URL(string: urlStr)!)
    }

How to add message box with 'OK' button?

Since in your situation you only want to notify the user with a short and simple message, a Toast would make for a better user experience.

Toast.makeText(getApplicationContext(), "Data saved", Toast.LENGTH_LONG).show();

Update: A Snackbar is recommended now instead of a Toast for Material Design apps.

If you have a more lengthy message that you want to give the reader time to read and understand, then you should use a DialogFragment. (The documentation currently recommends wrapping your AlertDialog in a fragment rather than calling it directly.)

Make a class that extends DialogFragment:

public class MyDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("App Title");
        builder.setMessage("This is an alert with no consequence");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // You don't have to do anything here if you just 
                // want it dismissed when clicked
            }
        });

        // Create the AlertDialog object and return it
        return builder.create();
    }
}

Then call it when you need it in your activity:

DialogFragment dialog = new MyDialogFragment();
dialog.show(getSupportFragmentManager(), "MyDialogFragmentTag");

See also

enter image description here

How do you convert epoch time in C#?

You actually want to AddMilliseconds(milliseconds), not seconds. Adding seconds will give you an out of range exception.

Is there a download function in jsFiddle?

Step 1:
Go to a fiddle page like jsfiddle.net/oskar/v5893p61

Step 2:
Add '/show' at the end of the URL, like jsfiddle.net/oskar/v5893p61/show

Step 3:
Right click on the page and click on the View frame source. You will get the HTML code including CSS in tag and Javascript (js) in tag. [Also source link of all library will be added]. See screenshot

Step 4:
Now you can save the source code in a .html file.

Maximum concurrent Socket.IO connections

This guy appears to have succeeded in having over 1 million concurrent connections on a single Node.js server.

http://blog.caustik.com/2012/08/19/node-js-w1m-concurrent-connections/

It's not clear to me exactly how many ports he was using though.

How to style icon color, size, and shadow of Font Awesome Icons

Using FA 4.4.0 adding

.text-danger
    color: #d9534f

to the document css and then using

 <i class="fa fa-ban text-danger"></i>

changes the color to red. You can set your own for any color.

What is the convention for word separator in Java package names?

Concatenation of words in the package name is something most developers don't do.

You can use something like.

com.stackoverflow.mypackage

Refer JLS Name Declaration

How to align the checkbox and label in same line in html?

If you are using bootstrap wrap your label and input with a div of a "checkbox" or "checkbox-inline" class.

<li>
    <div class="checkbox">
        <label><input type="checkbox" value="">Option 1</label>
    </div>
</li>

Reference: https://www.w3schools.com/bootstrap/bootstrap_forms_inputs.asp

Python list directory, subdirectory, and files

Since every example here is just using walk (with join), i'd like to show a nice example and comparison with listdir:

import os, time

def listFiles1(root): # listdir
    allFiles = []; walk = [root]
    while walk:
        folder = walk.pop(0)+"/"; items = os.listdir(folder) # items = folders + files
        for i in items: i=folder+i; (walk if os.path.isdir(i) else allFiles).append(i)
    return allFiles

def listFiles2(root): # listdir/join (takes ~1.4x as long) (and uses '\\' instead)
    allFiles = []; walk = [root]
    while walk:
        folder = walk.pop(0); items = os.listdir(folder) # items = folders + files
        for i in items: i=os.path.join(folder,i); (walk if os.path.isdir(i) else allFiles).append(i)
    return allFiles

def listFiles3(root): # walk (takes ~1.5x as long)
    allFiles = []
    for folder, folders, files in os.walk(root):
        for file in files: allFiles+=[folder.replace("\\","/")+"/"+file] # folder+"\\"+file still ~1.5x
    return allFiles

def listFiles4(root): # walk/join (takes ~1.6x as long) (and uses '\\' instead)
    allFiles = []
    for folder, folders, files in os.walk(root):
        for file in files: allFiles+=[os.path.join(folder,file)]
    return allFiles


for i in range(100): files = listFiles1("src") # warm up

start = time.time()
for i in range(100): files = listFiles1("src") # listdir
print("Time taken: %.2fs"%(time.time()-start)) # 0.28s

start = time.time()
for i in range(100): files = listFiles2("src") # listdir and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.38s

start = time.time()
for i in range(100): files = listFiles3("src") # walk
print("Time taken: %.2fs"%(time.time()-start)) # 0.42s

start = time.time()
for i in range(100): files = listFiles4("src") # walk and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.47s

So as you can see for yourself, the listdir version is much more efficient. (and that join is slow)

How to open Console window in Eclipse?

Just open the Window(in eclipse IDE) -> click on Reset Perspective. It worked for me.

Calculate text width with JavaScript

The ExtJS javascript library has a great class called Ext.util.TextMetrics that "provides precise pixel measurements for blocks of text so that you can determine exactly how high and wide, in pixels, a given block of text will be". You can either use it directly or view its source to code to see how this is done.

http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html

NameError: name 'datetime' is not defined

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)

Binding value to style

Try [attr.style]="changeBackground()"

Get string character by index - Java

You want .charAt()

Here's a tutorial

"mystring".charAt(2)

returns s

If you're hellbent on having a string there are a couple of ways to convert a char to a string:

String mychar = Character.toString("mystring".charAt(2));

Or

String mychar = ""+"mystring".charAt(2);

Or even

String mychar = String.valueOf("mystring".charAt(2));

For example.

Twitter Bootstrap 3.0 how do I "badge badge-important" now

In short: Replace badge-important with either alert-danger or progress-bar-danger.

It looks like this: Bootply Demo.


You might combine the CSS class badge with alert-* or progess-bar-* to color them:

With class="badges alert-*"

  <span class="badge alert-info">badge</span> Info
  <span class="badge alert-success">badge</span> Success 
  <span class="badge alert-danger">badge</span> Danger   
  <span class="badge alert-warning">badge</span> Warning

Alerts Docu: http://getbootstrap.com/components/#alerts

With class="badges progress-bar-*" (as suggested by @clami219)

  <span class="badge progress-bar-info">badge</span> Info
  <span class="badge progress-bar-success">badge</span> Success
  <span class="badge progress-bar-danger">badge</span> Danger
  <span class="badge progress-bar-warning">badge</span> Warning

Progress-Bar Docu: http://getbootstrap.com/components/#progress-alternatives

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I got the same problem in my console application development and as a quick workaround,

go to project properties then,

click on signing tab and uncheck "Sign the ClickOnce Manifest".

Image Description:

enter image description here

enter image description here

FYI You can also see this less one minute video solution. The above picture is taken form the video.

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

I got this error when I was trying to convert a char (or string) to bytes, the code was something like this with Python 2.7:

# -*- coding: utf-8 -*-
print( bytes('ò') )

This is the way of Python 2.7 when dealing with unicode chars.

This won't work with Python 3.6, since bytes require an extra argument for encoding, but this can be little tricky, since different encoding may output different result:

print( bytes('ò', 'iso_8859_1') ) # prints: b'\xf2'
print( bytes('ò', 'utf-8') ) # prints: b'\xc3\xb2'

In my case I had to use iso_8859_1 when encoding bytes in order to solve the issue.

Hope this helps someone.

Kotlin Android start new Activity

From activity to activity

val intent = Intent(this, YourActivity::class.java)
startActivity(intent)

From fragment to activity

val intent = Intent(activity, YourActivity::class.java)
startActivity(intent)

Hibernate: How to set NULL query-parameter value with HQL?

This is not a Hibernate specific issue (it's just SQL nature), and YES, there IS a solution for both SQL and HQL:

@Peter Lang had the right idea, and you had the correct HQL query. I guess you just needed a new clean run to pick up the query changes ;-)

The below code absolutely works and it is great if you keep all your queries in orm.xml

from CountryDTO c where ((:status is null and c.status is null) or c.status = :status) and c.type =:type

If your parameter String is null then the query will check if the row's status is null as well. Otherwise it will resort to compare with the equals sign.

Notes:

The issue may be a specific MySql quirk. I only tested with Oracle.

The above query assumes that there are table rows where c.status is null

The where clause is prioritized so that the parameter is checked first.

The parameter name 'type' may be a reserved word in SQL but it shouldn't matter since it is replaced before the query runs.

If you needed to skip the :status where_clause altogether; you can code like so:

from CountryDTO c where (:status is null or c.status = :status) and c.type =:type

and it is equivalent to:

sql.append(" where ");
if(status != null){
  sql.append(" c.status = :status and ");
}
sql.append(" c.type =:type ");

How to draw a graph in LaTeX?

Aside from the (excellent) suggestion to use TikZ, you could use gastex. I used this before TikZ was available and it did its job too.

No connection could be made because the target machine actively refused it 127.0.0.1:3446

I also faced problem in .Net Remoting Service in C#.

I got it solved in 3 steps:

  1. Change Port of Protocol in all the files whereever it is being used.
  2. Run your Host Server Program and make it active.
  3. Now run your client program.

Windows Batch Files: if else

You have to do the following:

if "%1" == "" (
    echo The variable is empty
) ELSE (
    echo The variable contains %1
)

Pandas conditional creation of a series/dataframe column

You can use pandas methods where and mask:

df['color'] = 'green'
df['color'] = df['color'].where(df['Set']=='Z', other='red')
# Replace values where the condition is False

or

df['color'] = 'red'
df['color'] = df['color'].mask(df['Set']=='Z', other='green')
# Replace values where the condition is True

Output:

  Type Set  color
1    A   Z  green
2    B   Z  green
3    B   X    red
4    C   Y    red

How to read strings from a Scanner in a Java console application?

Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
scanner.nextLine(); //This is needed to pick up the new line
System.out.println("Enter employee name:");
name = scanner.nextLine();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();

Calling nextInt() was a problem as it didn't pick up the new line (when you hit enter). So, calling scanner.nextLine() after that does the work.

How to replace ${} placeholders in a text file?

here's my solution with perl based on former answer, replaces environment variables:

perl -p -e 's/\$\{(\w+)\}/(exists $ENV{$1}?$ENV{$1}:"missing variable $1")/eg' < infile > outfile

How to loop through all enum values in C#?

 Enum.GetValues(typeof(Foos))

Install sbt on ubuntu

The simplest way of installing SBT on ubuntu is the deb package provided by Typesafe.

Run the following shell commands:

  1. wget http://apt.typesafe.com/repo-deb-build-0002.deb
  2. sudo dpkg -i repo-deb-build-0002.deb
  3. sudo apt-get update
  4. sudo apt-get install sbt

And you're done !

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

You need an HTML element for each column in your layout.

I’d suggest:

HTML

<div class="two-col">
    <div class="col1">
        <label for="field1">Field One:</label>
        <input id="field1" name="field1" type="text">
    </div>

    <div class="col2">
        <label for="field2">Field Two:</label>
        <input id="field2" name="field2" type="text">
    </div>
</div>

CSS

.two-col {
    overflow: hidden;/* Makes this div contain its floats */
}

.two-col .col1,
.two-col .col2 {
    width: 49%;
}

.two-col .col1 {
    float: left;
}

.two-col .col2 {
    float: right;
}

.two-col label {
    display: block;
}

How to serve .html files with Spring

It sounds like you are trying to do something like this:

  • Static HTML views
  • Spring controllers serving AJAX

If that is the case, as previously mentioned, the most efficient way is to let the web server(not Spring) handle HTML requests as static resources. So you'll want the following:

  1. Forward all .html, .css, .js, .png, etc requests to the webserver's resource handler
  2. Map all other requests to spring controllers

Here is one way to accomplish that...

web.xml - Map servlet to root (/)

<servlet>
            <servlet-name>sprung</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            ...
<servlet>

<servlet-mapping>
            <servlet-name>sprung</servlet-name>
            <url-pattern>/</url-pattern>
</servlet-mapping>

Spring JavaConfig

public class SpringSprungConfig extends DelegatingWebMvcConfiguration {

    // Delegate resource requests to default servlet
    @Bean
    protected DefaultServletHttpRequestHandler defaultServletHttpRequestHandler() {
        DefaultServletHttpRequestHandler dsrh = new DefaultServletHttpRequestHandler();
        return dsrh;
    }

    //map static resources by extension
    @Bean
    public SimpleUrlHandlerMapping resourceServletMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();

        //make sure static resources are mapped first since we are using
        //a slightly different approach
        mapping.setOrder(0);
        Properties urlProperties = new Properties();
        urlProperties.put("/**/*.css", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.js", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.png", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.html", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.woff", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.ico", "defaultServletHttpRequestHandler");
        mapping.setMappings(urlProperties);
        return mapping;
    }

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();

        //controller mappings must be evaluated after the static resource requests
        handlerMapping.setOrder(1);
        handlerMapping.setInterceptors(this.getInterceptors());
        handlerMapping.setPathMatcher(this.getPathMatchConfigurer().getPathMatcher());
        handlerMapping.setRemoveSemicolonContent(false);
        handlerMapping.setUseSuffixPatternMatch(false);
        //set other options here
        return handlerMapping;
    }
}

Additional Considerations

  • Hide .html extension - This is outside the scope of Spring if you are delegating the static resource requests. Look into a URL rewriting filter.
  • Templating - You don't want to duplicate markup in every single HTML page for common elements. This likely can't be done on the server if serving HTML as a static resource. Look into a client-side *VC framework. I'm fan of YUI which has numerous templating mechanisms including Handlebars.

How do I update an entity using spring-data-jpa?

Using spring-data-jpa save(), I was having same problem as @DtechNet. I mean every save() was creating new object instead of update. To solve this I had to add version field to entity and related table.

What is the list of valid @SuppressWarnings warning names in Java?

I noticed that //noinspection can be auto-generated in IntelliJ

  • make sure you have not already a plan @SuppressWarninigs before the statement
  • Now you can auto-generate the specific //noinspection by hitting Alt+Enter when you have the warning selected and then use the right arrow key to see the Suppress for ... option

Ended up here when I wanted to suppress a "switch has too few case labels" warning from IntelliJ. I did not find a complete List for IntelliJ's @SuppressWarning support but //noinspection did the trick for me.

Asyncio.gather vs asyncio.wait

asyncio.wait is more low level than asyncio.gather.

As the name suggests, asyncio.gather mainly focuses on gathering the results. It waits on a bunch of futures and returns their results in a given order.

asyncio.wait just waits on the futures. And instead of giving you the results directly, it gives done and pending tasks. You have to manually collect the values.

Moreover, you could specify to wait for all futures to finish or just the first one with wait.

What is the behavior of integer division?

Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.

-5 / 2 = -2
 5 / 2 =  2

For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).

Self-references in object literals / initializers

if your object is written as a function which returns an object, AND you use ES6 object-attribute 'methods', then it's possible:

const module = (state) => ({
  a: 1,
  oneThing() {
    state.b = state.b + this.a
  },
  anotherThing() {
    this.oneThing();
    state.c = state.b + this.a
  },
});

const store = {b: 10};
const root = module(store);

root.oneThing();
console.log(store);

root.anotherThing();
console.log(store);

console.log(root, Object.keys(root), root.prototype);

Execute script after specific delay using JavaScript

If you only need to test a delay you can use this:

function delay(ms) {
   ms += new Date().getTime();
   while (new Date() < ms){}
}

And then if you want to delay for 2 second you do:

delay(2000);

Might not be the best for production though. More on that in the comments

java get file size efficiently

From GHad's benchmark, there are a few issue people have mentioned:

1>Like BalusC mentioned: stream.available() is flowed in this case.

Because available() returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

So 1st to remove the URL this approach.

2>As StuartH mentioned - the order the test run also make the cache difference, so take that out by run the test separately.


Now start test:

When CHANNEL one run alone:

CHANNEL sum: 59691, per Iteration: 238.764

When LENGTH one run alone:

LENGTH sum: 48268, per Iteration: 193.072

So looks like the LENGTH one is the winner here:

@Override
public long getResult() throws Exception {
    File me = new File(FileSizeBench.class.getResource(
            "FileSizeBench.class").getFile());
    return me.length();
}

How do I get the n-th level parent of an element in jQuery?

using eq appears to grab the dynamic DOM whereas using .parent().parent() appears to grab the DOM that was initially loaded (if that is even possible).

I use them both on an element that has classes applied it to on onmouseover. eq shows the classes while .parent().parent() doesnt.

Generate signed apk android studio

Official Android Documentation on the matter at hand with a step-by-step guide included on how to generate signed APK keys in Android Studio and even on how to setup the automatic APK key generation in a Gradle build.

https://developer.android.com/studio/publish/app-signing.html

Look under the chapter: Sign your release build

ImportError: No module named 'pygame'

The current PyGame release, 1.9.6 doesn't support Python 3.9. I fyou don't want to wait for PyGame 2.0, you have to use Python 3.8. Alternatively, you can install a developer version by explicitly specifying the version (2.0.0.dev20 is the latest release at the time of writing):

pip install pygame==2.0.0.dev20

or try to install a pre-release version by enabling the --pre option:

pip install pygame --pre

List submodules in a Git repository

If there isn't any .gitmodules file, but a submodules configuration exists in .git/modules/:

find .git/modules/ -name config -exec grep url {} \;

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I've run into the very same issue, when mistakenly named variable with the very same name, as function.

So this:

isLive = isLive(data);

failed, generating OP's mentioned error message.

Fix to this was as simple as changing above line to:

isItALive = isLive(data);

I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.

Using LIKE in an Oracle IN clause

What would be useful here would be a LIKE ANY predicate as is available in PostgreSQL

SELECT * 
FROM tbl
WHERE my_col LIKE ANY (ARRAY['%val1%', '%val2%', '%val3%', ...])

Unfortunately, that syntax is not available in Oracle. You can expand the quantified comparison predicate using OR, however:

SELECT * 
FROM tbl
WHERE my_col LIKE '%val1%' OR my_col LIKE '%val2%' OR my_col LIKE '%val3%', ...

Or alternatively, create a semi join using an EXISTS predicate and an auxiliary array data structure (see this question for details):

SELECT *
FROM tbl t
WHERE EXISTS (
  SELECT 1
  -- Alternatively, store those values in a temp table:
  FROM TABLE (sys.ora_mining_varchar2_nt('%val1%', '%val2%', '%val3%'/*, ...*/))
  WHERE t.my_col LIKE column_value
)

For true full-text search, you might want to look at Oracle Text: http://www.oracle.com/technetwork/database/enterprise-edition/index-098492.html

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

Detect click outside element

You can register two event listeners for click event like this

document.getElementById("some-area")
        .addEventListener("click", function(e){
        alert("You clicked on the area!");
        e.stopPropagation();// this will stop propagation of this event to upper level
     }
);

document.body.addEventListener("click", 
   function(e) {
           alert("You clicked outside the area!");
         }
);

How to convert all tables in database to one collation?

If you're using PhpMyAdmin, you can now:

  1. Select the database.
  2. Click the "Operations" tab.
  3. Under "Collation" section, select the desired collation.
  4. Click the "Change all tables collations" checkbox.
  5. A new "Change all tables columns collations" checkbox will appear.
  6. Click the "Change all tables columns collations" checkbox.
  7. Click the "Go" button.

I had over 250 tables to convert. It took a little over 5 minutes.

How to remove listview all items

Remove the data from the adapter and call adapter.notifyDataSetChanged();

How do I center content in a div using CSS?

Update 2020:

There are several options available*:

*Disclaimer: This list may not be complete.

Using Flexbox
Nowadays, we can use flexbox. It is quite a handy alternative to the css-transform option. I would use this solution almost always. If it is just one element maybe not, but for example if I had to support an array of data e.g. rows and columns and I want them to be relatively centered in the very middle.

_x000D_
_x000D_
.flexbox {
  display: flex;
  height: 100px;
  flex-flow: row wrap;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  /* default => flex: 0 1 auto */
  background-color: #fff;
  border: 1px dotted #333;
  box-sizing: border-box;
}
_x000D_
<div class="flexbox">
  <div class="item">I am centered in the middle.</div>
  <div class="item">I am centered in the middle, too.</div>
</div>
_x000D_
_x000D_
_x000D_


Using CSS 2D-Transform
This is still a good option, was also the accepted solution back in 2015. It is very slim and simple to apply and does not mess with the layouting of other elements.

_x000D_
_x000D_
.boxes {
  position: relative;
}

.box {
  position: relative;
  display: inline-block;
  float: left;
  width: 200px;
  height: 200px;
  font-weight: bold;
  color: #333;
  margin-right: 10px;
  margin-bottom: 10px;
  background-color: #eaeaea;
}

.h-center {
  text-align: center;
}

.v-center span {
  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translate(0, -50%);
}
_x000D_
<div class="boxes">
  <div class="box h-center">horizontally centered lorem ipsun dolor sit amet</div>
  <div class="box v-center"><span>vertically centered lorem ipsun dolor sit amet lorem ipsun dolor sit amet</span></div>
  <div class="box h-center v-center"><span>horizontally and vertically centered lorem ipsun dolor sit amet</span></div>
</div>
_x000D_
_x000D_
_x000D_

Note: This does also work with :after and :before pseudo-elements.


Using Grid
This might just be an overkill, but it depends on your DOM. If you want to use grid anyway, then why not. It is very powerful alternative and you are really maximum flexible with the design.

Note: To align the items vertically we use flexbox in combination with grid. But we could also use display: grid on the items.

_x000D_
_x000D_
.grid {
  display: grid;
  width: 400px;
  grid-template-rows: 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dotted #333;
  box-sizing: border-box;
}

.item-large {
  height: 80px;
}
_x000D_
<div class="grid">
  <div class="item">Item 1</div>
  <div class="item item-large">Item 2</div>
  <div class="item">Item 3</div>
</div>
_x000D_
_x000D_
_x000D_


Further reading:

CSS article about grid
CSS article about flexbox
CSS article about centering without flexbox or grid

Creating a chart in Excel that ignores #N/A or blank cells

I had the same problem with a full line appearing.

The end of my data only had #N/A.

When I changed the chart type from a stacked line to line then the end of the line was removed from the chart.

This did not work if the #N/A was in the middle of the data, only when it was in the trailing data.

What does LayoutInflater in Android do?

LayoutInflater.inflate() provides a means to convert a res/layout/*.xml file defining a view into an actual View object usable in your application source code.

basic two steps: get the inflater and then inflate the resource

How do you get the inflater?

LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

How do you get the view assuming the xml file is "list_item.xml"?

View view = inflater.inflate(R.layout.list_item, parent, false);

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

How to drop column with constraint?

Here's another way to drop a default constraint with an unknown name without having to first run a separate query to get the constraint name:

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'__ColumnName__'
                        AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)

How to modify STYLE attribute of element with known ID using JQuery

$("span").mouseover(function () {
$(this).css({"background-color":"green","font-size":"20px","color":"red"});
});

<div>
Sachin Tendulkar has been the most complete batsman of his time, the most prolific     runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.
</div>

Does delete on a pointer to a subclass call the base class destructor?

You should delete A yourself in the destructor of B.

Why emulator is very slow in Android Studio?

The emulator is much much faster when running on Linux. In Ubuntu 13.04, it launches within 10 seconds, and it runs nearly as smoothly as on a physical device. I haven't been able to reproduce the performance on Windows.

EDIT: Actually, after the first boot, when using the Atom arch. and GPU acceleration, the Windows emulator runs nearly as well as in Linux.

What is the difference between ports 465 and 587?

Port 465: IANA has reassigned a new service to this port, and it should no longer be used for SMTP communications.

However, because it was once recognized by IANA as valid, there may be legacy systems that are only capable of using this connection method. Typically, you will use this port only if your application demands it. A quick Google search, and you'll find many consumer ISP articles that suggest port 465 as the recommended setup. Hopefully this ends soon! It is not RFC compliant.

Port 587: This is the default mail submission port. When a mail client or server is submitting an email to be routed by a proper mail server, it should always use this port.

Everyone should consider using this port as default, unless you're explicitly blocked by your upstream network or hosting provider. This port, coupled with TLS encryption, will ensure that email is submitted securely and following the guidelines set out by the IETF.

Port 25: This port continues to be used primarily for SMTP relaying. SMTP relaying is the transmittal of email from email server to email server.

In most cases, modern SMTP clients (Outlook, Mail, Thunderbird, etc) shouldn't use this port. It is traditionally blocked, by residential ISPs and Cloud Hosting Providers, to curb the amount of spam that is relayed from compromised computers or servers. Unless you're specifically managing a mail server, you should have no traffic traversing this port on your computer or server.

Most efficient way to find smallest of 3 numbers Java?

It all looks ok, your code will be fine, unless you're doing this in a tight loop. I also would consider

double min;
min = (a<b) ? a : b;
min = (min<c) ? min : c;

Export MySQL database using PHP only

Best way to export database using php script.

Or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables

<?php 
    //ENTER THE RELEVANT INFO BELOW
    $mysqlUserName      = "Your Username";
    $mysqlPassword      = "Your Password";
    $mysqlHostName      = "Your Host";
    $DbName             = "Your Database Name here";
    $backup_name        = "mybackup.sql";
    $tables             = "Your tables";

   //or add 5th parameter(array) of specific tables:    array("mytable1","mytable2","mytable3") for multiple tables

    Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName,  $tables=false, $backup_name=false );

    function Export_Database($host,$user,$pass,$name,  $tables=false, $backup_name=false )
    {
        $mysqli = new mysqli($host,$user,$pass,$name); 
        $mysqli->select_db($name); 
        $mysqli->query("SET NAMES 'utf8'");

        $queryTables    = $mysqli->query('SHOW TABLES'); 
        while($row = $queryTables->fetch_row()) 
        { 
            $target_tables[] = $row[0]; 
        }   
        if($tables !== false) 
        { 
            $target_tables = array_intersect( $target_tables, $tables); 
        }
        foreach($target_tables as $table)
        {
            $result         =   $mysqli->query('SELECT * FROM '.$table);  
            $fields_amount  =   $result->field_count;  
            $rows_num=$mysqli->affected_rows;     
            $res            =   $mysqli->query('SHOW CREATE TABLE '.$table); 
            $TableMLine     =   $res->fetch_row();
            $content        = (!isset($content) ?  '' : $content) . "\n\n".$TableMLine[1].";\n\n";

            for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) 
            {
                while($row = $result->fetch_row())  
                { //when started (and every after 100 command cycle):
                    if ($st_counter%100 == 0 || $st_counter == 0 )  
                    {
                            $content .= "\nINSERT INTO ".$table." VALUES";
                    }
                    $content .= "\n(";
                    for($j=0; $j<$fields_amount; $j++)  
                    { 
                        $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); 
                        if (isset($row[$j]))
                        {
                            $content .= '"'.$row[$j].'"' ; 
                        }
                        else 
                        {   
                            $content .= '""';
                        }     
                        if ($j<($fields_amount-1))
                        {
                                $content.= ',';
                        }      
                    }
                    $content .=")";
                    //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                    if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) 
                    {   
                        $content .= ";";
                    } 
                    else 
                    {
                        $content .= ",";
                    } 
                    $st_counter=$st_counter+1;
                }
            } $content .="\n\n\n";
        }
        //$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
        $backup_name = $backup_name ? $backup_name : $name.".sql";
        header('Content-Type: application/octet-stream');   
        header("Content-Transfer-Encoding: Binary"); 
        header("Content-disposition: attachment; filename=\"".$backup_name."\"");  
        echo $content; exit;
    }
?>

Check if a JavaScript string is a URL

Improvement on the accepted answer...

  • Check for ftp/ftps as protocol
  • Has double escaping for backslashes (\\)
  • Ensures that domains have a dot and an extension (.com .io .xyz)
  • Allows full colon (:) in the path e.g. http://thingiverse.com/download:1894343
  • Allows ampersand (&) in path e.g http://en.wikipedia.org/wiki/Procter_&_Gamble
  • Allows @ symbol in path e.g. https://medium.com/@techytimo

    isURL(str) {
      var pattern = new RegExp('^((ft|htt)ps?:\\/\\/)?'+ // protocol
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name and extension
      '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
      '(\\:\\d+)?'+ // port
      '(\\/[-a-z\\d%@_.~+&:]*)*'+ // path
      '(\\?[;&a-z\\d%@_.,~+&:=-]*)?'+ // query string
      '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
      return pattern.test(str);
    }
    

Aborting a shell script if any command returns a non-zero value

The $? variable is rarely needed. The pseudo-idiom command; if [ $? -eq 0 ]; then X; fi should always be written as if command; then X; fi.

The cases where $? is required is when it needs to be checked against multiple values:

command
case $? in
  (0) X;;
  (1) Y;;
  (2) Z;;
esac

or when $? needs to be reused or otherwise manipulated:

if command; then
  echo "command successful" >&2
else
  ret=$?
  echo "command failed with exit code $ret" >&2
  exit $ret
fi

PostgreSQL: How to change PostgreSQL user password?

You can and should have the users's password encrypted:

ALTER USER username WITH ENCRYPTED PASSWORD 'password';

A child container failed during start java.util.concurrent.ExecutionException

Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.

Remove them all.

The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.

If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.

How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat

Im Maven Project:-

add follwing line in pom.xml file

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${default.javax.servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${default.javax.servlet.jsp.version}</version>
            <scope>provided</scope>
        </dependency>

Automatic creation date for Django model form objects?

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

Can I run multiple programs in a Docker container?

There can be only one ENTRYPOINT, but that target is usually a script that launches as many programs that are needed. You can additionally use for example Supervisord or similar to take care of launching multiple services inside single container. This is an example of a docker container running mysql, apache and wordpress within a single container.

Say, You have one database that is used by a single web application. Then it is probably easier to run both in a single container.

If You have a shared database that is used by more than one application, then it would be better to run the database in its own container and the applications each in their own containers.

There are at least two possibilities how the applications can communicate with each other when they are running in different containers:

  1. Use exposed IP ports and connect via them.
  2. Recent docker versions support linking.

How to check if input file is empty in jQuery

Questions : how to check File is empty or not?

Ans: I have slove this issue using this Jquery code

_x000D_
_x000D_
//If your file Is Empty :     _x000D_
      if (jQuery('#videoUploadFile').val() == '') {_x000D_
                       $('#message').html("Please Attach File");_x000D_
                   }else {_x000D_
                            alert('not work');_x000D_
                   }_x000D_
_x000D_
    
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="videoUploadFile">_x000D_
<br>_x000D_
<br>_x000D_
<div id="message"></div>
_x000D_
_x000D_
_x000D_

How do I handle ImeOptions' done button click?

Kotlin Solution

The base way to handle it in Kotlin is:

edittext.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        callback.invoke()
        true
    }
    false
}

Kotlin Extension

Use this to just call edittext.onDone{/*action*/} in your main code. Makes your code far more readable and maintainable

fun EditText.onDone(callback: () -> Unit) {
    setOnEditorActionListener { _, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            callback.invoke()
            true
        }
        false
    }
}

Don't forget to add these options to your edittext

<EditText ...
    android:imeOptions="actionDone"
    android:inputType="text"/>

If you need inputType="textMultiLine" support, read this post

Windows Application has stopped working :: Event Name CLR20r3

This is just because the application is built in non unicode language fonts and you are running the system on unicode fonts. change your default non unicode fonts to arabic by going in regional settings advanced tab in control panel. That will solve your problem.

hibernate - get id after save object

Let's say your primary key is an Integer and the object you save is "ticket", then you can get it like this. When you save the object, a Serializable id is always returned

Integer id = (Integer)session.save(ticket);

A transport-level error has occurred when receiving results from the server

In my case the "SQL Server" Server service stopped. When I restarted the service that enabled me to run the query and eliminate the error.

Its also a good idea to examine your query to find out why the query made this service stop

enter image description here

Ajax - 500 Internal Server Error

I fixed an error like this changing the places of the routes in routes.php, for example i had something like this:

Route::resource('Mensajes', 'MensajeriaController');
Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');

and then I put it like this:

Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');
Route::resource('Mensajes', 'MensajeriaController');

How to make image hover in css?

Exact solution to your problem

You can change the image on hover by using content:url("YOUR-IMAGE-PATH");

For image hover use below line in your css:

img:hover

and to change the image on hover using the below config inside img:hover:

img:hover{
content:url("https://www.planwallpaper.com/static/images/9-credit-1.jpg");
}

Simple IEnumerator use (with example)

Here is the documentation on IEnumerator. They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate, which means "to count off or name one by one".

IEnumerator and IEnumerator<T> is provided by all IEnumerable and IEnumerable<T> interfaces (the latter providing both) in .NET via GetEnumerator(). This is important because the foreach statement is designed to work directly with enumerators through those interface methods.

So for example:

IEnumerator enumerator = enumerable.GetEnumerator();

while (enumerator.MoveNext())
{
    object item = enumerator.Current;
    // Perform logic on the item
}

Becomes:

foreach(object item in enumerable)
{
    // Perform logic on the item
}

As to your specific scenario, almost all collections in .NET implement IEnumerable. Because of that, you can do the following:

public IEnumerator Enumerate(IEnumerable enumerable)
{
    // List implements IEnumerable, but could be any collection.
    List<string> list = new List<string>(); 

    foreach(string value in enumerable)
    {
        list.Add(value + "roxxors");
    }
    return list.GetEnumerator();
}

How to add values in a variable in Unix shell scripting?

the above script may not run in ksh. you have to use the 'let' opparand to assing the value and then echo it.

val1=4

val2=3

let val3=$val1+$val2

echo $val3 

Generate class from database table

I'm trying to give my 2 cents

0) QueryFirst https://marketplace.visualstudio.com/items?itemName=bbsimonbb.QueryFirst enter image description here Query-first is a visual studio extension for working intelligently with SQL in C# projects. Use the provided .sql template to develop your queries. When you save the file, Query-first runs your query, retrieves the schema and generates two classes and an interface: a wrapper class with methods Execute(), ExecuteScalar(), ExecuteNonQuery() etc, its corresponding interface, and a POCO encapsulating a line of results.

1) Sql2Objects Creates the class starting from the result of a query (but not the DAL) enter image description here

2) https://docs.microsoft.com/en-us/ef/ef6/resources/tools enter image description here

3) https://visualstudiomagazine.com/articles/2012/12/11/sqlqueryresults-code-generation.aspx enter image description here

4) http://www.codesmithtools.com/product/generator#features

Using group by on two fields and count in SQL

SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup

Is there a unique Android device ID?

Settings.Secure#ANDROID_ID returns the Android ID as an unique for each user 64-bit hex string.

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID);

Also read Best practices for unique identifiers: https://developer.android.com/training/articles/user-data-ids

How to customize message box

Here is the code needed to create your own message box:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyStuff
{
    public class MyLabel : Label
    {
        public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Label l = new Label();
            l.Text = Text;
            l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            l.AutoSize = true;
            return l;
        }
    }
    public class MyButton : Button
    {
        public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Button b = new Button();
            b.Text = Text;
            b.Width = Width;
            b.Height = Height;
            b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
            return b;
        }
    }
    public class MyImage : PictureBox
    {
        public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
        {
            PictureBox i = new PictureBox();
            if (ImagePath != null)
            {
                i.BackgroundImageLayout = ImageLayout.Zoom;
                i.Location = new Point(9, 9);
                i.Margin = new Padding(3, 3, 2, 3);
                i.Size = new Size(Width, Height);
                i.TabStop = false;
                i.Visible = true;
                i.BackgroundImage = Image.FromFile(ImagePath);
            }
            else
            {
                i.Visible = true;
                i.Size = new Size(0, 0);
            }
            return i;
        }
    }
    public partial class MyMessageBox : Form
    {
        private MyMessageBox()
        {
            this.panText = new FlowLayoutPanel();
            this.panButtons = new FlowLayoutPanel();
            this.SuspendLayout();
            // 
            // panText
            // 
            this.panText.Parent = this;
            this.panText.AutoScroll = true;
            this.panText.AutoSize = true;
            this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            //this.panText.Location = new Point(90, 90);
            this.panText.Margin = new Padding(0);
            this.panText.MaximumSize = new Size(500, 300);
            this.panText.MinimumSize = new Size(108, 50);
            this.panText.Size = new Size(108, 50);
            // 
            // panButtons
            // 
            this.panButtons.AutoSize = true;
            this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            this.panButtons.FlowDirection = FlowDirection.RightToLeft;
            this.panButtons.Location = new Point(89, 89);
            this.panButtons.Margin = new Padding(0);
            this.panButtons.MaximumSize = new Size(580, 150);
            this.panButtons.MinimumSize = new Size(108, 0);
            this.panButtons.Size = new Size(108, 35);
            // 
            // MyMessageBox
            // 
            this.AutoScaleDimensions = new SizeF(8F, 19F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new Size(206, 133);
            this.Controls.Add(this.panButtons);
            this.Controls.Add(this.panText);
            this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.Margin = new Padding(4);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.MinimumSize = new Size(168, 132);
            this.Name = "MyMessageBox";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(Label);
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(MyLabel.Set(Label));
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            if (Labels == null) Labels = new List<Label>();
            if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
            if (Buttons == null) Buttons = new List<Button>();
            if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
            List<Button> buttons = new List<Button>(Buttons);
            buttons.Reverse();

            int ImageWidth = 0;
            int ImageHeight = 0;
            int LabelWidth = 0;
            int LabelHeight = 0;
            int ButtonWidth = 0;
            int ButtonHeight = 0;
            int TotalWidth = 0;
            int TotalHeight = 0;

            MyMessageBox mb = new MyMessageBox();

            mb.Text = Title;

            //Image
            if (Image != null)
            {
                mb.Controls.Add(Image);
                Image.MaximumSize = new Size(150, 300);
                ImageWidth = Image.Width + Image.Margin.Horizontal;
                ImageHeight = Image.Height + Image.Margin.Vertical;
            }

            //Labels
            List<int> il = new List<int>();
            mb.panText.Location = new Point(9 + ImageWidth, 9);
            foreach (Label l in Labels)
            {
                mb.panText.Controls.Add(l);
                l.Location = new Point(200, 50);
                l.MaximumSize = new Size(480, 2000);
                il.Add(l.Width);
            }
            int mw = Labels.Max(x => x.Width);
            il.ToString();
            Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
            mb.panText.Height = Labels.Sum(l => l.Height);
            mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
            mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
            LabelWidth = mb.panText.Width;
            LabelHeight = mb.panText.Height;

            //Buttons
            foreach (Button b in buttons)
            {
                mb.panButtons.Controls.Add(b);
                b.Location = new Point(3, 3);
                b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
                b.Click += new EventHandler(mb.Button_Click);
            }
            ButtonWidth = mb.panButtons.Width;
            ButtonHeight = mb.panButtons.Height;

            //Set Widths
            if (ButtonWidth > ImageWidth + LabelWidth)
            {
                Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
                mb.panText.Height = Labels.Sum(l => l.Height);
                mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
                mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
                LabelWidth = mb.panText.Width;
                LabelHeight = mb.panText.Height;
            }
            TotalWidth = ImageWidth + LabelWidth;

            //Set Height
            TotalHeight = LabelHeight + ButtonHeight;

            mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);

            mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
            mb.ShowDialog();
            return mb.Result;
        }

        private FlowLayoutPanel panText;
        private FlowLayoutPanel panButtons;
        private int ScrollBarWidth(List<Label> Labels)
        {
            return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Result = ((Button)sender).Text;
            Close();
        }

        private string Result = "";
    }
}