Programs & Examples On #Moonlight

Moonlight is a Mono based Linux port of Silverlight. Silverlight is Microsoft's cross-browser, cross platform plug-in for media experiences and rich interactive applications.

Twitter Bootstrap - how to center elements horizontally or vertically

i use this

<style>
    html, body {
        height: 100%;
        margin: 0;
        padding: 0 0;
    }

    .container-fluid {
        height: 100%;
        display: table;
        width: 100%;
        padding-right: 0;
        padding-left: 0;
    }

    .row-fluid {
        height: 100%;
        display: table-cell;
        vertical-align: middle;
        width: 100%;
    }

    .centering {
        float: none;
        margin: 0 auto;
    }
</style>
<body>
    <div class="container-fluid">
        <div class="row-fluid">
            <div class="offset3 span6 centering">
                content here
            </div>
        </div>
    </div>
</body>

Convert `List<string>` to comma-separated string

The following will result in a comma separated list. Be sure to include a using statement for System.Linq

List<string> ls = new List<string>();
ls.Add("one");
ls.Add("two");
string type = ls.Aggregate((x,y) => x + "," + y);

will yield one,two

if you need a space after the comma, simply change the last line to string type = ls.Aggregate((x,y) => x + ", " + y);

I have never set any passwords to my keystore and alias, so how are they created?

Keystore name: "debug.keystore"

Keystore password: "android"

Key alias: "androiddebugkey"

Key password: "android"

I use this information and successfully generate Signed APK.

Android Studio - How to Change Android SDK Path

This may not be what you want, but being an eclipse user I had the same problem having duplicate sdk folders which were eating all my ssd space. Currently you can only change sdk path inside android studio project wide which is annoying. What I did instead was I copied all the previous android sdk files that I was using with eclipse to /Android Studio/sdk/ and then just changed the sdk path inside eclipse.

Now both android studio and eclipse are happy.

How to colorize diff on the command line?

And for those occasions when a yum install colordiff or an apt-get install colordiff is not an option due to some insane constraint beyond your immediate control, or you're just feeling crazy, you can re-invent the wheel with a line of sed:

sed 's/^-/\x1b[41m-/;s/^+/\x1b[42m+/;s/^@/\x1b[34m@/;s/$/\x1b[0m/'

Throw that in a shell script and pipe unified diff output through it.

It makes hunk markers blue and highlights new/old filenames and added/removed lines in green and red background, respectively.1 And it will make trailing space2 changes more readily apparent than colordiff can.


1 Incidentally, the reason for highlighting the filenames the same as the modified lines is that to correctly differentiate between the filenames and the modified lines requires properly parsing the diff format, which is not something to tackle with a regex. Highlighting them the same works "well enough" visually and makes the problem trivial. That said, there are some interesting subtleties.

2 But not trailing tabs. Apparently tabs don't get their background set, at least in my xterm. It does make tab vs space changes stand out a bit though.

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

Another flexible way using classpath containing fat jar (-cp fat.jar) or all jars (-cp "$JARS_DIR/*") and another custom config classpath or folder containing configuration files usually elsewhere and outside jar. So instead of the limited java -jar, use the more flexible classpath way as follows:

java \
   -cp fat_app.jar \ 
   -Dloader.path=<path_to_your_additional_jars or config folder> \
   org.springframework.boot.loader.PropertiesLauncher

See Spring-boot executable jar doc and this link

If you do have multiple MainApps which is common, you can use How do I tell Spring Boot which main class to use for the executable jar?

You can add additional locations by setting an environment variable LOADER_PATH or loader.path in loader.properties (comma-separated list of directories, archives, or directories within archives). Basically loader.path works for both java -jar or java -cp way.

And as always you can override and exactly specify the application.yml it should pickup for debugging purpose

--spring.config.location=/some-location/application.yml --debug

Removing a non empty directory programmatically in C or C++

If you are using a POSIX compliant OS, you could use nftw() for file tree traversal and remove (removes files or directories). If you are in C++ and your project uses boost, it is not a bad idea to use the Boost.Filesystem as suggested by Manuel.

In the code example below I decided not to traverse symbolic links and mount points (just to avoid a grand removal:) ):

#include <stdio.h>
#include <stdlib.h>
#include <ftw.h>

static int rmFiles(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb)
{
    if(remove(pathname) < 0)
    {
        perror("ERROR: remove");
        return -1;
    }
    return 0;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr,"usage: %s path\n",argv[0]);
        exit(1);
    }

    // Delete the directory and its contents by traversing the tree in reverse order, without crossing mount boundaries and symbolic links

    if (nftw(argv[1], rmFiles,10, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) < 0)
    {
        perror("ERROR: ntfw");
        exit(1);
    }

    return 0;
}

How to generate a unique hash code for string input in android...?

I use this i tested it as key from my EhCacheManager Memory map ....

Its cleaner i suppose

   /**
     * Return Hash256 of String value
     *
     * @param text
     * @return 
     */
    public static String getHash256(String text) {
        try {
            return org.apache.commons.codec.digest.DigestUtils.sha256Hex(text);
        } catch (Exception ex) {
            Logger.getLogger(HashUtil.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
    }

am using maven but this is the jar commons-codec-1.9.jar

Link to all Visual Studio $ variables

Anybody working on legacy software using Visual Studio 6.0 will find that $(Configuration) and $(ProjectDir) macro's are not defined. For post-build/pre-build events, give a relative path starting with the location of your .dsw file(workspace) as the starting point. In relative path dot represents the current directory and .. represents the parent directory. Give a relative path to the file that need to be processed. Example: ( copy /y .\..\..\Debug\mylib.dll .\..\MyProject\Debug\ )

Find the number of downloads for a particular app in apple appstore

I think developers can do this for their own apps via iTunes Connect but this doesn't help you if you are looking for stats on other peoples apps.

148Apps also have some aggregate AppStore metrics on their web site that could be useful to you but, again, doesn't really give a low-level breakdown of numbers.

You could also scrape some stats from the RSS feeds generated by the iTunes Store RSS Generator but, again, this just gets currently popular apps rather than actual download numbers.

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

In case you're looking for a solution that converts ANY FORMAT to 24 hours HH:MM correctly.

function get24hTime(str){
    str = String(str).toLowerCase().replace(/\s/g, '');
    var has_am = str.indexOf('am') >= 0;
    var has_pm = str.indexOf('pm') >= 0;
    // first strip off the am/pm, leave it either hour or hour:minute
    str = str.replace('am', '').replace('pm', '');
    // if hour, convert to hour:00
    if (str.indexOf(':') < 0) str = str + ':00';
    // now it's hour:minute
    // we add am/pm back if striped out before 
    if (has_am) str += ' am';
    if (has_pm) str += ' pm';
    // now its either hour:minute, or hour:minute am/pm
    // put it in a date object, it will convert to 24 hours format for us 
    var d = new Date("1/1/2011 " + str);
    // make hours and minutes double digits
    var doubleDigits = function(n){
        return (parseInt(n) < 10) ? "0" + n : String(n);
    };
    return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
}

console.log(get24hTime('6')); // 06:00
console.log(get24hTime('6am')); // 06:00
console.log(get24hTime('6pm')); // 18:00
console.log(get24hTime('6:11pm')); // 18:11
console.log(get24hTime('6:11')); // 06:11
console.log(get24hTime('18')); // 18:00
console.log(get24hTime('18:11')); // 18:11

Java : Convert formatted xml file to one line string

FileUtils.readFileToString(fileName);

link

How to use continue in jQuery each() loop?

We can break both a $(selector).each() loop and a $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

return false; // this is equivalent of 'break' for jQuery loop

return;       // this is equivalent of 'continue' for jQuery loop

Note that $(selector).each() and $.each() are different functions.

References:

MongoDB running but can't connect using shell

I had a similar problem, well actually the same (mongo process is running but can't connect to it). What I did was went to my database path and removed mongod.lock, and then gave it another try (restarted mongo). After that it worked.

Hope it works for you too. mongodb repair on ubuntu

How to set default value for form field in Symfony2?

Just so I understand the problem.

You want to adjust the way the form is built based on data in your entity. If the entity is being created then use some default value. If the entity is existing use the database value.

Personally, I think @MolecularMans's solution is the way to go. I would actually set the default values in the constructor or in the property statement. But you don't seem to like that approach.

Instead you can follow this: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html

You hang a listener on your form type and you can then examine your entity and adjust the builder->add statements accordingly based on havine a new or existing entity. You still need to specify your default values somewhere though you could just code them in your listener. Or pass them into the form type.

Seems like a lot of work though. Better to just pass the entity to the form with it's default values already set.

No tests found with test runner 'JUnit 4'

There are two reasons for this Exception:

  1. The source code hasn’t been compiled YET.
  2. Or on the contrary, the source code has been compiled BUT it cannot been found by JUnit.

For reason one, it has no leg to stand. Because like many people said: the ‘old’ methods work perfectly. Only the new-added methods cannot been identified. Then the second reason became the only explanation: JUnit can NOT find the freshly compiled classes. Having that in mind, I did this: Right click the project ->Java Build Path -> Edit Source item: project_name/src/test/java’s Output folder, change the Output folder into a ‘Specific output folder(path relative to project_name). Provide this value: target/test-class. Be hold: This is the default test source codes’ output folder defined by Maven. It has been overwrote by M2E (or me). That’s why JUnit cannot find it. So my guess is many people who had run into this lovely exception are most likely dealing with a Web project which is managed by Maven. Am I right?! This also contributed my conclusion that reason one should be excluded -- “old” methods can be found is because they had been automatically compiled when the Tomcat was (re)started. Into the ‘wrong’ path maybe, but JUnit found it anyway.

Before I had figured this out. I tried many things as advised: update to the latest JUnit4, Back and forth between build path and use as source folder, capital Test vs test, etc. Nothing happened until I specifically identified the output location for the test source. With all those explanation, my second reason should be re-phrased as this: the new codes had not been timely compiled to the right path! Good luck.

How to reload the current route with the angular 2 router

Solved a similar scenario by using a dummy component and route for reload, which actually does a redirect. This definitely doesn't cover all user scenarios but just worked for my scenario.

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Http } from '@angular/http';

@Component({
  selector: 'reload',
  template: `
    <h1>Reloading...</h1>
  `,
})
export class ReloadComponent implements OnInit{
  constructor(private router: Router, private route: ActivatedRoute) {
  }

  ngOnInit() {
    const url = this.route.snapshot.pathFromRoot.pop().url.map(u => u.path).join('/');
    this.router.navigateByUrl(url);
  }
}

The routing is wired to catch all urls using a wildcard:

import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { LoginViewComponent } from './views/login/login.component';
import { HomeViewComponent } from './views/home/home.component';
import { ReloadComponent } from './views/reload/reload.component';

@NgModule({
  declarations: [ 
    LoginViewComponent, HomeViewComponent, ReloadComponent
  ],
  imports: [
    RouterModule.forRoot([
      { path: 'login', component: LoginViewComponent },
      { path: 'home', component: HomeViewComponent },
      { 
        path: 'reload',
        children: [{
          path: '**',
          component: ReloadComponent 
        }]
      },
      { path: '**', redirectTo: 'login'}
    ])
  ],
  exports: [
    RouterModule,
  ],
  providers: [],

})
export class AppRoutingModule {}

To use this, we just need to add reload to the url where we want to go:

  this.router.navigateByUrl('reload/some/route/again/fresh', {skipLocationChange: true})

How to find the Vagrant IP?

I've developed a small vagrant-address plugin for that. It's simple, cross-platform, cross-provider, and does not require scripting.

https://github.com/mkuzmin/vagrant-address

How to modify a specified commit?

To get a non-interactive command, put a script with this content in your PATH:

#!/bin/sh
#
# git-fixup
# Use staged changes to modify a specified commit
set -e
cmt=$(git rev-parse $1)
git commit --fixup="$cmt"
GIT_EDITOR=true git rebase -i --autosquash "$cmt~1"

Use it by staging your changes (with git add) and then run git fixup <commit-to-modify>. Of course, it will still be interactive if you get conflicts.

How to put/get multiple JSONObjects to JSONArray?

Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

Something like this maybe:

jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);

Then create new JSONObject, put the other values into it and add it to the JSONArray:

jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

I don't know why but its happened when you submit a form inside a page to itself by the POST method.

So change the method="post" to method="get" or remove action="anyThings.any" from your <form> tag.

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

Reshaping data.frame from wide to long format

Since this answer is tagged with , I felt it would be useful to share another alternative from base R: stack.

Note, however, that stack does not work with factors--it only works if is.vector is TRUE, and from the documentation for is.vector, we find that:

is.vector returns TRUE if x is a vector of the specified mode having no attributes other than names. It returns FALSE otherwise.

I'm using the sample data from @Jaap's answer, where the values in the year columns are factors.

Here's the stack approach:

cbind(wide[1:2], stack(lapply(wide[-c(1, 2)], as.character)))
##    Code     Country values  ind
## 1   AFG Afghanistan 20,249 1950
## 2   ALB     Albania  8,097 1950
## 3   AFG Afghanistan 21,352 1951
## 4   ALB     Albania  8,986 1951
## 5   AFG Afghanistan 22,532 1952
## 6   ALB     Albania 10,058 1952
## 7   AFG Afghanistan 23,557 1953
## 8   ALB     Albania 11,123 1953
## 9   AFG Afghanistan 24,555 1954
## 10  ALB     Albania 12,246 1954

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

If using Spring Boot this works well. Even with Spring Reactive Mongo.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

and validation config:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@Configuration
public class MongoValidationConfig {

    @Bean
    public ValidatingMongoEventListener validatingMongoEventListener() {
        return new ValidatingMongoEventListener(validator());
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        return new LocalValidatorFactoryBean();
    }
}

How do I convert a list into a string with spaces in Python?

"".join([i for i in my_list])

This should work just like you asked!

javascript function wait until another function to finish

Following answer can help in this and other similar situations like synchronous AJAX call -

Working example

waitForMe().then(function(intentsArr){
  console.log('Finally, I can execute!!!');
},
function(err){
  console.log('This is error message.');
})

function waitForMe(){
    // Returns promise
    console.log('Inside waitForMe');
    return new Promise(function(resolve, reject){
        if(true){ // Try changing to 'false'
            setTimeout(function(){
                console.log('waitForMe\'s function succeeded');
                resolve();
            }, 2500);
        }
        else{
            setTimeout(function(){
                console.log('waitForMe\'s else block failed');
                resolve();
            }, 2500);
        }
    });
}

Change label text using JavaScript

Because the script will get executed first.. When the script will get executed, at that time controls are not getting loaded. So after loading controls you write a script.

It will work.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved

Try the following :

  1. Make sure you add M2_HOME variable to your environment variables. It looks like you might have set M2_HOME temporarily in a cmd window and not as a permanent environment variable. Also append M2_HOME to the PATH variable.

  2. Go to the m2 folder in your user directory.

    Example: On Windows, for user bot, the .m2 directory will be under C:\Users\bot. Look for the settings.xml file in this directory and look for the repository url within this file. See if you are able to hit this url from your browser. If not, you probably need to point to a different maven repository or use a proxy.

  3. If you are able to hit the repository url from the browser, then check if the repository contains the maven-resource-plugin version 2.6. This can be found by navigating to org.apache.maven.plugins folder in the browser. It's possible that your pom has hard-coded the dependency of the plugin to 2.6 but it is not available in the repository. This can be fixed by changing the depndency version to the one available in the repository.

How can I find where I will be redirected using cURL?

Add this line to curl inizialization

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

and use getinfo before curl_close

$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );

es:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$html = curl_exec($ch);
$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );
curl_close($ch);

How to concatenate string and int in C?

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

JavaScript replace/regex

You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):

  "$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")

Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).

Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.

Check if a PHP cookie exists and if not set its value

Answer

You can't according to the PHP manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

Work around

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {
    setcookie('lg', 'ro');
    $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];

Setting paper size in FPDF

They say it right there in the documentation for the FPDF constructor:

FPDF([string orientation [, string unit [, mixed size]]])

This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...

size

The size used for pages. It can be either one of the following values (case insensitive):

A3 A4 A5 Letter Legal

or an array containing the width and the height (expressed in the unit given by unit).

They even give an example with custom size:

Example with a custom 100x150 mm page size:

$pdf = new FPDF('P','mm',array(100,150));

jQuery UI themes and HTML tables

I've got a one liner to make HTML Tables look BootStrapped:

<table class="table table-striped table-bordered table-hover">

The theme suits other controls and it supports alternate row highlighting.

How to find whether a ResultSet is empty or not in Java?

If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?

    public void fetchData(ResultSet res, JTable table) throws SQLException{     
    ResultSetMetaData metaData = res.getMetaData();
    int fieldsCount = metaData.getColumnCount();
    for (int i = 1; i <= fieldsCount; i++)
        ((DefaultTableModel) table.getModel()).addColumn(metaData.getColumnLabel(i));
    if (!res.first())
        JOptionPane.showMessageDialog(rootPane, "no data!");
    else
        do {
            Vector<Object> v = new Vector<Object>();
            for (int i = 1; i <= fieldsCount; i++)              
                v.addElement(res.getObject(i));         
            ((DefaultTableModel) table.getModel()).addRow(v);
        } while (res.next());
        res.close();
}

plot different color for different categorical levels using matplotlib

I usually do it using Seaborn which is built on top of matplotlib

import seaborn as sns
iris = sns.load_dataset('iris')
sns.scatterplot(x='sepal_length', y='sepal_width',
              hue='species', data=iris); 

Is it possible to select the last n items with nth-child?

Because of the definition of the semantics of nth-child, I don't see how this is possible without including the length of the list of elements involved. The point of the semantics is to allow segregation of a bunch of child elements into repeating groups (edit - thanks BoltClock) or into a first part of some fixed length, followed by "the rest". You sort-of want the opposite of that, which is what nth-last-child gives you.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Why can't overriding methods throw exceptions broader than the overridden method?

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.

Example:

class Super {
    public void throwCheckedExceptionMethod() throws IOException {
        FileReader r = new FileReader(new File("aFile.txt"));
        r.close();
    }
}

class Sub extends Super {    
    @Override
    public void throwCheckedExceptionMethod() throws FileNotFoundException {
        // FileNotFoundException extends IOException
        FileReader r = new FileReader(new File("afile.txt"));
        try {
            // close() method throws IOException (that is unhandled)
            r.close();
        } catch (IOException e) {
        }
    }
}

class Sub2 extends Sub {
    @Override
    public void throwCheckedExceptionMethod() {
        // Overriding method can throw no exception
    }
}

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

NullPointerException with JSP can also happen if:

A getter returns a non-public inner class.

This code will fail if you remove Getters's access modifier or make it private or protected.

JAVA:

package com.myPackage;
public class MyClass{ 
    //: Must be public or you will get:
    //: org.apache.jasper.JasperException: 
    //: java.lang.NullPointerException
    public class Getters{
        public String 
        myProperty(){ return(my_property); }
    };;

    //: JSP EL can only access functions:
    private Getters _get;
    public  Getters  get(){ return _get; }

    private String 
    my_property;

    public MyClass(String my_property){
        super();
        this.my_property    = my_property;
        _get = new Getters();
    };;
};;

JSP

<%@ taglib uri   ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
    MyClass inst = new MyClass("[PROP_VALUE]");
    pageContext.setAttribute("my_inst", inst ); 
%><html lang="en"><body>
    ${ my_inst.get().myProperty() }
</body></html>

dropzone.js - how to do something after ALL files are uploaded

this.on("totaluploadprogress", function(totalBytes, totalBytesSent){


                    if(totalBytes == 100) {

                        //all done! call func here
                    }
                });

How to do select from where x is equal to multiple values?

You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)

make script execution to unlimited

As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush(), but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:

set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();

How to return first 5 objects of Array in Swift?

I slightly changed Markus' answer to update it for the latest Swift version, as var inside your method declaration is no longer supported:

extension Array {
    func takeElements(elementCount: Int) -> Array {
        if (elementCount > count) {
            return Array(self[0..<count])
        }
        return Array(self[0..<elementCount])
    }
}

Filter Linq EXCEPT on properties

This is what LINQ needs

public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other, Func<T, TKey> getKey) 
{
    return from item in items
            join otherItem in other on getKey(item)
            equals getKey(otherItem) into tempItems
            from temp in tempItems.DefaultIfEmpty()
            where ReferenceEquals(null, temp) || temp.Equals(default(T))
            select item; 
}

How to trap the backspace key using jQuery?

try this one :

 $('html').keyup(function(e){if(e.keyCode == 8)alert('backspace trapped')})  

href="file://" doesn't work

The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is because you specified http://file://

The http:// at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.

Note

If you link to something like

<a href="file:///K:/yourfile.pdf">yourfile.pdf</a>

The above represents a link to a file called k:/yourfile.pdf on the k: drive on the machine on which you are viewing the URL.

You can do this, for example the below creates a link to C:\temp\test.pdf

<a href="file:///C:/Temp/test.pdf">test.pdf</a>

By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.

Most people do not have a K:/ drive.

But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).

You could try

<a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>

Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is a malformed

Oracle Add 1 hour in SQL

Use an interval:

select some_date_column + interval '1' hour 
from your_table;

How do I add comments to package.json for npm install?

I've been doing this:

{
  ...
  "scripts": {
    "about": "echo 'Say something about this project'",
    "about:clean": "echo 'Say something about the clean script'",
    "clean": "do something",
    "about:build": "echo 'Say something about building it'",
    "build": "do something",
    "about:watch": "echo 'Say something about how watch works'",
    "watch": "do something",
  }
  ...
}

This way, I can both read the "pseudo-comments" in the script itself, and also run something like the following, to see some kind of help in the terminal:

npm run about
npm run about:watch

How can you print multiple variables inside a string using printf?

printf("\nmaximum of %d and %d is = %d",a,b,c);

URL string format for connecting to Oracle database with JDBC

There are two ways to set this up. If you have an SID, use this (older) format:

jdbc:oracle:thin:@[HOST][:PORT]:SID

If you have an Oracle service name, use this (newer) format:

jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE

Source: this OraFAQ page

The call to getConnection() is correct.

Also, as duffymo said, make sure the actual driver code is present by including ojdbc6.jar in the classpath, where the number corresponds to the Java version you're using.

Change bootstrap navbar background color and font color

I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.

.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
    color: #000; /*Sets the text hover color on navbar*/
}

.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
        a:hover, .navbar-default .navbar-nav > .active > a:focus {
    color: white; /*BACKGROUND color for active*/
    background-color: #030033;
}

.navbar-default {
    background-color: #0f006f;
    border-color: #030033;
}

.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
    color: #262626;
    text-decoration: none;
    background-color: #66CCFF; /*change color of links in drop down here*/
}

.nav > li > a:hover,
.nav > li > a:focus {
    text-decoration: none;
    background-color: silver; /*Change rollover cell color here*/
}

.navbar-default .navbar-nav > li > a {
    color: white; /*Change active text color here*/
}

How do I view 'git diff' output with my preferred diff tool/ viewer?

Here's a batch file that works for Windows - assumes DiffMerge installed in default location, handles x64, handles forward to backslash replacement as necessary and has ability to install itself. Should be easy to replace DiffMerge with your favourite diff program.

To install:

gitvdiff --install 

gitvdiff.bat:

@echo off

REM ---- Install? ----
REM To install, run gitvdiff --install

if %1==--install goto install



REM ---- Find DiffMerge ----

if DEFINED ProgramFiles^(x86^) (
    Set DIFF="%ProgramFiles(x86)%\SourceGear\DiffMerge\DiffMerge.exe"
) else (
    Set DIFF="%ProgramFiles%\SourceGear\DiffMerge\DiffMerge.exe"
)



REM ---- Switch forward slashes to back slashes ----

set oldW=%2
set oldW=%oldW:/=\%
set newW=%5
set newW=%newW:/=\%


REM ---- Launch DiffMerge ----

%DIFF% /title1="Old Version" %oldW% /title2="New Version" %newW%

goto :EOF



REM ---- Install ----
:install
set selfL=%~dpnx0
set selfL=%selfL:\=/%
@echo on
git config --global diff.external %selfL%
@echo off


:EOF

Initialize a long in Java

You need to add uppercase L at the end like so

long i = 12345678910L;

Same goes true for float with 3.0f

Which should answer both of your questions

Determine version of Entity Framework I am using?

If you go to references, click on the Entity Framework, view properties It will tell you the version number.

docker: "build" requires 1 argument. See 'docker build --help'

On older versions of Docker it seems you need to use this order:

docker build -t tag .

and not

docker build . -t tag

Inline instantiation of a constant List

const is for compile-time constants. You could just make it static readonly, but that would only apply to the METRICS variable itself (which should typically be Metrics instead, by .NET naming conventions). It wouldn't make the list immutable - so someone could call METRICS.Add("shouldn't be here");

You may want to use a ReadOnlyCollection<T> to wrap it. For example:

public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
    (new List<String> { 
         SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
         SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn, 
         SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });

ReadOnlyCollection<T> just wraps a potentially-mutable collection, but as nothing else will have access to the List<T> afterwards, you can regard the overall collection as immutable.

(The capitalization here is mostly guesswork - using fuller names would make them clearer, IMO.)

Whether you declare it as IList<string>, IEnumerable<string>, ReadOnlyCollection<string> or something else is up to you... if you expect that it should only be treated as a sequence, then IEnumerable<string> would probably be most appropriate. If the order matters and you want people to be able to access it by index, IList<T> may be appropriate. If you want to make the immutability apparent, declaring it as ReadOnlyCollection<T> could be handy - but inflexible.

Can Linux apps be run in Android?

android only use linux kernel, that means the GNU tool chain like gcc as are not implemented in android, so if you want run a linux app in android, you need recompile it with google's tool chain( NDK ).

Calculating time difference in Milliseconds

From Java 8 onward you can try the following:

import java.time.*;
import java.time.temporal.ChronoUnit;

Instant start_time = Instant.now();
// Your code
Instant stop_time = Instant.now();

System.out.println(Duration.between(start_time, stop_time).toMillis());

//or

System.out.println(ChronoUnit.MILLIS.between(start_time, stop_time));

Definition of "downstream" and "upstream"

In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.

When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.

Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.

How to call stopservice() method of Service class from the calling activity class

In Kotlin you can do this...

Service:

class MyService : Service() {
    init {
        instance = this
    }

    companion object {
        lateinit var instance: MyService

        fun terminateService() {
            instance.stopSelf()
        }
    }
}

In your activity (or anywhere in your app for that matter):

btn_terminate_service.setOnClickListener {
    MyService.terminateService()
}

Note: If you have any pending intents showing a notification in Android's status bar, you may want to terminate that as well.

how to get bounding box for div element in jquery

using JQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]

how to remove css property using javascript?

You have two options:

OPTION 1:

You can use removeProperty method. It will remove a style from an element.

el.style.removeProperty('zoom');

OPTION 2:

You can set it to the default value:

el.style.zoom = "";

The effective zoom will now be whatever follows from the definitions set in the stylesheets (through link and style tags). So this syntax will only modify the local style of this element.

Change Git repository directory location.

A more Git based approach would be to make the changes to your local copy using cd or copy and pasting and then pushing these changes from local to remote repository.

If you try checking status of your local repo, it may show "untracked changes" which are actually the relocated files. To push these changes forcefully, you need to stage these files/directories by using

$ git add -A
#And commiting them
$ git commit -m "Relocating image demo files"
#And finally, push
$ git push -u local_repo -f HEAD:master

Hope it helps.

How to get option text value using AngularJS?

<div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>

AngularJS:

angular.module('ngrepeatSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.data = {
    model: null,
    availableOptions: [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ]
   };
}]);

taken from AngularJS docs

Join String list elements with a delimiter in one step

If you are using Spring you can use StringUtils.join() method which also allows you to specify prefix and suffix.

String s = StringUtils.collectionToDelimitedString(fieldRoles.keySet(),
                "\n", "<value>", "</value>");

Get unique values from a list in python

My solution to check contents for uniqueness but preserve the original order:

def getUnique(self):
    notunique = self.readLines()
    unique = []
    for line in notunique: # Loop over content
        append = True # Will be set to false if line matches existing line
        for existing in unique:
            if line == existing: # Line exists ? do not append and go to the next line
                append = False
                break # Already know file is unique, break loop
        if append: unique.append(line) # Line not found? add to list
    return unique

Edit: Probably can be more efficient by using dictionary keys to check for existence instead of doing a whole file loop for each line, I wouldn't use my solution for large sets.

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

If the requested resource of the server is using Flask. Install Flask-CORS.

Error QApplication: no such file or directory

Make sure you have qmake in your path (which qmake), and that it works (qmake -v) (IF you have to kill it with ctr-c then there is something wrong with your environment).

Then follow this: http://developer.qt.nokia.com/doc/qt-4.8/gettingstartedqt.html

jquery count li elements inside ul -> length?

You have to count the li elements not the ul elements:

if ( $('#menu ul li').length > 1 ) {

If you need every UL element containing at least two LI elements, use the filter function:

$('#menu ul').filter(function(){ return $(this).children("li").length > 1 })

You can also use that in your condition:

if ( $('#menu ul').filter(function(){ return $(this).children("li").length > 1 }).length) {

Get HTML code using JavaScript with a URL

First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).

In PHP, this is how you do it:

file_get_contents($theUrl);

In javascript, there is three ways :

Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/

var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
    if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);

Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/

var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
    alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);

Thirdly, by jQuery : [http://jsfiddle.net/edggD/2/

$.get('../edggD',function(data)//Remember, same domain
{
    alert(data);
});

]4

Convert UIImage to NSData and convert back to UIImage in Swift?

Thanks. Helped me a lot. Converted to Swift 3 and worked

To save: let data = UIImagePNGRepresentation(image)

To load: let image = UIImage(data: data)

How to: "Separate table rows with a line"

There are several ways to do that. Using HTML alone, you can write

<table border=1 frame=void rules=rows>

or, if you want a border above the first row and below the last row too,

<table border=1 frame=hsides rules=rows>

This is rather inflexible, though; you cannot e.g. make the lines dotted this way, or thicker than one pixel. This is why in the past people used special separator rows, consisting of nothing but some content intended to produce a line (it gets somewhat dirty, especially when you need to make rows e.g. just a few pixels high, but it’s possible).

For the most of it, people nowadays use CSS border properties for the purpose. It’s fairly simple and cross-browser. But note that to make the lines continuous, you need to prevent spacing between cells, using either the cellspacing=0 attribute in the table tag or the CSS rule table { border-collapse: collapse; }. Removing such spacing may necessitate adding some padding (with CSS, preferably) inside the cells.

At the simplest, you could use

<style>
table {
  border-collapse: collapse;
}
tr { 
  border: solid;
  border-width: 1px 0;
}
</style>

This puts a border above the first row and below the last row too. To prevent that, add e.g. the following into the style sheet:

tr:first-child {
  border-top: none;
}
tr:last-child {
  border-bottom: none;
}

HTML table with 100% width, with vertical scroll inside tbody

For using "overflow: scroll" you must set "display:block" on thead and tbody. And that messes up column widths between them. But then you can clone the thead row with Javascript and paste it in the tbody as a hidden row to keep the exact col widths.

$('.myTable thead > tr').clone().appendTo('.myTable tbody').addClass('hidden-to-set-col-widths');

http://jsfiddle.net/Julesezaar/mup0c5hk/

<table class="myTable">
    <thead>
        <tr>
            <td>Problem</td>
            <td>Solution</td>
            <td>blah</td>
            <td>derp</td>
        </tr>
    </thead>
    <tbody></tbody>
</table>
<p>
  Some text to here
</p>

The css:

table {
  background-color: #aaa;
  width: 100%;
}

thead,
tbody {
  display: block; // Necessary to use overflow: scroll
}

tbody {
  background-color: #ddd;
  height: 150px;
  overflow-y: scroll;
}

tbody tr.hidden-to-set-col-widths,
tbody tr.hidden-to-set-col-widths td {
  visibility: hidden;
  height: 0;
  line-height: 0;
  padding-top: 0;
  padding-bottom: 0;
}

td {
  padding: 3px 10px;
}

SQL Query to add a new column after an existing column in SQL Server 2005

If you want to alter order for columns in Sql server, There is no direct way to do this in SQL Server currently.

Have a look at http://blog.sqlauthority.com/2008/04/08/sql-server-change-order-of-column-in-database-tables/

You can change order while edit design for table.

What is the difference between a Docker image and a container?

I couldn't understand the concept of image and layer in spite of reading all the questions here and then eventually stumbled upon this excellent documentation from Docker (duh!).

The example there is really the key to understand the whole concept. It is a lengthy post, so I am summarising the key points that need to be really grasped to get clarity.

  • Image: A Docker image is built up from a series of read-only layers

  • Layer: Each layer represents an instruction in the image’s Dockerfile.

Example: The below Dockerfile contains four commands, each of which creates a layer.

FROM ubuntu:15.04

COPY . /app

RUN make /app

CMD python /app/app.py

Importantly, each layer is only a set of differences from the layer before it.

  • Container. When you create a new container, you add a new writable layer on top of the underlying layers. This layer is often called the “container layer”. All changes made to the running container, such as writing new files, modifying existing files, and deleting files, are written to this thin writable container layer.

Hence, the major difference between a container and an image is the top writable layer. All writes to the container that add new or modify existing data are stored in this writable layer. When the container is deleted, the writable layer is also deleted. The underlying image remains unchanged.

Understanding images cnd Containers from a size-on-disk perspective

To view the approximate size of a running container, you can use the docker ps -s command. You get size and virtual size as two of the outputs:

  • Size: the amount of data (on disk) that is used for the writable layer of each container

  • Virtual Size: the amount of data used for the read-only image data used by the container. Multiple containers may share some or all read-only image data. Hence these are not additive. I.e. you can't add all the virtual sizes to calculate how much size on disk is used by the image

Another important concept is the copy-on-write strategy

If a file or directory exists in a lower layer within the image, and another layer (including the writable layer) needs read access to it, it just uses the existing file. The first time another layer needs to modify the file (when building the image or running the container), the file is copied into that layer and modified.

I hope that helps someone else like me.

Maven: The packaging for this project did not assign a file to the build artifact

I have same issue. Error message for me is not complete. But in my case, I've added generation jar with sources. By placing this code in pom.xml:

<build> 
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.1.2</version>
                <executions>
                    <execution>
                        <phase>deploy</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

So in deploy phase I execute source:jar goal which produces jar with sources. And deploy ends with BUILD SUCCESS

Why does my Eclipse keep not responding?

Open your workspace\.metadata\.log file. That will tell you usually what is going wrong.

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

By default, IUSR account is used for anonymous user.

All you need to do is:

IIS -> Authentication --> Set Anonymous Authentication to Application Pool Identity.

Problem solved :)

What is a MIME type?

MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format.

For example, using the Content-type header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.

Internet Media Type (also Content-type) is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".

A MIME type is a string identifier composed of two parts: a type and a subtype.

  • The "type" refers to a logical grouping of many MIME types that are closely related to each other; it's no more than a high level category.
  • "subtypes" are specific to one file type within the "type".

The x- prefix of a MIME subtype simply means that it's non-standard.
The vnd prefix means that the MIME value is vendor specific.

Source

How can I align the columns of tables in Bash?

Below code has been tested and does exactly what is requested in the original question.

Parameters: %30s Column of 30 char and text right align. %10d integer notation, %10s will also work. Added clarification included on code comments.

stringarray[0]="a very long string.........."
# 28Char (max length for this column)
numberarray[0]=1122324333
# 10digits (max length for this column)
anotherfield[0]="anotherfield"
# 12Char (max length for this column)
stringarray[1]="a smaller string....."
numberarray[1]=123124343
anotherfield[1]="anotherfield"

printf "%30s %10d %13s" "${stringarray[0]}" ${numberarray[0]} "${anotherfield[0]}"
printf "\n"
printf "%30s %10d %13s" "${stringarray[1]}" ${numberarray[1]} "${anotherfield[1]}"
# a var string with spaces has to be quoted
printf "\n Next line will fail \n"      
printf "%30s %10d %13s" ${stringarray[0]} ${numberarray[0]} "${anotherfield[0]}"



  a very long string.......... 1122324333  anotherfield
         a smaller string.....  123124343  anotherfield

How to calculate age in T-SQL with years, months, and days

CREATE FUNCTION DBO.GET_AGE
(
@DATE AS DATETIME
)
RETURNS VARCHAR(MAX)
AS
BEGIN

DECLARE @YEAR  AS VARCHAR(50) = ''
DECLARE @MONTH AS VARCHAR(50) = ''
DECLARE @DAYS  AS VARCHAR(50) = ''
DECLARE @RESULT AS VARCHAR(MAX) = ''

SET @YEAR  = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) / 12 ))
SET @MONTH = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) % 12 ))
SET @DAYS = DATEDIFF(DD,DATEADD(MM,CONVERT(INT,CONVERT(INT,@YEAR)*12 + CONVERT(INT,@MONTH)),@DATE),GETDATE())

SET @RESULT = (RIGHT('00' + @YEAR, 2) + ' YEARS ' + RIGHT('00' + @MONTH, 2) + ' MONTHS ' + RIGHT('00' + @DAYS, 2) + ' DAYS')

RETURN @RESULT
END

SELECT DBO.GET_AGE('04/12/1986')

Centering elements in jQuery Mobile

The best option would be to put any element you want to be centered in a div like this:

        <div class="center">
            <img src="images/logo.png" />
        </div>

and css or inline style:

.center {  
      text-align:center  
 }

Getting Raw XML From SOAPMessage in Java

It turns out that one can get the raw XML by using Provider<Source>, in this way:

import java.io.ByteArrayOutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.ws.Provider;
import javax.xml.ws.Service;
import javax.xml.ws.ServiceMode;
import javax.xml.ws.WebServiceProvider;

@ServiceMode(value=Service.Mode.PAYLOAD)
@WebServiceProvider()
public class SoapProvider implements Provider<Source>
{
    public Source invoke(Source msg)
    {
        StreamResult sr = new StreamResult();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        sr.setOutputStream(out);

        try {
            Transformer trans = TransformerFactory.newInstance().newTransformer();
            trans.transform(msg, sr);

            // Use out to your heart's desire.
        }
        catch (TransformerException e) {
            e.printStackTrace();
        }    

        return msg;
    }
}

I've ended up not needing this solution, so I haven't actually tried this code myself - it might need some tweaking to get right. But I know this is the right path to go down to get the raw XML from a web service.

(I'm not sure how to make this work if you absolutely must have a SOAPMessage object, but then again, if you're going to be handling the raw XML anyways, why would you use a higher-level object?)

Run AVD Emulator without Android Studio

(Only for Windows) Why to torture yourself? Make a Simple BAT file ! :

  1. Open Notepad
  2. Create the command as shown below
  3. Save as *.bat
  4. (Optional) Create a shortcut to that *.bat, rename shortcut and change icon

Here is the command:

cd /d yourSdkPath\emulator && emulator -avd yourAVDName

Example:

cd /d D:\Android_SDK\emulator && emulator -avd Nexus_5_API_28

What is the difference between single-quoted and double-quoted strings in PHP?

A single-quoted string does not have variables within it interpreted. A double-quoted string does.

Also, a double-quoted string can contain apostrophes without backslashes, while a single-quoted string can contain unescaped quotation marks.

The single-quoted strings are faster at runtime because they do not need to be parsed.

How to check if array is not empty?

There's no mention of numpy in the question. If by array you mean list, then if you treat a list as a boolean it will yield True if it has items and False if it's empty.

l = []

if l:
    print "list has items"

if not l:
    print "list is empty"

What is an ORM, how does it work, and how should I use one?

Introduction

Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase "an ORM".

An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same language you're using.

For example, here is a completely imaginary case with a pseudo language:

You have a book class, you want to retrieve all the books of which the author is "Linus". Manually, you would do something like that:

book_list = new List();
sql = "SELECT book FROM library WHERE author = 'Linus'";
data = query(sql); // I over simplify ...
while (row = data.next())
{
     book = new Book();
     book.setAuthor(row.get('author');
     book_list.add(book);
}

With an ORM library, it would look like this:

book_list = BookTable.query(author="Linus");

The mechanical part is taken care of automatically via the ORM library.

Pros and Cons

Using ORM saves a lot of time because:

  • DRY: You write your data model in only one place, and it's easier to update, maintain, and reuse the code.
  • A lot of stuff is done automatically, from database handling to I18N.
  • It forces you to write MVC code, which, in the end, makes your code a little cleaner.
  • You don't have to write poorly-formed SQL (most Web programmers really suck at it, because SQL is treated like a "sub" language, when in reality it's a very powerful and complex one).
  • Sanitizing; using prepared statements or transactions are as easy as calling a method.

Using an ORM library is more flexible because:

  • It fits in your natural way of coding (it's your language!).
  • It abstracts the DB system, so you can change it whenever you want.
  • The model is weakly bound to the rest of the application, so you can change it or use it anywhere else.
  • It lets you use OOP goodness like data inheritance without a headache.

But ORM can be a pain:

  • You have to learn it, and ORM libraries are not lightweight tools;
  • You have to set it up. Same problem.
  • Performance is OK for usual queries, but a SQL master will always do better with his own SQL for big projects.
  • It abstracts the DB. While it's OK if you know what's happening behind the scene, it's a trap for new programmers that can write very greedy statements, like a heavy hit in a for loop.

How to learn about ORM?

Well, use one. Whichever ORM library you choose, they all use the same principles. There are a lot of ORM libraries around here:

If you want to try an ORM library in Web programming, you'd be better off using an entire framework stack like:

  • Symfony (PHP, using Propel or Doctrine).
  • Django (Python, using a internal ORM).

Do not try to write your own ORM, unless you are trying to learn something. This is a gigantic piece of work, and the old ones took a lot of time and work before they became reliable.

Echo off but messages are displayed

As Mike Nakis said, echo off only prevents the printing of commands, not results. To hide the result of a command add >nul to the end of the line, and to hide errors add 2>nul. For example:

Del /Q *.tmp >nul 2>nul

Like Krister Andersson said, the reason you get an error is your variable is expanding with spaces:

set INSTALL_PATH=C:\My App\Installer
if exist %INSTALL_PATH% (

Becomes:

if exist C:\My App\Installer (

Which means:

If "C:\My" exists, run "App\Installer" with "(" as the command line argument.

You see the error because you have no folder named "App". Put quotes around the path to prevent this splitting.

Disable same origin policy in Chrome

for mac users:

open -a "Google Chrome" --args --disable-web-security --user-data-dir

and before Chrome 48, you could just use:

open -a "Google Chrome" --args --disable-web-security

How do I escape reserved words used as column names? MySQL/Create Table

If you are interested in portability between different SQL servers you should use ANSI SQL queries. String escaping in ANSI SQL is done by using double quotes ("). Unfortunately, this escaping method is not portable to MySQL, unless it is set in ANSI compatibility mode.

Personally, I always start my MySQL server with the --sql-mode='ANSI' argument since this allows for both methods for escaping. If you are writing queries that are going to be executed in a MySQL server that was not setup / is controlled by you, here is what you can do:

  • Write all you SQL queries in ANSI SQL
  • Enclose them in the following MySQL specific queries:

    SET @OLD_SQL_MODE=@@SQL_MODE;
    SET SESSION SQL_MODE='ANSI';
    -- ANSI SQL queries
    SET SESSION SQL_MODE=@OLD_SQL_MODE;
    

This way the only MySQL specific queries are at the beginning and the end of your .sql script. If you what to ship them for a different server just remove these 3 queries and you're all set. Even more conveniently you could create a script named: script_mysql.sql that would contain the above mode setting queries, source a script_ansi.sql script and reset the mode.

How to get div height to auto-adjust to background size?

This Worked For Me:

background-image: url("/assets/image_complete_path");
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover;
height: 100%;

How to use mysql JOIN without ON condition?

There are several ways to do a cross join or cartesian product:

SELECT column_names FROM table1 CROSS JOIN table2;

SELECT column_names FROM table1, table2;

SELECT column_names FROM table1 JOIN table2;

Neglecting the on condition in the third case is what results in a cross join.

SQL to find the number of distinct values in a column

Count(distinct({fieldname})) is redundant

Simply Count({fieldname}) gives you all the distinct values in that table. It will not (as many presume) just give you the Count of the table [i.e. NOT the same as Count(*) from table]

How to extract text from a string using sed?

sed doesn't recognize \d, use [[:digit:]] instead. You will also need to escape the + or use the -r switch (-E on OS X).

Note that [0-9] works as well for Arabic-Hindu numerals.

Inserting HTML elements with JavaScript

Instead of directly messing with innerHTML it might be better to create a fragment and then insert that:

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }
    return frag;
}

var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);

Benefits:

  1. You can use native DOM methods for insertion such as insertBefore, appendChild etc.
  2. You have access to the actual DOM nodes before they're inserted; you can access the fragment's childNodes object.
  3. Using document fragments is very quick; faster than creating elements outside of the DOM and in certain situations faster than innerHTML.

Even though innerHTML is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

Scott Jehl came up with a fantastic solution that uses the accelerometer to anticipate orientation changes. This solution is very responsive and does not interfere with zoom gestures.

https://github.com/scottjehl/iOS-Orientationchange-Fix

How it works: This fix works by listening to the device's accelerometer to predict when an orientation change is about to occur. When it deems an orientation change imminent, the script disables user zooming, allowing the orientation change to occur properly, with zooming disabled. The script restores zoom again once the device is either oriented close to upright, or after its orientation has changed. This way, user zooming is never disabled while the page is in use.

Minified source:

/*! A fix for the iOS orientationchange zoom bug. Script by @scottjehl, rebound by @wilto.MIT License.*/(function(m){if(!(/iPhone|iPad|iPod/.test(navigator.platform)&&navigator.userAgent.indexOf("AppleWebKit")>-1)){return}var l=m.document;if(!l.querySelector){return}var n=l.querySelector("meta[name=viewport]"),a=n&&n.getAttribute("content"),k=a+",maximum-scale=1",d=a+",maximum-scale=10",g=true,j,i,h,c;if(!n){return}function f(){n.setAttribute("content",d);g=true}function b(){n.setAttribute("content",k);g=false}function e(o){c=o.accelerationIncludingGravity;j=Math.abs(c.x);i=Math.abs(c.y);h=Math.abs(c.z);if(!m.orientation&&(j>7||((h>6&&i<8||h<8&&i>6)&&j>5))){if(g){b()}}else{if(!g){f()}}}m.addEventListener("orientationchange",f,false);m.addEventListener("devicemotion",e,false)})(this);

MVC Return Partial View as JSON

Instead of RenderViewToString I prefer a approach like

return Json(new { Url = Url.Action("Evil", model) });

then you can catch the result in your javascript and do something like

success: function(data) {
    $.post(data.Url, function(partial) { 
        $('#IdOfDivToUpdate').html(partial);
    });
}

Jenkins could not run git

Adding "/usr/bin/git" >> Path to Git executable, didn't work for me. Then I deleted the contents of $JENKINS_HOME/fingerprints and restarted Jenkins. The problem goes away.

docker-compose up for only certain containers

You can use the run command and specify your services to run. Be careful, the run command does not expose ports to the host. You should use the flag --service-ports to do that if needed.

docker-compose run --service-ports client server database

Understanding inplace=True

inplace=True makes the function impure. It changes the original dataframe and returns None. In that case, You breaks the DSL chain. Because most of dataframe functions return a new dataframe, you can use the DSL conveniently. Like

df.sort_values().rename().to_csv()

Function call with inplace=True returns None and DSL chain is broken. For example

df.sort_values(inplace=True).rename().to_csv()

will throw NoneType object has no attribute 'rename'

Something similar with python’s build-in sort and sorted. lst.sort() returns None and sorted(lst) returns a new list.

Generally, do not use inplace=True unless you have specific reason of doing so. When you have to write reassignment code like df = df.sort_values(), try attaching the function call in the DSL chain, e.g.

df = pd.read_csv().sort_values()...

How to install an APK file on an Android phone?

outside device,we can use :

adb install file.apk

or adb install -r file.apk

  adb install [-l] [-r] [-s] [--algo <algorithm name> --key <hex-encoded key> --iv <hex-encoded iv>] <file>
                               - push this package file to the device and install it
                                 ('-l' means forward-lock the app)
                                 ('-r' means reinstall the app, keeping its data)
                                 ('-s' means install on SD card instead of internal storage)
                                 ('--algo', '--key', and '--iv' mean the file is encrypted already)

inside devices also, we can use:

pm install file.apk

or pm install -r file.apk

pm install: installs a package to the system.  Options:
    -l: install the package with FORWARD_LOCK.
    -r: reinstall an exisiting app, keeping its data.
    -t: allow test .apks to be installed.
    -i: specify the installer package name.
    -s: install package on sdcard.
    -f: install package on internal flash.
    -d: allow version code downgrade.

For more then one apk file on Linux we can use xargs and on windows we can use for loop.
Linux / Unix sample :

ls -1 *.apk | xargs -I xxx adb install -r xxx

Gson - convert from Json to a typed ArrayList<T>

Why nobody wrote this simple way of converting JSON string in List ?

List<Object> list = Arrays.asList(new GsonBuilder().create().fromJson(jsonString, Object[].class));

Import PEM into Java Key Store

I've developed http://code.google.com/p/java-keyutil/ which imports PEM certificates straight into a Java keystore. Its primary purpose is to import a multi-part PEM Operating System certificate bundles such as ca-bundle.crt. These often includes headers which keytool cannot handle

</self promotion>

Commit empty folder structure (with git)

This is easy.

tell .gitignore to ignore everything except .gitignore and the folders you want to keep. Put .gitignore into folders that you want to keep in the repo.

Contents of the top-most .gitignore:

# ignore everything except .gitignore and folders that I care about:
*
!images*
!.gitignore

In the nested images folder this is your .gitignore:

# ignore everything except .gitignore
*
!.gitignore

Note, you must spell out in the .gitignore the names of the folders you don't want to be ignored in the folder where that .gitignore is located. Otherwise they are, obviously, ignored.

Your folders in the repo will, obviously, NOT be empty, as each one will have .gitignore in it, but that part can be ignored, right. :)

How can I check if string contains characters & whitespace, not just whitespace?

Just check the string against this regex:

if(mystring.match(/^\s+$/) === null) {
    alert("String is good");
} else {
    alert("String contains only whitespace");
}

If Python is interpreted, what are .pyc files?

These are created by the Python interpreter when a .py file is imported, and they contain the "compiled bytecode" of the imported module/program, the idea being that the "translation" from source code to bytecode (which only needs to be done once) can be skipped on subsequent imports if the .pyc is newer than the corresponding .py file, thus speeding startup a little. But it's still interpreted.

How can I disable an <option> in a <select> based on its value in JavaScript?

Set an id to the option then use get element by id and disable it when x value has been selected..

example

<body>
      <select class="pull-right text-muted small" 
                 name="driveCapacity" id=driveCapacity onchange="checkRPM()">
      <option value="4000.0" id="4000">4TB</option>
      <option value="900.0" id="900">900GB</option>
      <option value="300.0" id ="300">300GB</option>
    </select>
    </body>
<script>
var perfType = document.getElementById("driveRPM").value;
if(perfType == "7200"){         
        document.getElementById("driveCapacity").value = "4000.0";
        document.getElementById("4000").disabled = false;           
    }else{          
        document.getElementById("4000").disabled = true;            
    }    
</script>

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Java 9 incompatible

I got this error when trying to calling mvn install on a project.

I had installed Java 9 on macOS as well as Java 8 Update 144. My Maven project was apparently invoking Java 9 and failing. Removed Java 9 from my Mac, leaving just Java 8 in place. Maven is now happily building my project to successful completion.

Using Apache Maven 3.5.0 on macOS Sierra.

When to use RDLC over RDL reports?

While I currently lean toward RDL because it seems more flexible and easier to manage, RDLC has an advantage in that it seems to simplify your licensing. Because RDLC doesn’t need a Reporting Services instance, you won't need a Reporting Services License to use it.

I’m not sure if this still applies with the newer versions of SQL Server, but at one time if you chose to put the SQL Server Database and Reporting Services instances on two separate machines, you were required to have two separate SQL Server licenses:
http://social.msdn.microsoft.com/forums/en-US/sqlgetstarted/thread/82dd5acd-9427-4f64-aea6-511f09aac406/

You can Bing for other similar blogs and posts regarding Reporting Services licensing.

Delete files in subfolder using batch script

del parentpath (or just place the .bat file inside parent folder) *.txt /s

That will delete all .txt files in the parent and all sub folders. If you want to delete multiple file extensions just add a space and do the same thing. Ex. *.txt *.dll *.xml

How do I automatically set the $DISPLAY variable for my current session?

I'm guessing here, based on issues I've had in the past which I did solve:

  • you're connecting to a vnc server on machine B, displaying it using a VNC client on machine A
  • you're launching a console (xterm or equivalent) on machine B and using that to connect to machine C
  • you want to launch an X-based application on machine C, having it display to the VNC server on machine B, so you can see it on machine A.

I ended up with two solutions. My original solution was based on using rsh. Since then, most of our servers have had ssh installed, which has made this easier.

Using rsh, I put together a table of machines vs OS vs custom options which would guide this process in perl. Bourne shell wasn't sufficient, and we don't have bash on Sun or HP machines (and didn't have bash on AIX at the time - AIX 5L wasn't out yet). Korn shell wasn't much of an option, either, since most of our Linux boxes don't have pdksh installed. But, if you don't face these limitations, you can implement the idea in ksh or bash, I think.

Anyway, I would basically run 'rsh $machine -l $user "$cmd"' where $machine, of course, was the machine I was logging in to, $user, similarly obvious (though when I was going in as "root" this had some variance as we have multiple roots on some machines for reasons I don't fully understand), and $cmd was basically "DISPLAY=$DISPLAY xterm", though if I were launching konsole, for example, $cmd would be "konsole --display=$DISPLAY". Since $DISPLAY was being evaluated locally (where it's set properly), and not being passed literally across rsh, the display would always be set correctly.

I also had to make sure that no one did anything silly like reset DISPLAY if it was already set.

Now, I just use ssh, make sure that X11Forwarding is set to yes on the server (sshd_config), and then I can just ssh to the machine, let X commands go across the wire encrypted, and it'll always go back to the right place.

How to change the foreign key referential action? (behavior)

I had a bunch of FKs to alter, so I wrote something to make the statements for me. Figured I'd share:

SELECT

CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
    '` DROP FOREIGN KEY `' ,rc.CONSTRAINT_NAME,'`;')
, CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
    '` ADD CONSTRAINT `' ,rc.CONSTRAINT_NAME ,'` FOREIGN KEY (`',kcu.COLUMN_NAME,
    '`) REFERENCES `',kcu.REFERENCED_TABLE_NAME,'` (`',kcu.REFERENCED_COLUMN_NAME,'`) ON DELETE CASCADE;')

FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
LEFT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
    ON kcu.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA
    AND kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
WHERE DELETE_RULE = 'NO ACTION'
AND rc.CONSTRAINT_SCHEMA = 'foo'

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

You need to replace it as WHERE clockDate = { fn CURRENT_DATE() } AND userName = 'test'. Please remove extra ")" from { fn CURRENT_DATE() })

PHP DOMDocument loadHTML not encoding UTF-8 correctly

Make sure the real source file is saved as UTF-8 (You may even want to try the non-recommended BOM Chars with UTF-8 to make sure).

Also in case of HTML, make sure you have declared the correct encoding using meta tags:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

If it's a CMS (as you've tagged your question with Joomla) you may need to configure appropriate settings for the encoding.

How to create an exit message

I've never heard of such a function, but it would be trivial enough to implement...

def die(msg)
  puts msg
  exit
end

Then, if this is defined in some .rb file that you include in all your scripts, you are golden.... just because it's not built in doesn't mean you can't do it yourself ;-)

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

For your interest, to do the same with double

double doubleVal = 1.745;
double doubleVal2 = 0.745;
doubleVal = Math.round(doubleVal * 100 + 0.005) / 100.0;
doubleVal2 = Math.round(doubleVal2 * 100 + 0.005) / 100.0;
System.out.println("bdTest: " + doubleVal); //1.75
System.out.println("bdTest1: " + doubleVal2);//0.75

or just

double doubleVal = 1.745;
double doubleVal2 = 0.745;
System.out.printf("bdTest: %.2f%n",  doubleVal);
System.out.printf("bdTest1: %.2f%n",  doubleVal2);

both print

bdTest: 1.75
bdTest1: 0.75

I prefer to keep code as simple as possible. ;)

As @mshutov notes, you need to add a little more to ensure that a half value always rounds up. This is because numbers like 265.335 are a little less than they appear.

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

I got Darin's solution working eventually but made a few mistakes first which resulted in a problem similar to David (in the comments below Darin's solution) where the result was posting to a new page.

Because I had to do something with the form after the method returned, I stored it for later use:

var form = $(this);

However, this variable did not have the "action" or "method" properties which are used in the ajax call.

$(document).on("submit", "form", function (event) {
    var form = $(this);

    if (form.valid()) {
        $.ajax({
            url: form.action, // Not available to 'form' variable
            type: form.method,  // Not available to 'form' variable
            data: form.serialize(),
            success: function (html) {
                // Do something with the returned html.
            }
        });
    }

    event.preventDefault();
});

Instead you need to use the "this" variable:

$.ajax({
    url: this.action, 
    type: this.method,
    data: $(this).serialize(),
    success: function (html) {
        // Do something with the returned html.
    }
});

Selecting an element in iFrame jQuery

If the case is accessing the IFrame via console, e. g. Chrome Dev Tools then you can just select the context of DOM requests via dropdown (see the picture).

Chrome Dev Tools - Selecting the iFrame

get data from mysql database to use in javascript

To do with javascript you could do something like this:

<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>

Then you can use whatever you want in your javascript to put the text var into the textbox.

Python: How to pip install opencv2 with specific version 2.4.9?

If you're a Windows user, opencv can be installed using pip, like this:

pip install opencv-python==<python version>

ex - pip install opencv-python==3.6

If you're a Linux user:

sudo apt-get install python-opencv

At the same time, opencv can be installed using conda like this...

conda install -c https://conda.binstar.org/menpo opencv=3.6

includes() not working in all browsers

import 'core-js/es7/array' 

into polyfill.ts worked for me.

Auto Increment after delete in MySQL

What you're trying to do sounds dangerous, as that's not the intended use of AUTO_INCREMENT.

If you really want to find the lowest unused key value, don't use AUTO_INCREMENT at all, and manage your keys manually. However, this is NOT a recommended practice.

Take a step back and ask "why you need to recycle key values?" Do unsigned INT (or BIGINT) not provide a large enough key space?

Are you really going to have more than 18,446,744,073,709,551,615 unique records over the course of your application's lifetime?

Where will log4net create this log file?

it will create the file in the root directory of your project/solution.

You can specify a location of choice in the web.config of your app as follows:

   <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:/ServiceLogs/Olympus.Core.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value=".yyyyMMdd.log" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />
      <lockingModel type="log4net.Appender.RollingFileAppender+MinimalLock" />
      <maxSizeRollBackups value="-1" />
      <countDirection value="1" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception" />
      </layout>
    </appender>

the file tag specifies the location.

java.io.InvalidClassException: local class incompatible:

If a class does not explicitly define a private static final long serialVersionUID in the code it will be autogenerated, and there is no guarantee that different machines will generate the same id; it looks like that is exactly what happened. Also if the classes are different in any way (using different versions of the class) the autogenerated serialVersionUIDs will also be different.

From the Serializable interface's docs:

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members. Array classes cannot declare an explicit serialVersionUID, so they always have the default computed value, but the requirement for matching serialVersionUID values is waived for array classes.

You should define a serialVersionUID in the class definition, e.g.:

class MyClass implements Serializable {
    private static final long serialVersionUID = 6529685098267757690L;
    ...

What are POD types in C++?

Plain Old Data

In short, it is all built-in data types (e.g. int, char, float, long, unsigned char, double, etc.) and all aggregation of POD data. Yes, it's a recursive definition. ;)

To be more clear, a POD is what we call "a struct": a unit or a group of units that just store data.

What does ellipsize mean in android?

Use ellipsize when you have fixed width, then it will automatically truncate the text & show the ellipsis at end,

it Won't work if you set layout_width as wrap_content & match_parent.

android:width="40dp"
android:ellipsize="end"
android:singleLine="true"

How to perform grep operation on all files in a directory?

To search in all sub-directories, but only in specific file types, use grep with --include.

For example, searching recursively in current directory, for text in *.yml and *.yaml :

grep "text to search" -r . --include=*.{yml,yaml}

How to manually trigger validation with jQuery validate?

My approach was as below. Now I just wanted my form to be validated when one specific checkbox was clicked/changed:

$('#myForm input:checkbox[name=yourChkBxName]').click(
 function(e){
  $("#myForm").valid();
}
)

How do you specify the Java compiler version in a pom.xml file?

<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <fork>true</fork>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin> 

VMware Workstation and Device/Credential Guard are not compatible

install the latest vmware workstation > 15.5.5 version

which has support of Hyper-V Host

With the release of VMware Workstation/Player 15.5. 5 or >, we are very excited and proud to announce support for Windows hosts with Hyper-V mode enabled! As you may know, this is a joint project from both Microsoft and VMware

https://blogs.vmware.com/workstation/2020/05/vmware-workstation-now-supports-hyper-v-mode.html

i installed the VMware.Workstation.Pro.16.1.0

and now it fixed my issue now i am using docker & vmware same time even my window Hyper-V mode is enabled

When use getOne and findOne methods Spring Data JPA

while spring.jpa.open-in-view was true, I didn't have any problem with getOne but after setting it to false , i got LazyInitializationException. Then problem was solved by replacing with findById.
Although there is another solution without replacing the getOne method, and that is put @Transactional at method which is calling repository.getOne(id). In this way transaction will exists and session will not be closed in your method and while using entity there would not be any LazyInitializationException.

What is secret key for JWT based authentication and how to generate it?

You can write your own generator. The secret key is essentially a byte array. Make sure that the string that you convert to a byte array is base64 encoded.

In Java, you could do something like this.

String key = "random_secret_key";
String base64Key = DatatypeConverter.printBase64Binary(key.getBytes());
byte[] secretBytes = DatatypeConverter.parseBase64Binary(base64Key);

Random Number Between 2 Double Numbers

Johnny5 suggested creating an extension method. Here's a more complete code example showing how you could do this:

public static class RandomExtensions
{
    public static double NextDouble(
        this Random random,
        double minValue,
        double maxValue)
    {
        return random.NextDouble() * (maxValue - minValue) + minValue;
    }
}

Now you can call it as if it were a method on the Random class:

Random random = new Random();
double value = random.NextDouble(1.23, 5.34);

Note that you should not create lots of new Random objects in a loop because this will make it likely that you get the same value many times in a row. If you need lots of random numbers then create one instance of Random and re-use it.

Unable to connect to any of the specified mysql hosts. C# MySQL

Try this:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "127.0.0.1";
conn_string.Port = 3306;
conn_string.UserID = "root";
conn_string.Password = "myPassword";
conn_string.Database = "myDB";



MySqlConnection MyCon = new MySqlConnection(conn_string.ToString());

try
{
    MyCon.Open();
    MessageBox.Show("Open");
    MyCon.Close();
    MessageBox.Show("Close");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

Creating a daemon in Linux

By calling fork() you've created a child process. If the fork is successful (fork returned a non-zero PID) execution will continue from this point from within the child process. In this case we want to gracefully exit the parent process and then continue our work in the child process.

Maybe this will help: http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html

How to update std::map after using the find method?

If you already know the key, you can directly update the value at that key using m[key] = new_value

Here is a sample code that might help:

map<int, int> m;

for(int i=0; i<5; i++)
    m[i] = i;

for(auto it=m.begin(); it!=m.end(); it++)
    cout<<it->second<<" ";
//Output: 0 1 2 3 4

m[4] = 7;  //updating value at key 4 here

cout<<"\n"; //Change line

for(auto it=m.begin(); it!=m.end(); it++)
    cout<<it->second<<" ";
// Output: 0 1 2 3 7    

C: What is the difference between ++i and i++?

The following C code fragment illustrates the difference between the pre and post increment and decrement operators:

int  i;
int  j;

Increment operators:

i = 1;
j = ++i;    // i is now 2, j is also 2
j = i++;    // i is now 3, j is 2

How to check if a Docker image with a specific tag exist locally?

You can use like the following:

[ ! -z $(docker images -q someimage:sometag) ] || echo "does not exist"

Or:

[ -z $(docker images -q someimage:sometag) ] || echo "already exists"

What are the best practices for using a GUID as a primary key, specifically regarding performance?

Most of the times it should not be used as the primary key for a table because it really hit the performance of the database. useful links regarding GUID impact on performance and as a primary key.

  1. https://www.sqlskills.com/blogs/kimberly/disk-space-is-cheap/
  2. https://www.sqlskills.com/blogs/kimberly/guids-as-primary-keys-andor-the-clustering-key/

What is the best way to determine a session variable is null or empty in C#?

If you know it's a string, you can use the String.IsEmptyOrNull() function.

mkdir's "-p" option

The man pages is the best source of information you can find... and is at your fingertips: man mkdir yields this about -p switch:

-p, --parents
    no error if existing, make parent directories as needed

Use case example: Assume I want to create directories hello/goodbye but none exist:

$mkdir hello/goodbye
mkdir:cannot create directory 'hello/goodbye': No such file or directory
$mkdir -p hello/goodbye
$

-p created both, hello and goodbye

This means that the command will create all the directories necessaries to fulfill your request, not returning any error in case that directory exists.

About rlidwka, Google has a very good memory for acronyms :). My search returned this for example: http://www.cs.cmu.edu/~help/afs/afs_acls.html

 Directory permissions

l (lookup)
    Allows one to list the contents of a directory. It does not allow the reading of files. 
i (insert)
    Allows one to create new files in a directory or copy new files to a directory. 
d (delete)
    Allows one to remove files and sub-directories from a directory. 
a (administer)
    Allows one to change a directory's ACL. The owner of a directory can always change the ACL of a directory that s/he owns, along with the ACLs of any subdirectories in that directory. 

File permissions

r (read)
    Allows one to read the contents of file in the directory. 
w (write)
    Allows one to modify the contents of files in a directory and use chmod on them. 
k (lock)
    Allows programs to lock files in a directory. 

Hence rlidwka means: All permissions on.

It's worth mentioning, as @KeithThompson pointed out in the comments, that not all Unix systems support ACL. So probably the rlidwka concept doesn't apply here.

Deleting multiple elements from a list

You can use remove, too.

delete_from_somelist = []
for i in [int(0), int(2)]:
     delete_from_somelist.append(somelist[i])
for j in delete_from_somelist:
     newlist = somelist.remove(j)

Redirect using AngularJS

It is hard to say without knowing your code. My best guess is that the onchange event is not firing when you change your textbox value from JavaScript code.

There are two ways for this to work; the first is to call onchange by yourself, and the second is to wait for the textbox to lose focus.

Check this question; same issue, different framework.

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

How to bind bootstrap popover on dynamic elements

Probably way too late but this is another option:

 $('body').popover({
    selector: '[rel=popover]',
    trigger: 'hover',
    html: true,
    content: function () {
        return $(this).parents('.row').first().find('.metaContainer').html();
    }
});

Removing legend on charts with chart.js v2

The options object can be added to the chart when the new Chart object is created.

var chart1 = new Chart(canvas, {
    type: "pie",
    data: data,
    options: {
         legend: {
            display: false
         },
         tooltips: {
            enabled: false
         }
    }
});

How to set time delay in javascript

For sync calls you can use the method below:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));

This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.


WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

Element is Clickable - it is Displayed and Enabled.

From WebDriver docs: Explicit and Implicit Waits

Read file As String

With files we know the size in advance, so just read it all at once!

String result;
File file = ...;

long length = file.length();
if (length < 1 || length > Integer.MAX_VALUE) {
    result = "";
    Log.w(TAG, "File is empty or huge: " + file);
} else {
    try (FileReader in = new FileReader(file)) {
        char[] content = new char[(int)length];

        int numRead = in.read(content);
        if (numRead != length) {
            Log.e(TAG, "Incomplete read of " + file + ". Read chars " + numRead + " of " + length);
        }
        result = new String(content, 0, numRead);
    }
    catch (Exception ex) {
        Log.e(TAG, "Failure reading " + this.file, ex);
        result = "";
    }
}

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

You can press I twice to interrupt the kernel.

This only works if you're in Command mode. If not already enabled, press Esc to enable it.

Starting Docker as Daemon on Ubuntu

There are multiple popular repositories offering docker packages for Ubuntu. The package docker.io is (most likely) from the Ubuntu repository. Another popular one is http://get.docker.io/ubuntu which offers a package lxc-docker (I am running the latter because it ships updates faster). Make sure only one package is installed. Not quite sure if removal of the packages cleans up properly. If sudo service docker restart still does not work, you may have to clean up manually in /etc/.

embedding image in html email

The other solution is attaching the image as attachment and then referencing it html code using cid.

HTML Code:

<html>
    <head>
    </head>
    <body>
        <img width=100 height=100 id="1" src="cid:Logo.jpg">
    </body>
</html>

C# Code:

EmailMessage email = new EmailMessage(service);
email.Subject = "Email with Image";
email.Body = new MessageBody(BodyType.HTML, html);
email.ToRecipients.Add("[email protected]");
string file = @"C:\Users\acv\Pictures\Logo.jpg";
email.Attachments.AddFileAttachment("Logo.jpg", file);
email.Attachments[0].IsInline = true;
email.Attachments[0].ContentId = "Logo.jpg";
email.SendAndSaveCopy();

error: strcpy was not declared in this scope

Observations:

  • #include <cstring> should introduce std::strcpy().
  • using namespace std; (as written in medico.h) introduces any identifiers from std:: into the global namespace.

Aside from using namespace std; being somewhat clumsy once the application grows larger (as it introduces one hell of a lot of identifiers into the global namespace), and that you should never use using in a header file (see below!), using namespace does not affect identifiers introduced after the statement.

(using namespace std is written in the header, which is included in medico.cpp, but #include <cstring> comes after that.)

My advice: Put the using namespace std; (if you insist on using it at all) into medico.cpp, after any includes, and use explicit std:: in medico.h.


strcmpi() is not a standard function at all; while being defined on Windows, you have to solve case-insensitive compares differently on Linux.

(On general terms, I would like to point to this answer with regards to "proper" string handling in C and C++ that takes Unicode into account, as every application should. Summary: The standard cannot handle these things correctly; do use ICU.)


warning: deprecated conversion from string constant to ‘char*’

A "string constant" is when you write a string literal (e.g. "Hello") in your code. Its type is const char[], i.e. array of constant characters (as you cannot change the characters). You can assign an array to a pointer, but assigning to char *, i.e. removing the const qualifier, generates the warning you are seeing.


OT clarification: using in a header file changes visibility of identifiers for anyone including that header, which is usually not what the user of your header file wants. For example, I could use std::string and a self-written ::string just perfectly in my code, unless I include your medico.h, because then the two classes will clash.

Don't use using in header files.

And even in implementation files, it can introduce lots of ambiguity. There is a case to be made to use explicit namespacing in implementation files as well.

How do I center an anchor element in CSS?

css cannot be directly applied for the alignment of the anchor tag. The css (text-align:center;) should be applied to the parent div/element for the alignment effect to take place on the anchor tag.

How to turn on front flash light programmatically in Android?

There's different ways to access Camera Flash in different Android versions. Few APIs stopped working in Lollipop and then it got changed again in Marshmallow. To overcome this, I have created a simple library that I have been using in few of my projects and it's giving good results. It's still incomplete, but you can try to check the code and find the missing pieces. Here's the link - NoobCameraFlash.

If you just want to integrate in your code, you can use gradle for that. Here's the instructions (Taken directly from the Readme) -

Step 1. Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:

allprojects {
        repositories {
            ...
            maven { url "https://jitpack.io" }
        }
}

Step 2. Add the dependency

dependencies {
        compile 'com.github.Abhi347:NoobCameraFlash:0.0.1'
  }

Usage

Initialize the NoobCameraManager singleton.

NoobCameraManager.getInstance().init(this);

You can optionally set the Log Level for debug logging. Logging uses LumberJack library. The default LogLevel is LogLevel.None

NoobCameraManager.getInstance().init(this, LogLevel.Verbose);

After that you just need to call the singleton to turn on or off the camera flash.

NoobCameraManager.getInstance().turnOnFlash();
NoobCameraManager.getInstance().turnOffFlash();

You have to take care of the runtime permissions to access Camera yourself, before initializing the NoobCameraManager. In version 0.1.2 or earlier we used to provide support for permissions directly from the library, but due to dependency on the Activity object, we have to remove it.

It's easy to toggle Flash too

if(NoobCameraManager.getInstance().isFlashOn()){
    NoobCameraManager.getInstance().turnOffFlash();
}else{
    NoobCameraManager.getInstance().turnOnFlash();
}

SSL peer shut down incorrectly in Java

You can set protocol versions in system property as :

overcome ssl handshake error

System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");

C# 4.0 optional out/ref arguments

ICYMI: Included on the new features for C# 7.0 enumerated here, "discards" is now allowed as out parameters in the form of a _, to let you ignore out parameters you don’t care about:

p.GetCoordinates(out var x, out _); // I only care about x

P.S. if you're also confused with the part "out var x", read the new feature about "Out Variables" on the link as well.

How to check if an integer is within a range of numbers in PHP?

$ranges = [
    1 => [
        'min_range' => 0.01,
        'max_range' => 199.99
    ],
    2 => [
        'min_range' => 200.00,
    ],
];

   foreach( $ranges as $value => $range ){
        if( filter_var( $cartTotal, FILTER_VALIDATE_FLOAT, [ 'options' => $range ] ) ){
            return $value;
        }
    }

Difference between two dates in MySQL

select 
unix_timestamp('2007-12-30 00:00:00') - 
unix_timestamp('2007-11-30 00:00:00');

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

In DefaultAppPool set NetworkService in the Identity property and in Sql Server add User Network Service and give it the appropiate permissions to your database, that's work very well for me, I've tested locally but I think this is the best configuration for connecting from any other computer in the network. when you set LocalSystem in the Identity in IIS that's work well and it is not necessary to create any other user in Sql Server but I think that will not work in a network environment.

How do I export an Android Studio project?

For Android Studio below 4.1:

From the Top menu Click File and then click Export to Zip File

For Android Studio 4.1 and above:

From the Top menu click File > Manage IDE Settings > Export to Zip File ()

Can I escape a double quote in a verbatim string literal?

There is a proposal open in GitHub for the C# language about having better support for raw string literals. One valid answer, is to encourage the C# team to add a new feature to the language (such as triple quote - like Python).

see https://github.com/dotnet/csharplang/discussions/89#discussioncomment-257343

increase font size of hyperlink text html

you can add class in anchor tag also like below

.a_class {font-size: 100px} 

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

If you set CURLOPT_RETURNTRANSFER to true or 1 then the return value from curl_exec will be the actual result from the successful operation. In other words it will not return TRUE on success. Although it will return FALSE on failure.

As described in the Return Values section of curl-exec PHP manual page: http://php.net/manual/function.curl-exec.php

You should enable the CURLOPT_FOLLOWLOCATION option for redirects but this would be a problem if your server is in safe_mode and/or open_basedir is in effect which can cause issues with curl as well.

How to position the Button exactly in CSS

I'd use absolute positioning:

#play_button {
    position:absolute;
transition: .5s ease;
    left: 202px;
    top: 198px;

}

What are the aspect ratios for all Android phone and tablet devices?

In case anyone wanted more of a visual reference:

aspect_ratio_visual_reference

Decimal approximations reference table:

+----------------------------------------------------------------------------+
¦       aspect ratio       ¦     decimal approx.    ¦     decimal approx.    ¦
¦ [long edge x short edge] ¦ [short edge/long edge] ¦ [long edge/short edge] ¦
¦--------------------------+------------------------+------------------------¦
¦         19.5 x 9         ¦        0.462...        ¦        2.167...        ¦
¦--------------------------+------------------------+------------------------¦
¦          19 x 9          ¦        0.474...        ¦         2.11...        ¦
¦--------------------------+------------------------+------------------------¦
¦        ~18.7 x 9         ¦        0.482...        ¦        2.074...        ¦
¦--------------------------+------------------------+------------------------¦    
¦         18.5 x 9         ¦        0.486...        ¦        2.056...        ¦
¦--------------------------+------------------------+------------------------¦
¦          18 x 9          ¦           0.5          ¦            2           ¦
¦--------------------------+------------------------+------------------------¦
¦          19 x 10         ¦        0.526...        ¦           1.9          ¦
¦--------------------------+------------------------+------------------------¦
¦          16 x 9          ¦         0.5625         ¦        1.778...        ¦
¦--------------------------+------------------------+------------------------¦
¦           5 x 3          ¦           0.6          ¦        1.667...        ¦
¦--------------------------+------------------------+------------------------¦
¦          16 x 10         ¦          0.625         ¦           1.6          ¦
¦--------------------------+------------------------+------------------------¦
¦           3 x 2          ¦        0.667...        ¦           1.5          ¦
¦--------------------------+------------------------+------------------------¦
¦           4 x 3          ¦          0.75          ¦        1.333...        ¦
+----------------------------------------------------------------------------+

Changelog:

  • May 2018: Added 56x27 === ~18.7x9 (Huawei P20), 19x9 (Nokia X6 2018) and 19.5x9 (LG G7 ThinQ)
  • May 2017: Added 19x10 (Essential Phone)
  • March 2017: Added 18.5x9 (Samsung Galaxy S8) and 18x9 (LG G6)

how to convert long date value to mm/dd/yyyy format

Try this example

 String[] formats = new String[] {
   "yyyy-MM-dd",
   "yyyy-MM-dd HH:mm",
   "yyyy-MM-dd HH:mmZ",
   "yyyy-MM-dd HH:mm:ss.SSSZ",
   "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
 };
 for (String format : formats) {
   SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
 }

and read this http://developer.android.com/reference/java/text/SimpleDateFormat.html

Getting current device language in iOS?

Simple Swift 3 function:

@discardableResult
func getLanguageISO() -> String {
    let locale = Locale.current
    guard let languageCode = locale.languageCode,
          let regionCode = locale.regionCode else {
        return "de_DE"
    }
    return languageCode + "_" + regionCode
}

Add CSS or JavaScript files to layout head from views or partial views

Update: basic example available at https://github.com/speier/mvcassetshelper

We are using the following implementation to add JS and CSS files into the layout page.

View or PartialView:

@{
    Html.Assets().Styles.Add("/Dashboard/Content/Dashboard.css");
    Html.Assets().Scripts.Add("/Dashboard/Scripts/Dashboard.js");
}

Layout page:

<head>
    @Html.Assets().Styles.Render()
</head>

<body>
    ...
    @Html.Assets().Scripts.Render()
</body>

HtmlHelper extension:

public static class HtmlHelperExtensions
{
    public static AssetsHelper Assets(this HtmlHelper htmlHelper)
    {
        return AssetsHelper.GetInstance(htmlHelper);
    }    
}

public class AssetsHelper 
{
    public static AssetsHelper GetInstance(HtmlHelper htmlHelper)
    {
        var instanceKey = "AssetsHelperInstance";

        var context = htmlHelper.ViewContext.HttpContext;
        if (context == null) return null;

        var assetsHelper = (AssetsHelper)context.Items[instanceKey];

        if (assetsHelper == null)
            context.Items.Add(instanceKey, assetsHelper = new AssetsHelper());

        return assetsHelper;
    }

    public ItemRegistrar Styles { get; private set; }
    public ItemRegistrar Scripts { get; private set; }

    public AssetsHelper()
    {
        Styles = new ItemRegistrar(ItemRegistrarFormatters.StyleFormat);
        Scripts = new ItemRegistrar(ItemRegistrarFormatters.ScriptFormat);
    }
}

public class ItemRegistrar
{
    private readonly string _format;
    private readonly IList<string> _items;

    public ItemRegistrar(string format)
    {
        _format = format;
        _items = new List<string>();
    }

    public ItemRegistrar Add(string url)
    {
        if (!_items.Contains(url))
            _items.Add(url);

        return this;
    }

    public IHtmlString Render()
    {
        var sb = new StringBuilder();

        foreach (var item in _items)
        {
            var fmt = string.Format(_format, item);
            sb.AppendLine(fmt);
        }

        return new HtmlString(sb.ToString());
    }
}

public class ItemRegistrarFormatters
{
    public const string StyleFormat = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
    public const string ScriptFormat = "<script src=\"{0}\" type=\"text/javascript\"></script>";
}

How to run a PowerShell script

I've had the same problem, and I tried and tried... Finally I used:

powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'"

And put this line in a batch-file, and this works.

Mysql adding user for remote access

for what DB is the user? look at this example

mysql> create database databasename;
Query OK, 1 row affected (0.00 sec)
mysql> grant all on databasename.* to cmsuser@localhost identified by 'password';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

so to return to you question the "%" operator means all computers in your network.

like aspesa shows I'm also sure that you have to create or update a user. look for all your mysql users:

SELECT user,password,host FROM user;

as soon as you got your user set up you should be able to connect like this:

mysql -h localhost -u gmeier -p

hope it helps

How do I generate a random int number?

This is the class I use. Works like RandomNumber.GenerateRandom(1, 666)

internal static class RandomNumber
{
    private static Random r = new Random();
    private static object l = new object();
    private static Random globalRandom = new Random();
    [ThreadStatic]
    private static Random localRandom;
    public static int GenerateNewRandom(int min, int max)
    {
        return new Random().Next(min, max);
    }
    public static int GenerateLockedRandom(int min, int max)
    {
        int result;
        lock (RandomNumber.l)
        {
            result = RandomNumber.r.Next(min, max);
        }
        return result;
    }
    public static int GenerateRandom(int min, int max)
    {
        Random random = RandomNumber.localRandom;
        if (random == null)
        {
            int seed;
            lock (RandomNumber.globalRandom)
            {
                seed = RandomNumber.globalRandom.Next();
            }
            random = (RandomNumber.localRandom = new Random(seed));
        }
        return random.Next(min, max);
    }
}

What is the significance of url-pattern in web.xml and how to configure servlet?

Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

First specification of url-pattern a web.xml file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern> as follows:

http://server.com/server/status/synopsis               = Matches
http://server.com/server/status/complete?date=today    = Matches
http://server.com/server/status                        = Matches
http://server.com/server/server1/status                = Does not match

Second specification of url-pattern A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern> as follows:

 http://server.com/server/US/Oregon/Portland.map    = Matches
 http://server.com/server/US/server/Seattle.map     = Matches
 http://server.com/server/Paris.France.map          = Matches
 http://server.com/server/US/Oregon/Portland.MAP    = Does not match, the extension is uppercase
 http://example.com/examples/interface/description/mail.mapi  =Does not match, the extension is mapi rather than map`

Third specification of url-mapping,A mapping that contains the pattern <url-pattern>/</url-pattern> matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.

The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.

The servlet-mapping element below maps the server servlet instance to the default mapping.

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

For the context that contains this element, any request that is not handled by another mapping is forwarded to the server servlet.

And Most importantly we should Know about Rule for URL path mapping

  1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
  2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
  3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
  4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

Reference URL Pattern

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

Multiple bluetooth connection

I was searching a way to connect 4 devices with bluetooth and I found the following.

http://groups.google.com/group/android-developers/browse_thread/thread/69d7810f6ef9bb7d

I'm not sure that this is what you want.

But in order to connect more than 2 devices using bluetooth you have to create a different UUID for each device you want to connect.

Follow the link to see code examples and a better explanation.

How to use a client certificate to authenticate and authorize in a Web API

Looking at the source code I also think there must be some issue with the private key.

What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.

If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.

(see source code from class SecureChannnel, method EnsurePrivateKey)

So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.

You can activate Network Tracing to try to debug this. It will give you output like this:

  • Trying to find a matching certificate in the certificate store
  • Cannot find the certificate in either the LocalMachine store or the CurrentUser store.

Visualizing decision tree in scikit-learn

You can copy the contents of the export_graphviz file and you can paste the same in the webgraphviz.com site.

You can check out the article on How to visualize the decision tree in Python with graphviz for more information.

Vertical divider CSS

.headerDivider {
     border-left:1px solid #38546d; 
     border-right:1px solid #16222c; 
     height:80px;
     position:absolute;
     right:249px;
     top:10px; 
}

<div class="headerDivider"></div>

"Debug certificate expired" error in Eclipse Android plugins

It's a pain to have to delete all your development .apk files, because the new certificate doesn't match so you can't upgrade them in all your AVDs. You have to get another development MAP-API key as well. There's another solution.

You can create your own debug certificate in debug.keystore with whatever expiration you want. Do this in the .android folder under your HOME directory:

keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -validity 14000

keytool.exe can be found in the JDK bin folder (e.g. C:\Program Files\Java\jdk1.6.0_31\bin\ on Windows).

ADT sets the first and last name on the certificate as "Android Debug", the organizational unit as "Android" and the two-letter country code as "US". You can leave the organization, city, and state values as "Unknown". This example uses a validity of 14000 days. You can use whatever value you like.

How to get URL of current page in PHP

The other answers are correct. However, a quick note: if you're looking to grab the stuff after the ? in a URI, you should use the $_GET[] array.

Java: How to convert String[] to List or Set

If you really want to use a set:

String[] strArray = {"foo", "foo", "bar"};  
Set<String> mySet = new HashSet<String>(Arrays.asList(strArray));
System.out.println(mySet);

output:

[foo, bar]

Get environment variable value in Dockerfile

Load environment variables from a file you create at runtime.

export MYVAR="my_var_outside"
cat > build/env.sh <<EOF
MYVAR=${MYVAR}
EOF

... then in the Dockerfile

ADD build /build
RUN /build/test.sh

where test.sh loads MYVAR from env.sh

#!/bin/bash
. /build/env.sh
echo $MYVAR > /tmp/testfile

How can I use Html.Action?

first, create a class to hold your parameters:

public class PkRk {
    public int pk { get; set; }
    public int rk { get; set; }
}

then, use the Html.Action passing the parameters:

Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })

and use in Controller:

public ActionResult PkRkAction(PkRk pkrk) {
    return PartialView(pkrk);
}

MySQL Trigger: Delete From Table AFTER DELETE

I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)

Try this as the new trigger:

CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
    WHERE patron_info.pid = old.id;
END

Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

sed s/^M//g file1.txt > file2.txt

where ^M is typed by simultaneously pressing the 3 keys, ctrl + v + m

How to write a large buffer into a binary file in C++, fast?

This did the job (in the year 2012):

#include <stdio.h>
const unsigned long long size = 8ULL*1024ULL*1024ULL;
unsigned long long a[size];

int main()
{
    FILE* pFile;
    pFile = fopen("file.binary", "wb");
    for (unsigned long long j = 0; j < 1024; ++j){
        //Some calculations to fill a[]
        fwrite(a, 1, size*sizeof(unsigned long long), pFile);
    }
    fclose(pFile);
    return 0;
}

I just timed 8GB in 36sec, which is about 220MB/s and I think that maxes out my SSD. Also worth to note, the code in the question used one core 100%, whereas this code only uses 2-5%.

Thanks a lot to everyone.

Update: 5 years have passed it's 2017 now. Compilers, hardware, libraries and my requirements have changed. That's why I made some changes to the code and did some new measurements.

First up the code:

#include <fstream>
#include <chrono>
#include <vector>
#include <cstdint>
#include <numeric>
#include <random>
#include <algorithm>
#include <iostream>
#include <cassert>

std::vector<uint64_t> GenerateData(std::size_t bytes)
{
    assert(bytes % sizeof(uint64_t) == 0);
    std::vector<uint64_t> data(bytes / sizeof(uint64_t));
    std::iota(data.begin(), data.end(), 0);
    std::shuffle(data.begin(), data.end(), std::mt19937{ std::random_device{}() });
    return data;
}

long long option_1(std::size_t bytes)
{
    std::vector<uint64_t> data = GenerateData(bytes);

    auto startTime = std::chrono::high_resolution_clock::now();
    auto myfile = std::fstream("file.binary", std::ios::out | std::ios::binary);
    myfile.write((char*)&data[0], bytes);
    myfile.close();
    auto endTime = std::chrono::high_resolution_clock::now();

    return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
}

long long option_2(std::size_t bytes)
{
    std::vector<uint64_t> data = GenerateData(bytes);

    auto startTime = std::chrono::high_resolution_clock::now();
    FILE* file = fopen("file.binary", "wb");
    fwrite(&data[0], 1, bytes, file);
    fclose(file);
    auto endTime = std::chrono::high_resolution_clock::now();

    return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
}

long long option_3(std::size_t bytes)
{
    std::vector<uint64_t> data = GenerateData(bytes);

    std::ios_base::sync_with_stdio(false);
    auto startTime = std::chrono::high_resolution_clock::now();
    auto myfile = std::fstream("file.binary", std::ios::out | std::ios::binary);
    myfile.write((char*)&data[0], bytes);
    myfile.close();
    auto endTime = std::chrono::high_resolution_clock::now();

    return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
}

int main()
{
    const std::size_t kB = 1024;
    const std::size_t MB = 1024 * kB;
    const std::size_t GB = 1024 * MB;

    for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << "option1, " << size / MB << "MB: " << option_1(size) << "ms" << std::endl;
    for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << "option2, " << size / MB << "MB: " << option_2(size) << "ms" << std::endl;
    for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << "option3, " << size / MB << "MB: " << option_3(size) << "ms" << std::endl;

    return 0;
}

This code compiles with Visual Studio 2017 and g++ 7.2.0 (a new requirements). I ran the code with two setups:

  • Laptop, Core i7, SSD, Ubuntu 16.04, g++ Version 7.2.0 with -std=c++11 -march=native -O3
  • Desktop, Core i7, SSD, Windows 10, Visual Studio 2017 Version 15.3.1 with /Ox /Ob2 /Oi /Ot /GT /GL /Gy

Which gave the following measurements (after ditching the values for 1MB, because they were obvious outliers): enter image description here enter image description here Both times option1 and option3 max out my SSD. I didn't expect this to see, because option2 used to be the fastest code on my old machine back then.

TL;DR: My measurements indicate to use std::fstream over FILE.

How can I capture the right-click event in JavaScript?

I think that you are looking for something like this:

   function rightclick() {
    var rightclick;
    var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert(rightclick); // true or false, you can trap right click here by if comparison
}

(http://www.quirksmode.org/js/events_properties.html)

And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >

How do I get the old value of a changed cell in Excel VBA?

You can use an event on the cell change to fire a macro that does the following:

vNew = Range("cellChanged").value
Application.EnableEvents = False
Application.Undo
vOld = Range("cellChanged").value
Range("cellChanged").value = vNew
Application.EnableEvents = True 

Tab space instead of multiple non-breaking spaces ("nbsp")?

&emsp; is the answer.

However, they won't be as functional as you might expect if you are used to using horizontal tabulations in word-processors e.g. Word, Wordperfect, Open Office, Wordworth, etc. They are fixed width, and they cannot be customised.

CSS gives you far greater control and provides an alternative until the W3C provide an official solution.

Example:

padding-left:4em 

..or..

margin-left:4em 

..as appropriate

It depends on which character set you want to use.

You could set up some tab tags and use them similar to how you would use h tags.

<style>
    tab1 { padding-left: 4em; }
    tab2 { padding-left: 8em; }
    tab3 { padding-left: 12em; }
    tab4 { padding-left: 16em; }
    tab5 { padding-left: 20em; }
    tab6 { padding-left: 24em; }
    tab7 { padding-left: 28em; }
    tab8 { padding-left: 32em; }
    tab9 { padding-left: 36em; }
    tab10 { padding-left: 40em; }
    tab11 { padding-left: 44em; }
    tab12 { padding-left: 48em; }
    tab13 { padding-left: 52em; }
    tab14 { padding-left: 56em; }
    tab15 { padding-left: 60em; }
    tab16 { padding-left: 64em; }
</style>

...and use them like so:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
_x000D_
<html>_x000D_
    <head>_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
        <title>Tabulation example</title>_x000D_
_x000D_
        <style type="text/css">_x000D_
            dummydeclaration { padding-left: 4em; } /* Firefox ignores first declaration for some reason */_x000D_
            tab1 { padding-left: 4em; }_x000D_
            tab2 { padding-left: 8em; }_x000D_
            tab3 { padding-left: 12em; }_x000D_
            tab4 { padding-left: 16em; }_x000D_
            tab5 { padding-left: 20em; }_x000D_
            tab6 { padding-left: 24em; }_x000D_
            tab7 { padding-left: 28em; }_x000D_
            tab8 { padding-left: 32em; }_x000D_
            tab9 { padding-left: 36em; }_x000D_
            tab10 { padding-left: 40em; }_x000D_
            tab11 { padding-left: 44em; }_x000D_
            tab12 { padding-left: 48em; }_x000D_
            tab13 { padding-left: 52em; }_x000D_
            tab14 { padding-left: 56em; }_x000D_
            tab15 { padding-left: 60em; }_x000D_
            tab16 { padding-left: 64em; }_x000D_
_x000D_
        </style>_x000D_
_x000D_
    </head>_x000D_
_x000D_
    <body>_x000D_
        <p>Non tabulated text</p>_x000D_
_x000D_
        <p><tab1>Tabulated text</tab1></p>_x000D_
        <p><tab2>Tabulated text</tab2></p>_x000D_
        <p><tab3>Tabulated text</tab3></p>_x000D_
        <p><tab3>Tabulated text</tab3></p>_x000D_
        <p><tab2>Tabulated text</tab2></p>_x000D_
        <p><tab3>Tabulated text</tab3></p>_x000D_
        <p><tab4>Tabulated text</tab4></p>_x000D_
        <p><tab4>Tabulated text</tab4></p>_x000D_
        <p>Non tabulated text</p>_x000D_
        <p><tab3>Tabulated text</tab3></p>_x000D_
        <p><tab4>Tabulated text</tab4></p>_x000D_
        <p><tab4>Tabulated text</tab4></p>_x000D_
        <p><tab1>Tabulated text</tab1></p>_x000D_
        <p><tab2>Tabulated text</tab2></p>_x000D_
_x000D_
    </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Run the snippet above to see a visual example.

Extra discussion

There are no horizontal tabulation entities defined in ISO-8859-1 HTML, however there are some other white-space characters available than the usual &nbsp, for example; &thinsp;, &ensp; and the aforementioned &emsp;.

It's also worth mentioning that in ASCII and Unicode, &#09; is a horizontal tabulation.

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

I also had the error error/constitute.c/ReadImage/453 when trying to convert an eps to a gif with image magick. I tried the solution proposed by sNICkerssss but still had errors (though different from the first one)e error/constitute.c/ReadImage/412 What solved the problem was to put read to other entries

 <policy domain="coder" rights="read" pattern="PS" />
 <policy domain="coder" rights="read" pattern="EPS" />
 <policy domain="coder" rights="read" pattern="PDF" />
 <policy domain="coder" rights="read" pattern="XPS" />
 <policy domain="coder" rights="read|write" pattern="LABEL" />

vertical alignment of text element in SVG

According to SVG spec, alignment-baseline only applies to <tspan>, <textPath>, <tref> and <altGlyph>. My understanding is that it is used to offset those from the <text> object above them. I think what you are looking for is dominant-baseline.

Possible values of dominant-baseline are:

auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge | inherit

Check the W3C recommendation for the dominant-baseline property for more information about each possible value.

Disable hover effects on mobile browsers

I really wanted a pure css solution to this myself, since sprinkling a weighty javascript solution around all of my views seemed like an unpleasant option. Finally found the @media.hover query, which can detect "whether the primary input mechanism allows the user to hover over elements." This avoids touch devices where "hovering" is more of an emulated action than a direct capability of the input device.

So for example, if I have a link:

<a href="/" class="link">Home</a>

Then I can safely style it to only :hover when the device easily supports it with this css:

@media (hover: hover) {
  .link:hover { /* hover styles */ }
}

While most modern browsers support interaction media feature queries, some popular browsers such as IE and Firefox do not. In my case this works fine, since I only intended to support Chrome on desktop and Chrome and Safari on mobile.

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

One trick you can use to increase the number of concurrent connections is to host your images from a different sub domain. These will be treated as separate requests, each domain is what will be limited to the concurrent maximum.

IE6, IE7 - have a limit of two. IE8 is 6 if you have a broadband - 2 (if it's a dial up).

Create Pandas DataFrame from a string

Split Method

data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)

Given a URL to a text file, what is the simplest way to read the contents of the text file?

For me, none of the above responses worked straight ahead. Instead, I had to do the following (Python 3):

from urllib.request import urlopen

data = urlopen("[your url goes here]").read().decode('utf-8')

# Do what you need to do with the data.

DISTINCT clause with WHERE

Query:

Select *, (Select distinct email) from Table1

Volatile vs Static in Java

volatile variable value access will be direct from main memory. It should be used only in multi-threading environment. static variable will be loaded one time. If its used in single thread environment, even if the copy of the variable will be updated and there will be no harm accessing it as there is only one thread.

Now if static variable is used in multi-threading environment then there will be issues if one expects desired result from it. As each thread has their own copy then any increment or decrement on static variable from one thread may not reflect in another thread.

if one expects desired results from static variable then use volatile with static in multi-threading then everything will be resolved.