Programs & Examples On #Javax.swing.timer

java: run a function after a specific number of seconds

Your original question mentions the "Swing Timer". If in fact your question is related to SWing, then you should be using the Swing Timer and NOT the util.Timer.

Read the section from the Swing tutorial on "How to Use Timers" for more information.

Set multiple system properties Java command line

There's nothing on the Documentation that mentions about anything like that.

Here's a quote:

-Dproperty=value Set a system property value. If value is a string that contains spaces, you must enclose the string in double quotes:

java -Dfoo="some string" SomeClass

VBA collection: list of keys

You can easily iterate you collection. The example below is for the special Access TempVars collection, but works with any regular collection.

Dim tv As Long
For tv = 0 To TempVars.Count - 1
    Debug.Print TempVars(tv).Name, TempVars(tv).Value
Next tv

how to redirect to external url from c# controller

Use the Controller's Redirect() method.

public ActionResult YourAction()
{
    // ...
    return Redirect("http://www.example.com");
}

Update

You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript.

public ActionResult YourAction()
{
    // ...
    return Json(new {url = "http://www.example.com"});
}

$.post("@Url.Action("YourAction")", function(data) {
    window.location = data.url;
});

add onclick function to a submit button

html:

<form method="post" name="form1" id="form1">    
    <input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" />
</form>

Javascript: to submit the form using javascript

function eatFood() {
document.getElementById('form1').submit();
}

to show onclick message

function eatFood() {
alert('Form has been submitted');
}

error while loading shared libraries: libncurses.so.5:

Mixaz's above answer worked for me. However I had issues installing the package because of PGP check failures. Installing it by skipping the signature worked, you could try this :

yaourt --m-arg "--skipchecksums --skippgpcheck" -Sb <your-package>

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

How to obtain the start time and end time of a day?

I know it's a bit late, but in case of Java 8, if you are using OffsetDateTime (which offers a lot of advantages, such as TimeZone, Nanoseconds, etc.), you can use the following code:

OffsetDateTime reallyEndOfDay = someDay.withHour(23).withMinute(59).withSecond(59).withNano(999999999);
// output: 2019-01-10T23:59:59.999999999Z

Error in launching AVD with AMD processor

For those who are using Android Studio based on Jetbrains:

  1. Goto Tools > Android > SDK Manager

  2. Under Extras --> select the checkbox Intel x86 Emulator Accelorator

For those who are unable to use Nexus AVD can also try using Generic AVD.

  1. Goto Tools > Android > AVD Manager

Then create a new Genreic AVD with something like QVGA and use for your app. This AVD does not use hardware acceleration.

Get all validation errors from Angular 2 FormGroup

I met the same problem and for finding all validation errors and displaying them, I wrote next method:

getFormValidationErrors() {
  Object.keys(this.productForm.controls).forEach(key => {

  const controlErrors: ValidationErrors = this.productForm.get(key).errors;
  if (controlErrors != null) {
        Object.keys(controlErrors).forEach(keyError => {
          console.log('Key control: ' + key + ', keyError: ' + keyError + ', err value: ', controlErrors[keyError]);
        });
      }
    });
  }

Form name productForm should be changed to yours.

It works in next way: we get all our controls from form in format {[p: string]: AbstractControl} and iterate by each error key, for get details of error. It skips null error values.

It also can be changed for displaying validation errors on the template view, just replace console.log(..) to what you need.

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

for sbt, use below versions

val glassfishEl = "org.glassfish" % "javax.el" % "3.0.1-b09"

val hibernateValidator = "org.hibernate.validator" % "hibernate-validator" % "6.0.17.Final"

val hibernateValidatorCdi = "org.hibernate.validator" % "hibernate-validator-cdi" % "6.0.17.Final"

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

You could disable the warnings temporarily in places where they appear by using

#pragma warning(push)
#pragma warning(disable: warning-code) //4996 for _CRT_SECURE_NO_WARNINGS equivalent
// deprecated code here
#pragma warning(pop)

so you don't disable all warnings, which can be harmful at times.

How do you convert a JavaScript date to UTC?

This is what I have done in the past:

var utcDateString = new Date(new Date().toUTCString()).toISOString();

How to find whether a number belongs to a particular range in Python?

if num in range(min, max):
  """do stuff..."""
else:
  """do other stuff..."""

Rename Excel Sheet with VBA Macro

This should do it:

WS.Name = WS.Name & "_v1"

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

hadoop copy a local file system folder to HDFS

You could try:

hadoop fs -put /path/in/linux /hdfs/path

or even

hadoop fs -copyFromLocal /path/in/linux /hdfs/path

By default both put and copyFromLocal would upload directories recursively to HDFS.

wkhtmltopdf: cannot connect to X server

wkhtmltopdf > 0.11 doesn't have this X-server issue.
So installing 0.12.2.1 on a linux server.

  1. At first install xvfb server:

    sudo apt-get install xvfb
    
  2. Get needed version of wkhtmltopdf from http://wkhtmltopdf.org/downloads.html

  3. Install wkhtmltopdf:

    sudo dpkg -i wkhtmltox-0.12.2.1_linux-trusty-amd64.deb
    

    or install with wget

    URL='http://download.gna.org/wkhtmltopdf/0.12/0.12.2.1/wkhtmltox-0.12.2.1_linux-trusty-amd64.deb'; FILE=`mktemp`; wget "$URL" -qO $FILE && sudo dpkg -i $FILE; rm $FILE
    
  4. Install dependency (if needed):

    sudo apt-get -f install
    
  5. Create symblic link in /usr/local/bin/:

    echo 'exec xvfb-run -a -s "-screen 0 640x480x16" wkhtmltopdf "$@"' | sudo tee /usr/local/bin/wkhtmltopdf.sh >/dev/null
    sudo chmod a+x /usr/local/bin/wkhtmltopdf.sh
    
  6. Now try below and it should work,

    /usr/local/bin/wkhtmltopdf http://www.google.com test.pdf
    

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

An expansion for those who did a bit of fiddling around like I did.

The following work (from W3):

<input type="text" autofocus />
<input type="text" autofocus="" />
<input type="text" autofocus="autofocus" />
<input type="text" autofocus="AuToFoCuS" />

It is important to note that this does not work in CSS though. I.e. you can't use:

.first-input {
    autofocus:"autofocus"
}

At least it didn't work for me...

Openssl is not recognized as an internal or external command

use this worked for me. please change your Path

C:\Program Files\Java\jre7\bin keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Ace.android\debug.keystore" | "C:\openssl\bin

\openssl.exe" sha1 -binary | "C:\openssl\bin\openssl.exe" base64

How to add new column to an dataframe (to the front not end)?

Add column "a"

> df["a"] <- 0
> df
  b c d a
1 1 2 3 0
2 1 2 3 0
3 1 2 3 0

Sort by column using colum name

> df <- df[c('a', 'b', 'c', 'd')]
> df
  a b c d
1 0 1 2 3
2 0 1 2 3
3 0 1 2 3

Or sort by column using index

> df <- df[colnames(df)[c(4,1:3)]]
> df
  a b c d
1 0 1 2 3
2 0 1 2 3
3 0 1 2 3

Valid characters in a Java class name

Identifiers are used for class names, method names, and variable names. An identifiermay be any descriptive sequence of uppercase and lowercase letters, numbers, or theunderscore and dollar-sign characters. They must not begin with a number, lest they beconfused with a numeric literal. Again, Java is case-sensitive, so VALUE is a differentidentifier than Value. Some examples of valid identifiers are:

AvgTemp ,count a4 ,$test ,this_is_ok

Invalid variable names include:

2count, high-temp, Not/ok

Is it possible to force row level locking in SQL Server?

You can't really force the optimizer to do anything, but you can guide it.

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

See - Controlling SQL Server with Locking and Hints

Split string into list in jinja?

You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.

For your purpose, it would make most sense to define a custom filter, so you could for example do the following:

The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{  splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{  splitpart(1) }}

The filter function could then look like this:

def splitpart (value, index, char = ','):
    return value.split(char)[index]

An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.

How does data binding work in AngularJS?

Here is an example of data binding with AngularJS, using an input field. I will explain later

HTML Code

<div ng-app="myApp" ng-controller="myCtrl" class="formInput">
     <input type="text" ng-model="watchInput" Placeholder="type something"/>
     <p>{{watchInput}}</p> 
</div>

AngularJS Code

myApp = angular.module ("myApp", []);
myApp.controller("myCtrl", ["$scope", function($scope){
  //Your Controller code goes here
}]);

As you can see in the example above, AngularJS uses ng-model to listen and watch what happens on HTML elements, especially on input fields. When something happens, do something. In our case, ng-model is bind to our view, using the mustache notation {{}}. Whatever is typed inside the input field is displayed on the screen instantly. And that's the beauty of data binding, using AngularJS in its simplest form.

Hope this helps.

See a working example here on Codepen

How to install pip for Python 3 on Mac OS X?

On MacOS 10.12

download pip: pip as get-pip.py

download python3: python3

  1. install python3
  2. open terminal: python3 get-pip.py
  3. pip3 is available

Why compile Python code?

It's compiled to bytecode which can be used much, much, much faster.

The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.

Important addition by Ben Blank:

It's worth noting that while running a compiled script has a faster startup time (as it doesn't need to be compiled), it doesn't run any faster.

Using jquery to delete all elements with a given id

.remove() should remove all of them. I think the problem is that you're using an ID. There's only supposed to be one HTML element with a particular ID on the page, so jQuery is optimizing and not searching for them all. Use a class instead.

Calculating arithmetic mean (one type of average) in Python

I am not aware of anything in the standard library. However, you could use something like:

def mean(numbers):
    return float(sum(numbers)) / max(len(numbers), 1)

>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0

In numpy, there's numpy.mean().

php $_GET and undefined index

Get into the habit of checking if a variable is available with isset, e.g.

if (isset($_GET['s']))
{
     //do stuff that requires 's'
}
else
{
     //do stuff that doesn't need 's'
}

You could disable notice reporting, but dealing them is good hygiene, and can allow you to spot problems you might otherwise miss.

CSS Display an Image Resized and Cropped

<div class="crop">
    <img src="image.jpg"/>
</div>
.crop {
  width: 200px;
  height: 150px;
  overflow: hidden;
}
.crop img {
  width: 100%;
  /*Here you can use margins for accurate positioning of cropped image*/
}

What is the default scope of a method in Java?

The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.

More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html

How to search a string in multiple files and return the names of files in Powershell?

This is how I would do it, you don't need get-content:

ls -r | Select-String dummy | select line,path

or

ls -r | Select-String dummy | fl *

To see what the different properties are...

This is faster. The second argument is -filter:

ls -r . *.bat | select-string netsh

ls -r . -filter *.bat | select-string netsh

Listing all extras of an Intent

This is how I define utility method to dump all extras of an Intent.

import java.util.Iterator;
import java.util.Set;
import android.os.Bundle;


public static void dumpIntent(Intent i){

    Bundle bundle = i.getExtras();
    if (bundle != null) {
        Set<String> keys = bundle.keySet();
        Iterator<String> it = keys.iterator();
        Log.e(LOG_TAG,"Dumping Intent start");
        while (it.hasNext()) {
            String key = it.next();
            Log.e(LOG_TAG,"[" + key + "=" + bundle.get(key)+"]");
        }
        Log.e(LOG_TAG,"Dumping Intent end");
    }
}

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

Pillow is new version

PIL-1.1.7.win-amd64-py2.x installers are available at

http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil

How to refresh activity after changing language (Locale) inside application

This approach will work on all API level device.

  1. Use Base Activity for attachBaseContext to set the locale language and extend this activity for all activities

    open class  BaseAppCompactActivity() : AppCompatActivity() {
    
        override fun attachBaseContext(newBase: Context) {
            super.attachBaseContext(LocaleHelper.onAttach(newBase))    
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)           
        }
    }
    
  2. Use Application attachBaseContext and onConfigurationChanged to set the locale language

    public class MyApplication extends Application {
        private static MyApplication application;
    
        @Override
        public void onCreate() {
            super.onCreate();
        }
    
        public static MyApplication getApplication() {
            return application;
        }
    
        /**
         * overide to change local sothat language can be chnaged from android device  nogaut and above
         */
        @Override
        protected void attachBaseContext(Context base) {
            super.attachBaseContext(LocaleHelper.INSTANCE.onAttach(base));
        }
    
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            setLanguageFromNewConfig(newConfig);
            super.onConfigurationChanged(newConfig);
        }
    
        /*** also handle chnage  language if  device language chnaged **/
        private void setLanguageFromNewConfig(Configuration newConfig){
            Prefs.putSaveLocaleLanguage(this,  selectedLocaleLanguage );
            LocaleHelper.INSTANCE.onAttach(this);
        }
    
  3. Use Locale Helper for handling language changes, this approach work on all device

    object LocaleHelper {
        private var defaultLanguage  :String = KycUtility.KYC_LANGUAGE.ENGLISH.languageCode
    
        fun onAttach(context: Context, defaultLanguage: String): Context {
            return setLocale(context, defaultLanguage)
        }
    
    
    
        fun setLocale(context: Context, language: String): Context {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                updateResources(context, language)
            } else updateResourcesLegacy(context, language)
    
        }
    
    
        @TargetApi(Build.VERSION_CODES.N)
        private fun updateResources(context: Context, language: String): Context {
            val locale = Locale(language)
            Locale.setDefault(locale)
    
            val configuration = context.getResources().getConfiguration()
            configuration.setLocale(locale)
            configuration.setLayoutDirection(locale)
    
            return context.createConfigurationContext(configuration)
        }
    
        private fun updateResourcesLegacy(context: Context, language: String): Context {
            val locale = Locale(language)
            Locale.setDefault(locale)
    
            val resources = context.getResources()
    
            val configuration = resources.getConfiguration()
            configuration.locale = locale
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                configuration.setLayoutDirection(locale)
            }
            resources.updateConfiguration(configuration, resources.getDisplayMetrics())
            return context
        }
    }
    

Calling a php function by onclick event

The onClick attribute of html tags only takes Javascript but not PHP code. However, you can easily call a PHP function from within the Javascript code by using the JS document.write() function - effectively calling the PHP function by "writing" its call to the browser window: Eg.

onclick="document.write('<?php //call a PHP function here ?>');"

Your example:

    <?php
          function hello(){
              echo "Hello";
          }
    ?>

<input type="button" name="Release" onclick="document.write('<?php hello() ?>');" value="Click to Release">

Changing a specific column name in pandas DataFrame

If you know which column # it is (first / second / nth) then this solution posted on a similar question works regardless of whether it is named or unnamed, and in one line: https://stackoverflow.com/a/26336314/4355695

df.rename(columns = {list(df)[1]:'new_name'}, inplace=True)
# 1 is for second column (0,1,2..)

time data does not match format

I had a similar error -

time data '01-07-2020' does not match format '%d%m%Y' (match)

I didn't know that I have to use a hyphen in the format parameter. This worked for me -

df['Date'] = pd.to_datetime(df['Date'], format='%d-%m-%Y')

Salt and hash a password in Python

passlib seems to be useful if you need to use hashes stored by an existing system. If you have control of the format, use a modern hash like bcrypt or scrypt. At this time, bcrypt seems to be much easier to use from python.

passlib supports bcrypt, and it recommends installing py-bcrypt as a backend: http://pythonhosted.org/passlib/lib/passlib.hash.bcrypt.html

You could also use py-bcrypt directly if you don't want to install passlib. The readme has examples of basic use.

see also: How to use scrypt to generate hash for password and salt in Python

Split string to equal length substrings in Java

A StringBuilder version:

public static List<String> getChunks(String s, int chunkSize)
{
 List<String> chunks = new ArrayList<>();
 StringBuilder sb = new StringBuilder(s);

while(!(sb.length() ==0)) 
{           
   chunks.add(sb.substring(0, chunkSize));
   sb.delete(0, chunkSize);

}
return chunks;

}

How do I create a Linked List Data Structure in Java?

//slightly improved code without using collection framework

package com.test;

public class TestClass {

    private static Link last;
    private static Link first;

    public static void main(String[] args) {

        //Inserting
        for(int i=0;i<5;i++){
            Link.insert(i+5);
        }
        Link.printList();

        //Deleting
        Link.deletefromFirst();
        Link.printList();
    }


    protected  static class Link {
        private int data;
        private Link nextlink;

        public Link(int d1) {
            this.data = d1;
        }

        public static void insert(int d1) {
            Link a = new Link(d1);
            a.nextlink = null;
            if (first != null) {
                last.nextlink = a;
                last = a;
            } else {
                first = a;
                last = a;
            }
            System.out.println("Inserted -:"+d1);
        }

        public static void deletefromFirst() {
            if(null!=first)
            {
                System.out.println("Deleting -:"+first.data);
                first = first.nextlink;
            }
            else{
                System.out.println("No elements in Linked List");
            }
        }

        public static void printList() {
            System.out.println("Elements in the list are");
            System.out.println("-------------------------");
            Link temp = first;
            while (temp != null) {
                System.out.println(temp.data);
                temp = temp.nextlink;
            }
        }
    }
}

Apply function to all elements of collection through LINQ

Or you can hack it up.

Items.All(p => { p.IsAwesome = true; return true; });

Understanding passport serialize deserialize

  1. Where does user.id go after passport.serializeUser has been called?

The user id (you provide as the second argument of the done function) is saved in the session and is later used to retrieve the whole object via the deserializeUser function.

serializeUser determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}

  1. We are calling passport.deserializeUser right after it where does it fit in the workflow?

The first argument of deserializeUser corresponds to the key of the user object that was given to the done function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc). In deserializeUser that key is matched with the in memory array / database or any data resource.

The fetched object is attached to the request object as req.user

Visual Flow

passport.serializeUser(function(user, done) {
    done(null, user.id);
});              ¦
                 ¦ 
                 ¦
                 +--------------------? saved to session
                                   ¦    req.session.passport.user = {id: '..'}
                                   ¦
                                   ?           
passport.deserializeUser(function(id, done) {
                   +---------------+
                   ¦
                   ? 
    User.findById(id, function(err, user) {
        done(err, user);
    });            +--------------? user object attaches to the request as req.user   
});

Best way to get whole number part of a Decimal number

You just need to cast it, as such:

int intPart = (int)343564564.4342

If you still want to use it as a decimal in later calculations, then Math.Truncate (or possibly Math.Floor if you want a certain behaviour for negative numbers) is the function you want.

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

JAVA_HOME does not point to the JDK

I just copied tools.jar file from JDK\lib folder to JRE\lib folder. Since then it worked like a champ.

Excluding Maven dependencies

Global exclusions look like they're being worked on, but until then...

From the Sonatype maven reference (bottom of the page):

Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.

As an example:

  <dependencies>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
    </dependencies>
  </dependencyManagement>

It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.

Python if not == vs if !=

@jonrsharpe has an excellent explanation of what's going on. I thought I'd just show the difference in time when running each of the 3 options 10,000,000 times (enough for a slight difference to show).

Code used:

def a(x):
    if x != 'val':
        pass


def b(x):
    if not x == 'val':
        pass


def c(x):
    if x == 'val':
        pass
    else:
        pass


x = 1
for i in range(10000000):
    a(x)
    b(x)
    c(x)

And the cProfile profiler results:

enter image description here

So we can see that there is a very minute difference of ~0.7% between if not x == 'val': and if x != 'val':. Of these, if x != 'val': is the fastest.

However, most surprisingly, we can see that

if x == 'val':
        pass
    else:

is in fact the fastest, and beats if x != 'val': by ~0.3%. This isn't very readable, but I guess if you wanted a negligible performance improvement, one could go down this route.

How to execute a java .class from the command line

First, have you compiled the class using the command line javac compiler? Second, it seems that your main method has an incorrect signature - it should be taking in an array of String objects, rather than just one:

public static void main(String[] args){

Once you've changed your code to take in an array of String objects, then you need to make sure that you're printing an element of the array, rather than array itself:

System.out.println(args[0])

If you want to print the whole list of command line arguments, you'd need to use a loop, e.g.

for(int i = 0; i < args.length; i++){
    System.out.print(args[i]);
}
System.out.println();

When saving, how can you check if a field has changed?

If you are using a form, you can use Form's changed_data (docs):

class AliasForm(ModelForm):

    def save(self, commit=True):
        if 'remote_image' in self.changed_data:
            # do things
            remote_image = self.cleaned_data['remote_image']
            do_things(remote_image)
        super(AliasForm, self).save(commit)

    class Meta:
        model = Alias

What is a 'workspace' in Visual Studio Code?

Just added in February 2021 is this documentation on "What is a VS Code 'workspace'": workspaces.

A Visual Studio Code "workspace" is the collection of one or more folders that are opened in a VS Code window (instance). In most cases, you will have a single folder opened as the workspace but, depending on your development workflow, you can include more than one folder, using an advanced configuration called Multi-root workspaces.

The concept of a workspace enables VS Code to:

Configure settings that only apply to a specific folder or folders but not others. Persist task and debugger launch configurations that are only valid in the context of that workspace. Store and restore UI state associated with that workspace (for example, the files that are opened). Selectively enable or disable extensions only for that workspace. You may see the terms "folder" and "workspace" used interchangeably in VS Code documentation, issues, and community discussions. Think of a workspace as the root of a project that has extra VS Code knowledge and capabilities.

  • Note: It is also possible to open VS Code without a workspace. For example, when you open a new VS Code window by selecting a file from your platform's File menu, you will not be inside a workspace. In this mode, some of VS Code's capabilities are reduced but you can still open text files and edit them.

Single-folder workspaces

You don't have to do anything for a folder to become a VS Code workspace other than open the folder with VS Code. Once a folder has been opened, VS Code will automatically keep track of things such as your open files and editor layout so the editor will be as you left it when you reopen that folder. You can also add other folder-specific configurations such as workspace-specific settings (versus global user settings) and task definition and debugging launch files (see below in the workspace settings section).

Multi-root workspaces

Multi-root workspaces are an advanced capability of VS Code that allow you to configure multiple distinct folders to be part of the workspace. Instead of opening a folder as workspace, you will open a .code-workspace JSON file that lists the folders of the workspace. For example:

{
  "folders": [
    {
      "path": "my-folder-a"
    },
    {
      "path": "my-folder-b"
    }
  ]
}

multi-root workspace folders

A multi-root workspace opened in VS Code

  • Note: The visual difference of having a folder opened versus opening a .code-workspace file can be subtle. To give you a hint that a .code-workspace file has been opened, some areas of the user interface (for example, the root of the File Explorer) show an extra (Workspace) suffix next to the name.

And much more at the first link.

The target principal name is incorrect. Cannot generate SSPI context

In my situation I was trying to use Integrated Security to connect from a PC to SQL Server on another PC on a network without a domain. On both PCs, I was signing in to Windows with the same Microsoft account. I switched to a local account on both PCs and SQL Server now connects successfully.

boolean in an if statement

I think that your reasoning is sound. But in practice I have found that it is far more common to omit the === comparison. I think that there are three reasons for that:

  1. It does not usually add to the meaning of the expression - that's in cases where the value is known to be boolean anyway.
  2. Because there is a great deal of type-uncertainty in JavaScript, forcing a type check tends to bite you when you get an unexpected undefined or null value. Often you just want your test to fail in such cases. (Though I try to balance this view with the "fail fast" motto).
  3. JavaScript programmers like to play fast-and-loose with types - especially in boolean expressions - because we can.

Consider this example:

var someString = getInput();
var normalized = someString && trim(someString);  
// trim() removes leading and trailing whitespace

if (normalized) {
    submitInput(normalized);
}

I think that this kind of code is not uncommon. It handles cases where getInput() returns undefined, null, or an empty string. Due to the two boolean evaluations submitInput() is only called if the given input is a string that contains non-whitespace characters.

In JavaScript && returns its first argument if it is falsy or its second argument if the first argument is truthy; so normalized will be undefined if someString was undefined and so forth. That means that none of the inputs to the boolean expressions above are actually boolean values.

I know that a lot of programmers who are accustomed to strong type-checking cringe when seeing code like this. But note applying strong typing would likely require explicit checks for null or undefined values, which would clutter up the code. In JavaScript that is not needed.

How to Check if value exists in a MySQL database

Assuming the connection is established and is available in global scope;

//Check if a value exists in a table
function record_exists ($table, $column, $value) {
    global $connection;
    $query = "SELECT * FROM {$table} WHERE {$column} = {$value}";
    $result = mysql_query ( $query, $connection );
    if ( mysql_num_rows ( $result ) ) {
        return TRUE;
    } else {
        return FALSE;
    }
}

Usage: Assuming that the value to be checked is stored in the variable $username;

if (record_exists ( 'employee', 'username', $username )){
    echo "Username is not available. Try something else.";
} else {
    echo "Username is available";
}

Name [jdbc/mydb] is not bound in this Context

For those who use Tomcat with Bitronix, this will fix the problem:

The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.

In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:

(if you already used them, make sure your references are correct):

  • btm.root
  • bitronix.tm.configuration

e.g.

-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59" 
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties" 

Now, restart your server and check the log.

SSL peer shut down incorrectly in Java

I was having the same issue, as everyone else I suppose.. adding the System.setProperties(....) didn't fix it for me.

So my email client is in a separate project uploaded to an artifactory. I'm importing this project into other projects as a gradle dependency. My problem was that I was using implementation in my build.gradle for javax.mail, which was causing issues downstream.
I changed this line from implementation to api and my downstream project started working and connecting again.

It says that TypeError: document.getElementById(...) is null

Make sure the script is placed in the bottom of the BODY element of the document you're trying to manipulate, not in the HEAD element or placed before any of the elements you want to "get".

It does not matter if you import the script or if it's inline, the important thing is the placing. You don't have to put the command inside a function either; while it's good practice you can just call it directly, it works just fine.

Pass user defined environment variable to tomcat

If you are starting your Tomcat from Eclipse ("Servers" view) then you should have a "Run/Run Configuration" (menu) entry called "Apache Tomcat / Tomcat …". When you select this entry in the list of run configurations you get a window with several tabs, one of which is labeled "Environment". There you can configure environment variables for your Tomcat. Be sure to restart Tomcat afterwards.

Best way to repeat a character in C#

What about using extension method?


public static class StringExtensions
{
   public static string Repeat(this char chatToRepeat, int repeat) {

       return new string(chatToRepeat,repeat);
   }
   public  static string Repeat(this string stringToRepeat,int repeat)
   {
       var builder = new StringBuilder(repeat*stringToRepeat.Length);
       for (int i = 0; i < repeat; i++) {
           builder.Append(stringToRepeat);
       }
       return builder.ToString();
   }
}

You could then write :

Debug.WriteLine('-'.Repeat(100)); // For Chars  
Debug.WriteLine("Hello".Repeat(100)); // For Strings

Note that a performance test of using the stringbuilder version for simple characters instead of strings gives you a major preformance penality : on my computer the difference in mesured performance is 1:20 between: Debug.WriteLine('-'.Repeat(1000000)) //char version and
Debug.WriteLine("-".Repeat(1000000)) //string version

Android Studio doesn't start, fails saying components not installed

This answer is for OSX

I needed to resolve two things to successfully install android studio:

  1. Ensure you aren't using proxy that is stopping you from accessing the android resources. If you are using a corporate proxy, ensure that you have the settings setup up in Android Studio > Preferences > Filter for Proxy. If you don't see the Licence Agreement (Agree/Disagree) then your connection is not reaching the google download servers
  2. Run rm -rf ~/.android. This was essential in getting this working for me. A previous install or something else had affected this download caches. Best to nuke it and start fresh.

Cannot read property 'getContext' of null, using canvas

I assume you have your JS file declared inside the <head> tag so it keeps it consistent, like standard, then in your JS make sure the canvas initialization is after the page is loaded:

window.onload = function () {
    var myCanvas = document.getElementById('canvas');
    var ctx = myCanvas.getContext('2d');
}

There is no need to use jQuery just to initialize a canvas, it's very evident most of the programmers all around the world use it unnecessarily and the accepted answer is a probe of that.

Getting the PublicKeyToken of .Net assemblies

Open a command prompt and type one of the following lines according to your Visual Studio version and Operating System Architecture :

VS 2008 on 32bit Windows :

"%ProgramFiles%\Microsoft SDKs\Windows\v6.0A\bin\sn.exe" -T <assemblyname>

VS 2008 on 64bit Windows :

"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v6.0A\bin\sn.exe" -T <assemblyname>

VS 2010 on 32bit Windows :

"%ProgramFiles%\Microsoft SDKs\Windows\v7.0A\bin\sn.exe" -T <assemblyname>

VS 2010 on 64bit Windows :

"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v7.0A\bin\sn.exe" -T <assemblyname>

VS 2012 on 32bit Windows :

"%ProgramFiles%\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\sn.exe" -T <assemblyname>

VS 2012 on 64bit Windows :

"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\sn.exe" -T <assemblyname>

VS 2015 on 64bit Windows :

"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\sn.exe" -T <assemblyname>

Note that for the versions VS2012+, sn.exe application isn't anymore in bin but in a sub-folder. Also, note that for 64bit you need to specify (x86) folder.

If you prefer to use Visual Studio command prompt, just type :

sn -T <assembly> 

where <assemblyname> is a full file path to the assembly you're interested in, surrounded by quotes if it has spaces.

You can add this as an external tool in VS, as shown here:
http://blogs.msdn.com/b/miah/archive/2008/02/19/visual-studio-tip-get-public-key-token-for-a-stong-named-assembly.aspx

Angular: conditional class with *ngClass

In Angular 7.X

The CSS classes are updated as follows, depending on the type of the expression evaluation:

  • string - the CSS classes listed in the string (space delimited) are added

  • Array - the CSS classes declared as Array elements are added

  • Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

<some-element [ngClass]="'first second'">...</some-element>

<some-element [ngClass]="['first', 'second']">...</some-element>

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>

<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>

<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>

Update cordova plugins in one command

Go to your cordova project directory then write

npm outdated

npm will be display your outdated plugins, if any plugin outdated then write this command

npm update

Console Preview

Choose folders to be ignored during search in VS Code

Hi you need to find settings and add a new exclude pattern for history files

VSC Screenshot

How can I strip HTML tags from a string in ASP.NET?

I have written a pretty fast method in c# which beats the hell out of the Regex. It is hosted in an article on CodeProject.

Its advantages are, among better performance the ability to replace named and numbered HTML entities (those like &amp;amp; and &203;) and comment blocks replacement and more.

Please read the related article on CodeProject.

Thank you.

Differences between utf8 and latin1

In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).

Spring Boot - How to log all requests and responses with exceptions in single place?

You could use javax.servlet.Filter if there wasn't a requirement to log java method that been executed.

But with this requirement you have to access information stored in handlerMapping of DispatcherServlet. That said, you can override DispatcherServlet to accomplish logging of request/response pair.

Below is an example of idea that can be further enhanced and adopted to your needs.

public class LoggableDispatcherServlet extends DispatcherServlet {

    private final Log logger = LogFactory.getLog(getClass());

    @Override
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (!(request instanceof ContentCachingRequestWrapper)) {
            request = new ContentCachingRequestWrapper(request);
        }
        if (!(response instanceof ContentCachingResponseWrapper)) {
            response = new ContentCachingResponseWrapper(response);
        }
        HandlerExecutionChain handler = getHandler(request);

        try {
            super.doDispatch(request, response);
        } finally {
            log(request, response, handler);
            updateResponse(response);
        }
    }

    private void log(HttpServletRequest requestToCache, HttpServletResponse responseToCache, HandlerExecutionChain handler) {
        LogMessage log = new LogMessage();
        log.setHttpStatus(responseToCache.getStatus());
        log.setHttpMethod(requestToCache.getMethod());
        log.setPath(requestToCache.getRequestURI());
        log.setClientIp(requestToCache.getRemoteAddr());
        log.setJavaMethod(handler.toString());
        log.setResponse(getResponsePayload(responseToCache));
        logger.info(log);
    }

    private String getResponsePayload(HttpServletResponse response) {
        ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
        if (wrapper != null) {

            byte[] buf = wrapper.getContentAsByteArray();
            if (buf.length > 0) {
                int length = Math.min(buf.length, 5120);
                try {
                    return new String(buf, 0, length, wrapper.getCharacterEncoding());
                }
                catch (UnsupportedEncodingException ex) {
                    // NOOP
                }
            }
        }
        return "[unknown]";
    }

    private void updateResponse(HttpServletResponse response) throws IOException {
        ContentCachingResponseWrapper responseWrapper =
            WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
        responseWrapper.copyBodyToResponse();
    }

}

HandlerExecutionChain - contains the information about request handler.

You then can register this dispatcher as following:

    @Bean
    public ServletRegistrationBean dispatcherRegistration() {
        return new ServletRegistrationBean(dispatcherServlet());
    }

    @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
    public DispatcherServlet dispatcherServlet() {
        return new LoggableDispatcherServlet();
    }

And here's the sample of logs:

http http://localhost:8090/settings/test
i.g.m.s.s.LoggableDispatcherServlet      : LogMessage{httpStatus=500, path='/error', httpMethod='GET', clientIp='127.0.0.1', javaMethod='HandlerExecutionChain with handler [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)] and 3 interceptors', arguments=null, response='{"timestamp":1472475814077,"status":500,"error":"Internal Server Error","exception":"java.lang.RuntimeException","message":"org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.RuntimeException","path":"/settings/test"}'}

http http://localhost:8090/settings/params
i.g.m.s.s.LoggableDispatcherServlet      : LogMessage{httpStatus=200, path='/settings/httpParams', httpMethod='GET', clientIp='127.0.0.1', javaMethod='HandlerExecutionChain with handler [public x.y.z.DTO x.y.z.Controller.params()] and 3 interceptors', arguments=null, response='{}'}

http http://localhost:8090/123
i.g.m.s.s.LoggableDispatcherServlet      : LogMessage{httpStatus=404, path='/error', httpMethod='GET', clientIp='127.0.0.1', javaMethod='HandlerExecutionChain with handler [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)] and 3 interceptors', arguments=null, response='{"timestamp":1472475840592,"status":404,"error":"Not Found","message":"Not Found","path":"/123"}'}

UPDATE

In case of errors Spring does automatic error handling. Therefore, BasicErrorController#error is shown as request handler. If you want to preserve original request handler, then you can override this behavior at spring-webmvc-4.2.5.RELEASE-sources.jar!/org/springframework/web/servlet/DispatcherServlet.java:971 before #processDispatchResult is called, to cache original handler.

"Can't find Project or Library" for standard VBA functions

Even when all references are fine the prefix problem causes compile errors.

What about creating a find and replace sub for all 'built-in VBA functions' in all modules, like this:

replace text in code module

e.g. "= Date" will be replaced with "= VBA.Date".

e.g. " Date(" will be replaced with " VBA.Date(" .

(excluding "dim t As Date" or "mydate")

All vba functions for find and replace are written here :

vba functions list

How to increase size of DOSBox window?

For using DOSBox with SDL, you will need to set or change the following:

[sdl]
windowresolution=1280x960
output=opengl

Here is three options to put those settings:

  1. Edit user's default configuration, for example, using vi:

    $ dosbox -printconf
    /home/USERNAME/.dosbox/dosbox-0.74.conf
    $ vi "$(dosbox -printconf)"
    $ dosbox
    
  2. For temporary resize, create a new configuration with the three lines above, say newsize.conf:

    $ dosbox -conf newsize.conf
    

    You can use -conf to load multiple configuration and/or with -userconf for default configuration, for example:

    $ dosbox -userconf -conf newsize.conf 
    [snip]
    ---
    CONFIG:Loading primary settings from config file /home/USERNAME/.dosbox/dosbox-0.74.conf
    CONFIG:Loading additional settings from config file newsize.conf
    [snip]
    
  3. Create a dosbox.conf under current directory, DOSBox loads it as default.

DOSBox should start up and resize to 1280x960 in this case.

Note that you probably would not get any size you desired, for instance, I set 1280x720 and I got 1152x720.

"unable to locate adb" using Android Studio

In Android Studio, Click on 'Tools' on the top tab bar of android studio

Tools >> Android >> SDK Manager >> Launch Standalone Sdk manager

there you can clearly see which platform tool is missing , then just install that and your adb will start working properly.In Image You Can see every thing

Postgres and Indexes on Foreign Keys and Primary Keys

This function, based on the work by Laurenz Albe at https://www.cybertec-postgresql.com/en/index-your-foreign-key/, list all the foreign keys with missing indexes. The size of the table is shown, as for small tables the scanning performance could be superior to the index one.

--
-- function:    fkeys_missing_indexes
-- purpose:     list all foreing keys in the database without and index in the source table.
-- author:      Laurenz Albe
-- see:         https://www.cybertec-postgresql.com/en/index-your-foreign-key/
--
create or replace function oftool_fkey_missing_indexes () 
returns table (
  src_table     regclass,
  fk_columns    varchar,
  table_size    varchar,
  fk_constraint name,
  dst_table     regclass
)
as $$
select
  -- source table having ta foreign key declaration
  tc.conrelid::regclass as src_table,
  
  -- ordered list of foreign key columns
  string_agg(ta.attname, ',' order by tx.n) as fk_columns,
  
  -- source table size
  pg_catalog.pg_size_pretty (
    pg_catalog.pg_relation_size(tc.conrelid)
  ) as table_size,
  
  -- name of the foreign key constraint
  tc.conname as fk_constraint,
  
  -- name of the target or destination table
  tc.confrelid::regclass as dst_table
  
from pg_catalog.pg_constraint tc

-- enumerated key column numbers per foreign key
cross join lateral unnest(tc.conkey) with ordinality as tx(attnum, n)

-- name for each key column
join pg_catalog.pg_attribute ta on ta.attnum = tx.attnum and ta.attrelid = tc.conrelid

where not exists (
  -- is there ta matching index for the constraint?
  select 1 from pg_catalog.pg_index i
  where 
    i.indrelid = tc.conrelid and 
    -- the first index columns must be the same as the key columns, but order doesn't matter
    (i.indkey::smallint[])[0:cardinality(tc.conkey)-1] @> tc.conkey) and 
    tc.contype = 'f'
  group by 
    tc.conrelid, 
    tc.conname, 
    tc.confrelid
  order by 
    pg_catalog.pg_relation_size(tc.conrelid) desc;
$$ language sql;

test it this way,

select * from oftool_fkey_missing_indexes();

you'll see a list like this.

fk_columns            |table_size|fk_constraint                     |dst_table        |
----------------------|----------|----------------------------------|-----------------|
id_group              |0 bytes   |fk_customer__group                |im_group         |
id_product            |0 bytes   |fk_cart_item__product             |im_store_product |
id_tax                |0 bytes   |fk_order_tax_resume__tax          |im_tax           |
id_product            |0 bytes   |fk_order_item__product            |im_store_product |
id_tax                |0 bytes   |fk_invoice_tax_resume__tax        |im_tax           |
id_product            |0 bytes   |fk_invoice_item__product          |im_store_product |
id_article,locale_code|0 bytes   |im_article_comment_id_article_fkey|im_article_locale|

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

If you need the for statement to contain only the if, you need to remove its else, like this:

for(int i=0; i<something_in_the_array.length;i++)
    if(whatever_value==(something_in_the_array[i]))
    {
        value=2;
        break;
    }

    /*this "else" must go*/
    if(whatever_value==2)
    {
        value=3;
        break;
    }

    else if(whatever_value==3)
    {
        value=4;
        break;
    }

How to fill color in a cell in VBA?

  1. Use conditional formatting instead of VBA to highlight errors.

  2. Using a VBA loop like the one you posted will take a long time to process

  3. the statement If cell.Value = "#N/A" Then will never work. If you insist on using VBA to highlight errors, try this instead.

    Sub ColorCells()

    Dim Data As Range
    Dim cell As Range
    Set currentsheet = ActiveWorkbook.Sheets("Comparison")
    Set Data = currentsheet.Range("A2:AW1048576")
    
    For Each cell In Data
    
    If IsError(cell.Value) Then
       cell.Interior.ColorIndex = 3
    End If
    Next
    
    End Sub
    
  4. Be prepared for a long wait, since the procedure loops through 51 million cells

  5. There are more efficient ways to achieve what you want to do. Update your question if you have a change of mind.

How can I determine if a variable is 'undefined' or 'null'?

The foo == null check should do the trick and resolve the "undefined OR null" case in the shortest manner. (Not considering "foo is not declared" case.) But people who are used to have 3 equals (as the best practice) might not accept it. Just look at eqeqeq or triple-equals rules in eslint and tslint...

The explicit approach, when we are checking if a variable is undefined or null separately, should be applied in this case, and my contribution to the topic (27 non-negative answers for now!) is to use void 0 as both short and safe way to perform check for undefined.

Using foo === undefined is not safe because undefined is not a reserved word and can be shadowed (MDN). Using typeof === 'undefined' check is safe, but if we are not going to care about foo-is-undeclared case the following approach can be used:

if (foo === void 0 || foo === null) { ... }

Fast query runs slow in SSRS

DO you use "group by" in the SSRS table?

I had a report with 3 grouped by fields and I noticed that the report runed very slowly despite having a light query, to the point where I can't even dial values in the search field.

Than I removed the groupings and now the report goes up in seconds and everything works in an instant.

Scale the contents of a div by a percentage?

You can simply use the zoom property:

#myContainer{
    zoom: 0.5;
    -moz-transform: scale(0.5);
}

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

Recommended SQL database design for tags or tagging

Normally I would agree with Yaakov Ellis but in this special case there is another viable solution:

Use two tables:

Table: Item
Columns: ItemID, Title, Content
Indexes: ItemID

Table: Tag
Columns: ItemID, Title
Indexes: ItemId, Title

This has some major advantages:

First it makes development much simpler: in the three-table solution for insert and update of item you have to lookup the Tag table to see if there are already entries. Then you have to join them with new ones. This is no trivial task.

Then it makes queries simpler (and perhaps faster). There are three major database queries which you will do: Output all Tags for one Item, draw a Tag-Cloud and select all items for one Tag Title.

All Tags for one Item:

3-Table:

SELECT Tag.Title 
  FROM Tag 
  JOIN ItemTag ON Tag.TagID = ItemTag.TagID
 WHERE ItemTag.ItemID = :id

2-Table:

SELECT Tag.Title
FROM Tag
WHERE Tag.ItemID = :id

Tag-Cloud:

3-Table:

SELECT Tag.Title, count(*)
  FROM Tag
  JOIN ItemTag ON Tag.TagID = ItemTag.TagID
 GROUP BY Tag.Title

2-Table:

SELECT Tag.Title, count(*)
  FROM Tag
 GROUP BY Tag.Title

Items for one Tag:

3-Table:

SELECT Item.*
  FROM Item
  JOIN ItemTag ON Item.ItemID = ItemTag.ItemID
  JOIN Tag ON ItemTag.TagID = Tag.TagID
 WHERE Tag.Title = :title

2-Table:

SELECT Item.*
  FROM Item
  JOIN Tag ON Item.ItemID = Tag.ItemID
 WHERE Tag.Title = :title

But there are some drawbacks, too: It could take more space in the database (which could lead to more disk operations which is slower) and it's not normalized which could lead to inconsistencies.

The size argument is not that strong because the very nature of tags is that they are normally pretty small so the size increase is not a large one. One could argue that the query for the tag title is much faster in a small table which contains each tag only once and this certainly is true. But taking in regard the savings for not having to join and the fact that you can build a good index on them could easily compensate for this. This of course depends heavily on the size of the database you are using.

The inconsistency argument is a little moot too. Tags are free text fields and there is no expected operation like 'rename all tags "foo" to "bar"'.

So tldr: I would go for the two-table solution. (In fact I'm going to. I found this article to see if there are valid arguments against it.)

Open Redis port for remote connections

  1. Open $REDIS_HOME/redis.conf and uncomment requirepass -YOUR-PASSWORD-HERE- and write down your password in the specified lines.

  2. Login to redis using redis-cli and verify your password in the database using auth -YOUR-PASSWORD-HERE- command.

  3. Disable protected mode by changing its string in $REDIS_HOME/redis.conf to protected-mode no.

  4. Search for all bind ports values and comment all of them. Just add bind 0.0.0.0 to $REDIS_HOME/redis.conf file.

  5. Disable your firewall or open redis port.

  6. Start redis using ./redis-server $REDIS_HOME/redis.conf.

  7. Check the configuration via ./redis-cli -h -YOUR-IP- -a -YOUR-PASSWORD-HERE-.

  8. Check the configuration via ./redis-cli -h -YOUR-IP- ping.

Replacing NULL and empty string within Select statement

For an example data in your table such as combinations of

'', null and as well as actual value than if you want to only actual value and replace to '' and null value by # symbol than execute this query

SELECT Column_Name = (CASE WHEN (Column_Name IS NULL OR Column_Name = '') THEN '#' ELSE Column_Name END) FROM Table_Name

and another way you can use it but this is little bit lengthy and instead of this you can also use IsNull function but here only i am mentioning IIF function

SELECT IIF(Column_Name IS NULL, '#', Column_Name) FROM Table_Name  
SELECT IIF(Column_Name  = '', '#', Column_Name) FROM Table_Name  
-- and syntax of this query
SELECT IIF(Column_Name IS NULL, 'True Value', 'False Value') FROM Table_Name

How to define dimens.xml for every different screen size in android?

we want to see the changes of required view size in different screens.

We need to create a different values folders for different screens and put dimens.xml file based on screen densities.

I have taken one TextView and observed the changes when i changed dimens.xml in different values folders.

Please follow the process

normal - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - xhdpi \ dimens.xml

nexus 5X ( 5.2" * 1080 * 1920 : 420dpi )

nexus 6P ( 5.7" * 1440 * 2560 : 560dpi)

nexus 6 ( 6.0" * 1440 * 2560 : 560dpi)

nexus 5 (5.0", 1080 1920 : xxhdpi)

nexus 4 (4.7", 768 * 1280 : xhdpi)

Galaxy nexus (4.7", 720 * 1280 : xhdpi)

4.65" 720p ( 720 * 1280 : xhdpi )

4.7" WXGA ( 1280 * 720 : Xhdpi )

Xlarge - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the Xlarge - xhdpi \ dimens.xml

nexus 9 ( 8.9", 2048 * 1556 : xhdpi)

nexus 10 (10.1", 2560 * 1600 : xhdpi)

large - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - xhdpi \ dimens.xml

nexus 7 ( 7.0", 1200 * 1920: xhdpi)

nexus 7 (2012) (7.0", 800 * 1280 : tvdpi)

The below screens are visible in " Search Generic Phones and Tablets "

large - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - mdpi \ dimens.xml

5.1" WVGA ( 480 * 800 : mdpi )

5.4" FWVGA ( 480 * 854 : mdpi )

7.0" WSVGA (Tablet) ( 1024 * 600 : mdpi )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

nexus s ( 4.0", 480 * 800 : hdpi )

nexus one ( 3.7", 480 * 800: hdpi)

small - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the small - ldpi \ dimens.xml

2.7" QVGA Slider ( 240 * 320 : ldpi )

2.7" QVGA ( 240 * 320 : ldpi )

xlarge - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the xlarge - mdpi \ dimens.xml

10.1" WXGA ( tABLET) ( 1280 * 800 : MDPI )

normal - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - ldpi \ dimens.xml

3.3" WQVGA ( 240 * 400 : LDPI )

3.4" WQVGA ( 240 * 432 : LDPI )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

4.0" WVGA ( 480 * 800 : hdpi )

3.7" WVGA ( 480 * 800 : hdpi )

3.7" FWVGA Slider ( 480 * 854 : hdpi )

normal - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - mdpi \ dimens.xml

3.2" HVGA Slider ( ADP1 ) ( 320 * 480 : MDPI )

3.2" QVGA ( ADP2 ) ( 320 * 480 : MDPI )

Counter increment in Bash loop not working

I think this single awk call is equivalent to your grep|grep|awk|awk pipeline: please test it. Your last awk command appears to change nothing at all.

The problem with COUNTER is that the while loop is running in a subshell, so any changes to the variable vanish when the subshell exits. You need to access the value of COUNTER in that same subshell. Or take @DennisWilliamson's advice, use a process substitution, and avoid the subshell altogether.

awk '
  /GET \/log_/ && /upstream timed out/ {
    split($0, a, ", ")
    split(a[2] FS a[4] FS $0, b)
    print "http://example.com" b[5] "&ip=" b[2] "&date=" b[7] "&time=" b[8] "&end=1"
  }
' | {
    while read WFY_URL
    do
        echo $WFY_URL #Some more action
        (( COUNTER++ ))
    done
    echo $COUNTER
}

if else condition in blade file (laravel 5.3)

I think you are putting one too many curly brackets. Try this

 @if($user->status=='waiting')
            <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
            @else
            <td>{!! $user->status !!}</td>
        @endif

How to remove a column from an existing table?

If you are using C# and the Identity column is int, create a new instance of int without providing any value to it.It worked for me.

[identity_column] = new int()

Runtime vs. Compile time

Compile Time:

Things that are done at compile time incur (almost) no cost when the resulting program is run, but might incur a large cost when you build the program. Run-Time:

More or less the exact opposite. Little cost when you build, more cost when the program is run.

From the other side; If something is done at compile time, it runs only on your machine and if something is run-time, it run on your users machine.

Android custom dropdown/popup menu

The Kotlin Way

fun showPopupMenu(view: View) {
    PopupMenu(view.context, view).apply {
                menuInflater.inflate(R.menu.popup_men, menu)
                setOnMenuItemClickListener { item ->
                    Toast.makeText(view.context, "You Clicked : " + item.title, Toast.LENGTH_SHORT).show()
                    true
                }
            }.show()
}

UPDATE: In the above code, the apply function returns this which is not required, so we can use run which don't return anything and to make it even simpler we can also remove the curly braces of showPopupMenu method.

Even Simpler:

fun showPopupMenu(view: View) = PopupMenu(view.context, view).run {
            menuInflater.inflate(R.menu.popup_men, menu)
            setOnMenuItemClickListener { item ->
                Toast.makeText(view.context, "You Clicked : ${item.title}", Toast.LENGTH_SHORT).show()
                true
            }
            show()
        }

How do I parse JSON with Objective-C?

NSString* path  = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"json"];

//????????????,????NSUTF8StringEncoding ????,
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

//??????????
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *jsonError;
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];


for (int i=0; i<[allKeys count]; i++) {
    NSDictionary *arrayResult = [allKeys objectAtIndex:i];
    NSLog(@"name=%@",[arrayResult objectForKey:@"storyboardName"]);

}

file:

 [
  {
  "ID":1,
  "idSort" : 0,
  "deleted":0,
  "storyboardName" : "MLMember",
  "dispalyTitle" : "76.360779",
  "rightLevel" : "10.010490",
  "showTabBar" : 1,
  "openWeb" : 0,
  "webUrl":""
  },
  {
  "ID":1,
  "idSort" : 0,
  "deleted":0,
  "storyboardName" : "0.00",
  "dispalyTitle" : "76.360779",
  "rightLevel" : "10.010490",
  "showTabBar" : 1,
  "openWeb" : 0,
  "webUrl":""
  }
  ]

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

Not in this questions askers case but often:

What does the "premature end of script headers" error mean?

That error means that the FCGI call was exited unexpectedly.

In some cases it means that the script "backup.php" did crash.

How to fix this?

If the crash of a script was the cause, fix the script so that it does not crash. Then this error is fixed, too. To find out if and why a script crashes, you need to debug it. For example you can check the PHP error log. Errors logged to STDERR normally go into the error handler of the FCGI.

How to get the selected row values of DevExpress XtraGrid?

All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.

For example:

private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
        return;
    MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());            
}

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

got into same kind of problem, wasn't able to exclude main spring boot class during testing. Solved it using following approach.

Instead of using @SpringBootApplication, use all three annotations which it contains and assign the name to @Configuration

@Configuration("myApp")
@EnableAutoConfiguration
@ComponentScan
public class MyApp { .. }

In your test class define configuration with exactly same name:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
// ugly hack how to exclude main configuration
@Configuration("myApp")
@SpringApplicationConfiguration(classes = MyTest.class)
public class MyTest { ... }

This should help. Would be nice to have some better way in place how to disable auto scanning for configuration annotations...

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

Best way to parse RSS/Atom feeds with PHP

Another great free parser - http://bncscripts.com/free-php-rss-parser/ It's very light ( only 3kb ) and simple to use!

Run a Command Prompt command from Desktop Shortcut

You can also create a shortcut on desktop that can run a specific command or even a batch file by just typing the command in "Type the Location of Item" bar in create shortcut wizard

  1. Right click on Desktop.
  2. Enter the command in "Type the Location of Item" bar.
  3. Double click the shortcut to run the command.

Found detailed Instructions here

Font awesome is not showing icon

When you open font-awesome.min.css you can see following path:

'Fonts/fontawesome-webfont.ttf?v=4.2.0' ...

It means that you have to create directory Fonts and then copy files fontawesome-webfont.ttf (fontawesome-webfont.woff, fontawesome-webfont.eot) to this folder. After that everything should work fine.

Root element is missing

  1. Check the trees.config file which located in config folder... sometimes (I don't know why) this file became to be empty like someone delete the content inside... keep backup up of this file in your local pc then when this error appear - replace the server file with your local file. This is what i do when this error happened.

  2. check the available space on the server. sometimes this is the problem.

Good luck.

Remove the last chars of the Java String variable

import org.apache.commons.lang3.StringUtils;

// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"
StringUtils.removeEnd(path, ".null");
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf"

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

Does MySQL ignore null values on unique constraints?

From the docs:

"a UNIQUE index permits multiple NULL values for columns that can contain NULL"

This applies to all engines but BDB.

test if display = none

Try this instead to only select the visible elements under the tbody:

$('tbody :visible').highlight(myArray[i]);

Android disable screen timeout while app is running

I used:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

to disable the screen timeout and

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

to re-enable it.

range() for floats

This can be done with numpy.arange(start, stop, stepsize)

import numpy as np

np.arange(0.5,5,1.5)
>> [0.5, 2.0, 3.5, 5.0]

# OBS you will sometimes see stuff like this happening, 
# so you need to decide whether that's not an issue for you, or how you are going to catch it.
>> [0.50000001, 2.0, 3.5, 5.0]

Note 1: From the discussion in the comment section here, "never use numpy.arange() (the numpy documentation itself recommends against it). Use numpy.linspace as recommended by wim, or one of the other suggestions in this answer"

Note 2: I have read the discussion in a few comments here, but after coming back to this question for the third time now, I feel this information should be placed in a more readable position.

How can I convert a char to int in Java?

You can use static methods from Character class to get Numeric value from char.

char x = '9';

if (Character.isDigit(x)) { // Determines if the specified character is a digit.
    int y = Character.getNumericValue(x); //Returns the int value that the 
                                          //specified Unicode character represents.
    System.out.println(y);
}

@font-face src: local - How to use the local font if the user already has it?

If you want to check for local files first do:

@font-face {
font-family: 'Green Sans Web';
src:
    local('Green Web'),
    local('GreenWeb-Regular'),
    url('GreenWeb.ttf');
}

There is a more elaborate description of what to do here.

What does "var" mean in C#?

"var" means the compiler will determine the explicit type of the variable, based on usage. For example,

var myVar = new Connection();

would give you a variable of type Connection.

@Autowired and static method

You can do this by following one of the solutions:

Using constructor @Autowired

This approach will construct the bean requiring some beans as constructor parameters. Within the constructor code you set the static field with the value got as parameter for constructor execution. Sample:

@Component
public class Boo {

    private static Foo foo;

    @Autowired
    public Boo(Foo foo) {
        Boo.foo = foo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}

Using @PostConstruct to hand value over to static field

The idea here is to hand over a bean to a static field after bean is configured by spring.

@Component
public class Boo {

    private static Foo foo;
    @Autowired
    private Foo tFoo;

    @PostConstruct
    public void init() {
        Boo.foo = tFoo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}

jQuery animate scroll

You can give this simple jQuery plugin (AnimateScroll) a whirl. It is quite easy to use.

1. Scroll to the top of the page:

$('body').animatescroll();

2. Scroll to an element with ID section-1:

$('#section-1').animatescroll({easing:'easeInOutBack'});

Disclaimer: I am the author of this plugin.

The opposite of Intersect()

I think you might be looking for Except:

The Except operator produces the set difference between two sequences. It will only return elements in the first sequence that don't appear in the second. You can optionally provide your own equality comparison function.

Check out this link, this link, or Google, for more information.

How to use jquery $.post() method to submit form values

You have to select and send the form data as well:

$("#post-btn").click(function(){        
    $.post("process.php", $("#reg-form").serialize(), function(data) {
        alert(data);
    });
});

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

How to get VM arguments from inside of Java application?

I found that HotSpot lists all the VM arguments in the management bean except for -client and -server. Thus, if you infer the -client/-server argument from the VM name and add this to the runtime management bean's list, you get the full list of arguments.

Here's the SSCCE:

import java.util.*;
import java.lang.management.ManagementFactory;

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

  static String fullVMArguments() {
    String name = javaVmName();
    return (contains(name, "Server") ? "-server "
      : contains(name, "Client") ? "-client " : "")
      + joinWithSpace(vmArguments());
  }

  static List<String> vmArguments() {
    return ManagementFactory.getRuntimeMXBean().getInputArguments();
  }

  static boolean contains(String s, String b) {
    return s != null && s.indexOf(b) >= 0;
  }

  static String javaVmName() {
    return System.getProperty("java.vm.name");
  }

  static String joinWithSpace(Collection<String> c) {
    return join(" ", c);
  }

  public static String join(String glue, Iterable<String> strings) {
    if (strings == null) return "";
    StringBuilder buf = new StringBuilder();
    Iterator<String> i = strings.iterator();
    if (i.hasNext()) {
      buf.append(i.next());
      while (i.hasNext())
        buf.append(glue).append(i.next());
    }
    return buf.toString();
  }
}

Could be made shorter if you want the arguments in a List<String>.

Final note: We might also want to extend this to handle the rare case of having spaces within command line arguments.

JPA Query selecting only specific columns without using Criteria Query?

Yes, it is possible. All you have to do is change your query to something like SELECT i.foo, i.bar FROM ObjectName i WHERE i.id = 10. The result of the query will be a List of array of Object. The first element in each array is the value of i.foo and the second element is the value i.bar. See the relevant section of JPQL reference.

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

I was facing a similar issue. Actually the command is :

java -version and not java --version.

You will get output something like this:

java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

Update MongoDB field using value of another field

Here's what we came up with for copying one field to another for ~150_000 records. It took about 6 minutes, but is still significantly less resource intensive than it would have been to instantiate and iterate over the same number of ruby objects.

js_query = %({
  $or : [
    {
      'settings.mobile_notifications' : { $exists : false },
      'settings.mobile_admin_notifications' : { $exists : false }
    }
  ]
})

js_for_each = %(function(user) {
  if (!user.settings.hasOwnProperty('mobile_notifications')) {
    user.settings.mobile_notifications = user.settings.email_notifications;
  }
  if (!user.settings.hasOwnProperty('mobile_admin_notifications')) {
    user.settings.mobile_admin_notifications = user.settings.email_admin_notifications;
  }
  db.users.save(user);
})

js = "db.users.find(#{js_query}).forEach(#{js_for_each});"
Mongoid::Sessions.default.command('$eval' => js)

SVG Positioning

As mentioned in the other comment, the transform attribute on the g element is what you want. Use transform="translate(x,y)" to move the g around and things within the g will move in relation to the g.

Get type of a generic parameter in Java with reflection

I want to try to break down the answer from @DerMike to explain:

First, type erasure does not mean that the JDK eliminates type information at runtime. It's a method for allowing compile-time type checking and runtime type compatibility to coexist in the same language. As this block of code implies, the JDK retains the erased type information--it's just not associated with checked casts and stuff.

Second, this provides generic type information to a generic class exactly one level up the heirarchy from the concrete type being checked--i.e. an abstract parent class with generic type parameters can find the concrete types corresponding to its type parameters for a concrete implementation of itself that directly inherits from it. If this class were non-abstract and instantiated, or the concrete implementation were two levels down, this wouldn't work (although a little bit of jimmying could make it apply to any predetermined number of levels beyond one, or up to the lowest class with X generic type parameters, et cetera).

Anyway, on to the explanation. Here's the code again, separated into lines for ease of reference:

1# Class genericParameter0OfThisClass = 
2#     (Class)
3#         ((ParameterizedType)
4#             getClass()
5#                .getGenericSuperclass())
6#                    .getActualTypeArguments()[0];

Let 'us' be the abstract class with generic types that contains this code. Reading this roughly inside out:

  • Line 4 gets the current concrete class' Class instance. This identifies our immediate descendant's concrete type.
  • Line 5 gets that class' supertype as a Type; this is us. Since we're a parametric type we can safely cast ourselves to ParameterizedType (line 3). The key is that when Java determines this Type object, it uses type information present in the child to associate type information with our type parameters in the new ParameterizedType instance. So now we can access concrete types for our generics.
  • Line 6 gets the array of types mapped into our generics, in order as declared in the class code. For this example we pull out the first parameter. This comes back as a Type.
  • Line 2 casts the final Type returned to a Class. This is safe because we know what types our generic type parameters are able to take and can confirm that they will all be classes (I'm not sure how in Java one would go about getting a generic parameter that doesn't have a Class instance associated with it, actually).

...and that's pretty much it. So we push type info from our own concrete implementation back into ourselves, and use it to access a class handle. we could double up getGenericSuperclass() and go two levels, or eliminate getGenericSuperclass() and get values for ourselves as a concrete type (caveat: I haven't tested these scenarios, they haven't come up for me yet).

It gets tricky if your concrete children are be an arbitrary number of hops away, or if you're concrete and not final, and especially tricky if you expect any of your (variably deep) children to have their own generics. But you can usually design around those considerations, so this gets you most of the way.

Hope this helped someone! I recognize this post is ancient. I'll probably snip this explanation and keep it for other questions.

Should I use alias or alias_method?

The rubocop gem contributors propose in their Ruby Style Guide:

Prefer alias when aliasing methods in lexical class scope as the resolution of self in this context is also lexical, and it communicates clearly to the user that the indirection of your alias will not be altered at runtime or by any subclass unless made explicit.

class Westerner
  def first_name
   @names.first
  end

 alias given_name first_name
end

Always use alias_method when aliasing methods of modules, classes, or singleton classes at runtime, as the lexical scope of alias leads to unpredictability in these cases

module Mononymous
  def self.included(other)
    other.class_eval { alias_method :full_name, :given_name }
  end
end

class Sting < Westerner
  include Mononymous
end

Can constructors be async?

if you make constructor asynchronous, after creating an object, you may fall into problems like null values instead of instance objects. For instance;

MyClass instance = new MyClass();
instance.Foo(); // null exception here

That's why they don't allow this i guess.

How can I force WebKit to redraw/repaint to propagate style changes?

Not that this question needs another answer, but I found simply changing the color by a single bit forced a repaint in my particular situation.

//Assuming black is the starting color, we tweak it by a single bit
elem.style.color = '#000001';

//Change back to black
setTimeout(function() {
    elem.style.color = '#000000';
}, 0);

The setTimeout proved critical to move the second style change outside the current event loop.

Postgres: INSERT if does not exist already

Here is a generic python function that given a tablename, columns and values, generates the upsert equivalent for postgresql.

import json

def upsert(table_name, id_column, other_columns, values_hash):

    template = """
    WITH new_values ($$ALL_COLUMNS$$) as (
      values
         ($$VALUES_LIST$$)
    ),
    upsert as
    (
        update $$TABLE_NAME$$ m
            set
                $$SET_MAPPINGS$$
        FROM new_values nv
        WHERE m.$$ID_COLUMN$$ = nv.$$ID_COLUMN$$
        RETURNING m.*
    )
    INSERT INTO $$TABLE_NAME$$ ($$ALL_COLUMNS$$)
    SELECT $$ALL_COLUMNS$$
    FROM new_values
    WHERE NOT EXISTS (SELECT 1
                      FROM upsert up
                      WHERE up.$$ID_COLUMN$$ = new_values.$$ID_COLUMN$$)
    """

    all_columns = [id_column] + other_columns
    all_columns_csv = ",".join(all_columns)
    all_values_csv = ','.join([query_value(values_hash[column_name]) for column_name in all_columns])
    set_mappings = ",".join([ c+ " = nv." +c for c in other_columns])

    q = template
    q = q.replace("$$TABLE_NAME$$", table_name)
    q = q.replace("$$ID_COLUMN$$", id_column)
    q = q.replace("$$ALL_COLUMNS$$", all_columns_csv)
    q = q.replace("$$VALUES_LIST$$", all_values_csv)
    q = q.replace("$$SET_MAPPINGS$$", set_mappings)

    return q


def query_value(value):
    if value is None:
        return "NULL"
    if type(value) in [str, unicode]:
        return "'%s'" % value.replace("'", "''")
    if type(value) == dict:
        return "'%s'" % json.dumps(value).replace("'", "''")
    if type(value) == bool:
        return "%s" % value
    if type(value) == int:
        return "%s" % value
    return value


if __name__ == "__main__":

    my_table_name = 'mytable'
    my_id_column = 'id'
    my_other_columns = ['field1', 'field2']
    my_values_hash = {
        'id': 123,
        'field1': "john",
        'field2': "doe"
    }
    print upsert(my_table_name, my_id_column, my_other_columns, my_values_hash)

Multiple submit buttons on HTML form – designate one button as default

If you're using jQuery, this solution from a comment made here is pretty slick:

$(function(){
    $('form').each(function () {
        var thisform = $(this);
        thisform.prepend(thisform.find('button.default').clone().css({
            position: 'absolute',
            left: '-999px',
            top: '-999px',
            height: 0,
            width: 0
        }));
    });
});

Just add class="default" to the button you want to be the default. It puts a hidden copy of that button right at the beginning of the form.

Checking character length in ruby

Instead of using a regular expression, just check if string.length > 25

Custom checkbox image android

Another option is to use a ToggleButton with null background and a custom button.

Bellow an example that includes a selector to the text color as well.

<ToggleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/toggle_selector"
    android:background="@null"
    android:paddingLeft="10dp"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:textColor="@drawable/toggle_text"
    android:textOn="My on state"
    android:textOff="My off state" />

toggle_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_checked="true"
        android:drawable="@drawable/state_on" />

    <item
        android:drawable="@drawable/state_off" />

</selector>

toggle_text.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_checked="true"
        android:color="@color/app_color" />

    <item
        android:color="@android:color/darker_gray" />

</selector>

Center text in table cell

I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:

.ui-helper-center {
    text-align: center;
}

And then add the ui-helper-center class to the table cells for which you wish to control the alignment:

<td class="ui-helper-center">Content</td>

EDIT: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.

See Gabe's answer for how to include the CSS rule into your page.

Read int values from a text file in C

How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2); 

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

Content-Disposition:What are the differences between "inline" and "attachment"?

If it is inline, the browser should attempt to render it within the browser window. If it cannot, it will resort to an external program, prompting the user.

With attachment, it will immediately go to the user, and not try to load it in the browser, whether it can or not.

Separators for Navigation

The other solution are OK, but there is no need to add separator at the very last if using :after or at the very beginning if using :before.

SO:

case :after

.link:after {
  content: '|';
  padding: 0 1rem;
}

.link:last-child:after {
  content: '';
}

case :before

.link:before {
  content: '|';
  padding: 0 1rem;
}

.link:first-child:before {
  content: '';
}

How to use Sublime over SSH

You can try something that I've been working on called 'xeno'. It will allow you to open up files/folders in Sublime Text (or any local editor really) over an SSH connection and automatically synchronize changes to the remote machine. It should work on almost all POSIX systems (I myself use it from OS X to connect to Linux machines and edit files in Sublime Text). It's free and open source. I'd love some feedback.

For more information: it's basically a Git/SSH mashup written in Python that allows you to edit files and folders on a remote machine in a local editor. You don't have to configure kernel modules, you don't need to have a persistent connection, it's all automatic, and it won't interfere with existing source control because it uses an out-of-worktree Git repository. Also, because it's built on Git, it's extremely fast and supports automatic merging of files that might be changing on both ends, unlike SSHFS/SFTP which will just clobber any files with older timestamps.

how to convert object into string in php

There is an object serialization module, with the serialize function you can serialize any object.

How to use font-awesome icons from node-modules

You have to set the proper font path. e.g.

my-style.scss

$fa-font-path:"../node_modules/font-awesome/fonts";
@import "../node_modules/font-awesome/scss/font-awesome";
.icon-user {
  @extend .fa;
  @extend .fa-user;
}

Gson: Is there an easier way to serialize a map

In Gson 2.7.2 it's as easy as

Gson gson = new Gson();
String serialized = gson.toJson(map);

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

When I was faced with the same problem I just had to clean my solution before rebuilding. That took care of it for me.

Minimum Hardware requirements for Android development

Have a look at the android SDK system requirements Here

I'm guessing some extra RAM would help your developing experience...Also the emulator does take some time to start on even the speediest systems.

Compute mean and standard deviation by group for multiple variables in a data.frame

Here's another take on the data.table answers, using @Carson's data, that's a bit more readable (and also a little faster, because of using lapply instead of sapply):

library(data.table)
set.seed(1)
dt = data.table(ID=c(1:3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

dt[, c(mean = lapply(.SD, mean), sd = lapply(.SD, sd)), by = ID]
#   ID mean.Obs_1 mean.Obs_2 mean.Obs_3  sd.Obs_1  sd.Obs_2  sd.Obs_3
#1:  1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
#2:  2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
#3:  3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

SQL Developer with JDK (64 bit) cannot find JVM

This is because sqldeveloper.conf has an entry for the java home being used

look at this solution

What does git push -u mean?

When you push a new branch the first time use: >git push -u origin

After that, you can just type a shorter command: >git push

The first-time -u option created a persistent upstream tracking branch with your local branch.

Java Singleton and Synchronization

Yes, you need to make getInstance() synchronized. If it's not there might arise a situation where multiple instances of the class can be made.

Consider the case where you have two threads that call getInstance() at the same time. Now imagine T1 executes just past the instance == null check, and then T2 runs. At this point in time the instance is not created or set, so T2 will pass the check and create the instance. Now imagine that execution switches back to T1. Now the singleton is created, but T1 has already done the check! It will proceed to make the object again! Making getInstance() synchronized prevents this problem.

There a few ways to make singletons thread-safe, but making getInstance() synchronized is probably the simplest.

How to disable the back button in the browser using JavaScript

Our approach is simple, but it works! :)

When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are on...simulating opening in new browser window without any history to go back to.

<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
    function logOut() {
        window.close = function () { 
            window.open('Default.aspx', '_blank'); 
        };
    }
</script>

Excel: Searching for multiple terms in a cell

Try using COUNT function like this

=IF(COUNT(SEARCH({"Romney","Obama","Gingrich"},C1)),1,"")

Note that you don't need the wildcards (as teylyn says) and unless there's a specific reason "1" doesn't need quotes (in fact that makes it a text value)

Calculate time difference in minutes in SQL Server

The following works as expected:

SELECT  Diff = CASE DATEDIFF(HOUR, StartTime, EndTime)
                    WHEN 0 THEN CAST(DATEDIFF(MINUTE, StartTime, EndTime) AS VARCHAR(10))
                    ELSE CAST(60 - DATEPART(MINUTE, StartTime) AS VARCHAR(10)) +
                        REPLICATE(',60', DATEDIFF(HOUR, StartTime, EndTime) - 1) + 
                        + ',' + CAST(DATEPART(MINUTE, EndTime) AS VARCHAR(10))
                END
FROM    (VALUES 
            (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
            (CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
            (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
        ) t (StartTime, EndTime);

To get 24 columns, you could use 24 case expressions, something like:

SELECT  [0] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 0
                        THEN DATEDIFF(MINUTE, StartTime, EndTime)
                    ELSE 60 - DATEPART(MINUTE, StartTime)
                END,
        [1] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 1 
                        THEN DATEPART(MINUTE, EndTime)
                    WHEN DATEDIFF(HOUR, StartTime, EndTime) > 1 THEN 60
                END,
        [2] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 2
                        THEN DATEPART(MINUTE, EndTime)
                    WHEN DATEDIFF(HOUR, StartTime, EndTime) > 2 THEN 60
                END -- ETC
FROM    (VALUES 
            (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
            (CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
            (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
        ) t (StartTime, EndTime);

The following also works, and may end up shorter than repeating the same case expression over and over:

WITH Numbers (Number) AS
(   SELECT  ROW_NUMBER() OVER(ORDER BY t1.N) - 1
    FROM    (VALUES (1), (1), (1), (1), (1), (1)) AS t1 (N)
            CROSS JOIN (VALUES (1), (1), (1), (1)) AS t2 (N)
), YourData AS
(   SELECT  StartTime, EndTime
    FROM    (VALUES 
                (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
                (CAST('09:45' AS TIME), CAST('18:59' AS TIME)),
                (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
            ) AS t (StartTime, EndTime)
), PivotData AS
(   SELECT  t.StartTime,
            t.EndTime,
            n.Number,
            MinuteDiff = CASE WHEN n.Number = 0 AND DATEDIFF(HOUR, StartTime, EndTime) = 0 THEN DATEDIFF(MINUTE, StartTime, EndTime)
                                WHEN n.Number = 0 THEN 60 - DATEPART(MINUTE, StartTime)
                                WHEN DATEDIFF(HOUR, t.StartTime, t.EndTime) <= n.Number THEN DATEPART(MINUTE, EndTime)
                                ELSE 60
                            END
    FROM    YourData AS t
            INNER JOIN Numbers AS n
                ON n.Number <= DATEDIFF(HOUR, StartTime, EndTime)
)
SELECT  *
FROM    PivotData AS d
        PIVOT 
        (   MAX(MinuteDiff)
            FOR Number IN 
            (   [0], [1], [2], [3], [4], [5], 
                [6], [7], [8], [9], [10], [11],
                [12], [13], [14], [15], [16], [17], 
                [18], [19], [20], [21], [22], [23]
            ) 
        ) AS pvt;

It works by joining to a table of 24 numbers, so the case expression doesn't need to be repeated, then rolling these 24 numbers back up into columns using PIVOT

Where will log4net create this log file?

For the log folder and file stuff, go with @Bens answer.

I will comment on the creating log part, though. Imo there is no correct way. When coding loggers manually I do it the way you're doing it:

ILog logger = LogManager.GetLogger(typeof(CCController));

because it is short and concise.

That said, I do not create the logger instances inside the classes these days, I let my IoC container inject it for me.

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

How to center horizontally div inside parent div

.parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child-canvas {
  flex-shrink: 0;
}

Image.open() cannot identify image file - Python?

Seems like a Permissions Issue. I was facing the same error. But when I ran it from the root account, it worked. So either give the read permission to the file using chmod (in linux) or run your script after logging in as a root user.

Storing a Key Value Array into a compact JSON string

If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"} is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.

For example:

var data = ["slide0001.html", "Looking Ahead"];

var C_KEY = 0;
var C_VALUE = 1;

var value = data[C_VALUE];

So, now, your data can be:

[
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
]

If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:

{ meta: { keys: [ "key", "value" ] },
  data: [
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
  ]
}

... which would then be handled by the parser.

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

Convert UTC to local time in Rails 3

Time#localtime will give you the time in the current time zone of the machine running the code:

> moment = Time.now.utc
  => 2011-03-14 15:15:58 UTC 
> moment.localtime
  => 2011-03-14 08:15:58 -0700 

Update: If you want to conver to specific time zones rather than your own timezone, you're on the right track. However, instead of worrying about EST vs EDT, just pass in the general Eastern Time zone -- it will know based on the day whether it is EDT or EST:

> Time.now.utc.in_time_zone("Eastern Time (US & Canada)")
  => Mon, 14 Mar 2011 11:21:05 EDT -04:00 
> (Time.now.utc + 10.months).in_time_zone("Eastern Time (US & Canada)")
  => Sat, 14 Jan 2012 10:21:18 EST -05:00 

How to set a reminder in Android?

You can use AlarmManager in coop with notification mechanism Something like this:

Intent intent = new Intent(ctx, ReminderBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
// time of of next reminder. Unix time.
long timeMs =...
if (Build.VERSION.SDK_INT < 19) {
    am.set(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
} else {
    am.setExact(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
}

It starts alarm.

public class ReminderBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(...)
                .setContentTitle(..)
                .setContentText(..);
        Intent intentToFire = new Intent(context, Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentToFire, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        NotificationManagerCompat.from(this);.notify((int) System.currentTimeMillis(), builder.build());
    }
}

How to get all keys with their values in redis

Use this script for redis >=5:

#!/bin/bash
redis-cli keys "*" > keys.txt
cat keys.txt | awk '{ printf "type %s\n", $1 }' | redis-cli > types.txt
paste -d'|' keys.txt types.txt | awk -F\| '
   $2 == "string"               { printf "echo \"KEY %s %s\"\nget %s\n", $1, $2, $1 }
   $2 == "list" || $2 == "set"  { printf "echo \"KEY %s %s\"\nsort %s by nosort\n", $1, $2, $1 }
   $2 == "hash"                 { printf "echo \"KEY %s %s\"\nhgetall %s\n", $1, $2, $1 }
   $2 == "zset"                 { printf "echo \"KEY %s %s\"\nzrange %s 0 -1 withscores\n", $1, $2,$1 }
' | redis-cli
rm keys.txt
rm types.txt

How do I specify the JDK for a GlassFish domain?

Here you can find how to set path to JDK for Glassfish: http://www.devdaily.com/blog/post/java/fixing-glassfish-jdk-path-problem-solved

Check

glassfish\config\asenv.bat

where java path is configured

REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16

How to read request body in an asp.net core webapi controller?

To be able to rewind the request body, @Jean's answer helped me come up with a solution that seems to work well. I currently use this for Global Exception Handler Middleware but the principle is the same.

I created a middleware that basically enables the rewind on the request body (instead of a decorator).

using Microsoft.AspNetCore.Http.Internal;
[...]
public class EnableRequestRewindMiddleware
{
    private readonly RequestDelegate _next;

    public EnableRequestRewindMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        context.Request.EnableRewind();
        await _next(context);
    }
}

public static class EnableRequestRewindExtension
{
    public static IApplicationBuilder UseEnableRequestRewind(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<EnableRequestRewindMiddleware>();
    }
}

This can then be used in your Startup.cs like so:

[...]
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    [...]
    app.UseEnableRequestRewind();
    [...]
}

Using this approach, I have been able to rewind the request body stream successfully.

Python Accessing Nested JSON Data

I'm using this lib to access nested dict keys

https://github.com/mewwts/addict

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number 

Efficient way to Handle ResultSet in Java

this is my alternative solution, instead of a List of Map, i'm using a Map of List. Tested on tables of 5000 elements, on a remote db, times are around 350ms for eiter method.

private Map<String, List<Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    Map<String, List<Object>> map = new HashMap<>(columns);
    for (int i = 1; i <= columns; ++i) {
        map.put(md.getColumnName(i), new ArrayList<>());
    }
    while (rs.next()) {
        for (int i = 1; i <= columns; ++i) {
            map.get(md.getColumnName(i)).add(rs.getObject(i));
        }
    }

    return map;
}

How do I delete all messages from a single queue using the CLI?

In case you are using RabbitMQ with Docker your steps should be:

  1. Connect to container: docker exec -it your_container_id bash
  2. rabbitmqctl purge_queue Queue-1 (where Queue-1 is queue name)

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

If the above methods don't work (as they didn't work on my Ubuntu 13.04 installation) try:

There are a number of alternative ways:

1) Run select-editor

select-editor

2) Manually edit the file: ~/.selected_editor specifying your preferred editor. With this option you can specify editor parameters.

# Generated by /usr/bin/select-editor
SELECTED_EDITOR="/usr/bin/emacs -nw"

3) You can specify on the fly on the commandline with:

env VISUAL="emacs -nw" crontab -e

Can't build create-react-app project with custom PUBLIC_URL

As documented here create-react-app will only import environment variables beginning with REACT_APP_, so the PUBLIC_URL, I believe, as mentioned by @redbmk, comes from the homepage setting in the package.json file.

Get folder name from full file path

Path.GetDirectoryName(@"c:\projects\roott\wsdlproj\devlop\beta2\text");

MSDN: Path.GetDirectoryName Method

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

This works for me:

static int id = 1;

// Returns a valid id that isn't in use
public int findId(){  
    View v = findViewById(id);  
    while (v != null){  
        v = findViewById(++id);  
    }  
    return id++;  
}

What is Func, how and when is it used

It is just a predefined generic delegate. Using it you don't need to declare every delegate. There is another predefined delegate, Action<T, T2...>, which is the same but returns void.

iOS how to set app icon and launch images

As per updated version(Xcode 8.3.3) I saw that below resolution are required for all fields of AppIcon sets.

40x40
58x58
60x60
80x80
87x87
120x120
180x180

It comes with hdpi, xhdpi, xxhdpi etc. Hope it will helps others.

Edited to 120x120

Drop view if exists

DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS 
SELECT * from {TableName}  
Go

jQuery UI - Close Dialog When Clicked Outside

Smart Code: I am using following code so that every thing remains clear and readable. out side body will close the dialog box.

$(document).ready(function () {
   $('body').on('click', '.ui-widget-overlay', closeDialogBox);
});

function closeDialogBox() {
    $('#dialog-message').dialog('close');
}

How to disable "prevent this page from creating additional dialogs"?

You should better use jquery-confirm rather than trying to remove that checkbox.

$.confirm({
    title: 'Confirm!',
    content: 'Are you sure you want to refund invoice ?',
    confirm: function(){
       //do something 
    },
    cancel: function(){
       //do something
    }
}); 

What is the difference between 'git pull' and 'git fetch'?

Git Fetch

Helps you to get known about the latest updates from a git repository. Let's say you working in a team using GitFlow, where team working on multiple branches ( features ). With git fetch --all command you can get known about all new branches within repository.

Mostly git fetch is used with git reset. For example you want to revert all your local changes to the current repository state.

git fetch --all // get known about latest updates
git reset --hard origin/[branch] // revert to current branch state

Git pull

This command update your branch with current repository branch state. Let's continue with GitFlow. Multiple feature branches was merged to develop branch and when you want to develop new features for the project you must go to the develop branch and do a git pull to get the current state of develop branch

Documentation for GitFlow https://gist.github.com/peterdeweese/4251497

How to change the value of ${user} variable used in Eclipse templates

Windows > Preferences > Java > Code Style > Code Templates > Comments

enter image description here

Or Open eclipse.ini file and add following.

-Duser.name=Sumit Singh // Your Name

enter image description here

Convert an integer to an array of digits

I can suggest the following method:

Convert the number to a string ? convert the string into an array of characters ? convert the array of characters into an array of integers

Here comes my code:

public class test {

    public static void main(String[] args) {

        int num1 = 123456; // Example 1
        int num2 = 89786775; // Example 2

        String str1 = Integer.toString(num1); // Converts num1 into String
        String str2 = Integer.toString(num2); // Converts num2 into String

        char[] ch1 = str1.toCharArray(); // Gets str1 into an array of char
        char[] ch2 = str2.toCharArray(); // Gets str2 into an array of char

        int[] t1 = new int[ch1.length]; // Defines t1 for bringing ch1 into it
        int[] t2 = new int[ch2.length]; // Defines t2 for bringing ch2 into it

        for(int i=0;i<ch1.length;i++) // Watch the ASCII table
            t1[i]= (int) ch1[i]-48; // ch1[i] is 48 units more than what we want

        for(int i=0;i<ch2.length;i++) // Watch the ASCII table
            t2[i]= (int) ch2[i]-48; // ch2[i] is 48 units more than what we want
        }
    }

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

I was getting the error “gcc: error: x86_64-linux-gnu-gcc: No such file or directory” as I was trying to build a simple c-extension module to run in Python. I tried all the things above to no avail, and finally realized that I had an error in my module.c code! So I thought it would be helpful to add that, if you are getting this error message but you have python-dev and everything correctly installed, you should look for issues in your code.

Android ImageView setImageResource in code

One easy way to map that country name that you have to an int to be used in the setImageResource method is:

int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);

But you should really try to use different folders resources for the countries that you want to support.

"Please provide a valid cache path" error in laravel

/path/to/laravel/storage/framework/

sessions views cache

Above is working solution

How to create JSON object Node.js

The other answers are helpful, but the JSON in your question isn't valid. I have formatted it to make it clearer below, note the missing single quote on line 24.

  1 {
  2     'Orientation Sensor':
  3     [
  4         {
  5             sampleTime: '1450632410296',
  6             data: '76.36731:3.4651554:0.5665419'
  7         },
  8         {
  9             sampleTime: '1450632410296',
 10             data: '78.15431:0.5247617:-0.20050584'
 11         }
 12     ],
 13     'Screen Orientation Sensor':
 14     [
 15         {
 16             sampleTime: '1450632410296',
 17             data: '255.0:-1.0:0.0'
 18         }
 19     ],
 20     'MPU6500 Gyroscope sensor UnCalibrated':
 21     [
 22         {
 23             sampleTime: '1450632410296',
 24             data: '-0.05006743:-0.013848438:-0.0063915867
 25         },
 26         {
 27             sampleTime: '1450632410296',
 28             data: '-0.051132694:-0.0127831735:-0.003325345'
 29         }
 30     ]
 31 }

There are a lot of great articles on how to manipulate objects in Javascript (whether using Node JS or a browser). I suggest here is a good place to start: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Setting up Gradle for api 26 (Android)

you must add in your MODULE-LEVEL build.gradle file with:

//module-level build.gradle file
repositories {
    maven {
        url 'https://maven.google.com'

    }
}

see: Google's Maven repository

I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url 'https://maven.google.com'}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:

//project-level build.gradle file
allprojects {
 repositories {
    jcenter()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
  }
}

UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0

Make an HTTP request with android

private String getToServer(String service) throws IOException {
    HttpGet httpget = new HttpGet(service);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    return new DefaultHttpClient().execute(httpget, responseHandler);

}

Regards

How to listen for changes to a MongoDB collection?

After 3.6 one is allowed to use database the following database triggers types:

  • event-driven triggers - useful to update related documents automatically, notify downstream services, propagate data to support mixed workloads, data integrity & auditing
  • scheduled triggers - useful for scheduled data retrieval, propagation, archival and analytics workloads

Log into your Atlas account and select Triggers interface and add new trigger:

enter image description here

Expand each section for more settings or details.

Rules for C++ string literals escape character

\0 will be interpreted as an octal escape sequence if it is followed by other digits, so \00 will be interpreted as a single character. (\0 is technically an octal escape sequence as well, at least in C).

The way you're doing it:

std::string ("0\0" "0", 3)  // String concatenation 

works because this version of the constructor takes a char array; if you try to just pass "0\0" "0" as a const char*, it will treat it as a C string and only copy everything up until the null character.

Here is a list of escape sequences.

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014

Just be sure to be using correct instance and connect each other

Just pay attention in Stored procs must be recompiled

Formatting floats without trailing zeros

"{:.5g}".format(x)

I use this to format floats to trail zeros.

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

My issue was caused by other application using the .dll file I was trying to debug.

Closing the application that was using the .dll solved it for me.

DataSet panel (Report Data) in SSRS designer is gone

With a .rdl, .rdlc or similar file selected, you can either:

  • Click View -> Report Data or...
  • Use the keyboard shortcut CTRL + ALT + D

Example

Color a table row with style="color:#fff" for displaying in an email

Rather than using direct tags, you can edit the css attribute for the color so that any tables you make will have the same color header text.

thead {
    color: #FFFFFF;
}

Batch file to run a command in cmd within a directory

For me, the following is working and running activiti server as well as opening the explorer in browser (with the help of zb226's answer and comment);

START "runas /user:administrator" cmd /K "cd C:\activiti-5.9\setup & ant demo.start"

START /wait localhost:8080/activiti-explorer

ConnectionTimeout versus SocketTimeout

A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.

A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.

By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!

If only the incoming stream stalls for more than a millisecond you are running into a timeout.

How to create a file name with the current date & time in Python?

This prints in an easy to read format -

import datetime

time_now  = datetime.datetime.now().strftime('%m_%d_%Y_%H_%M_%S') 

print(time_now)

Output: 02_03_2021_22_44_50

How to insert DECIMAL into MySQL database

MySql decimal types are a little bit more complicated than just left-of and right-of the decimal point.

The first argument is precision, which is the number of total digits. The second argument is scale which is the maximum number of digits to the right of the decimal point.

Thus, (4,2) can be anything from -99.99 to 99.99.

As for why you're getting 99.99 instead of the desired 3.80, the value you're inserting must be interpreted as larger than 99.99, so the max value is used. Maybe you could post the code that you are using to insert or update the table.

Edit

Corrected a misunderstanding of the usage of scale and precision, per http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html.

Correlation heatmap

Another alternative is to use the heatmap function in seaborn to plot the covariance. This example uses the Auto data set from the ISLR package in R (the same as in the example you showed).

import pandas.rpy.common as com
import seaborn as sns
%matplotlib inline

# load the R package ISLR
infert = com.importr("ISLR")

# load the Auto dataset
auto_df = com.load_data('Auto')

# calculate the correlation matrix
corr = auto_df.corr()

# plot the heatmap
sns.heatmap(corr, 
        xticklabels=corr.columns,
        yticklabels=corr.columns)

enter image description here

If you wanted to be even more fancy, you can use Pandas Style, for example:

cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)

def magnify():
    return [dict(selector="th",
                 props=[("font-size", "7pt")]),
            dict(selector="td",
                 props=[('padding', "0em 0em")]),
            dict(selector="th:hover",
                 props=[("font-size", "12pt")]),
            dict(selector="tr:hover td:hover",
                 props=[('max-width', '200px'),
                        ('font-size', '12pt')])
]

corr.style.background_gradient(cmap, axis=1)\
    .set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
    .set_caption("Hover to magify")\
    .set_precision(2)\
    .set_table_styles(magnify())

enter image description here

ADB No Devices Found

On my Windows 8.1 64bit (Nexus 5 did not show up), only manually installing the USB driver fixed it: http://developer.android.com/sdk/win-usb.html The "Google USB Driver" in "Android SDK Manager" was installed already.

Python locale error: unsupported locale setting

More permanent solution would be to fill the missing values, in the output shown by command: locale

Output from locale is:

 $ locale
LANG=en_US.utf8
LANGUAGE=
LC_CTYPE="en_US.utf8"
LC_NUMERIC=es_ES.utf8
LC_TIME=es_ES.utf8
LC_COLLATE="en_US.utf8"
LC_MONETARY=es_ES.utf8
LC_MESSAGES="en_US.utf8"
LC_PAPER=es_ES.utf8
LC_NAME="en_US.utf8"
LC_ADDRESS="en_US.utf8"
LC_TELEPHONE="en_US.utf8"
LC_MEASUREMENT=es_ES.utf8
LC_IDENTIFICATION="en_US.utf8"
LC_ALL=

To Fill the missing values edit ~/.bashrc :

 $ vim ~/.bashrc

Add the following lines after the above command (suppose you want en_US.UTF-8 to be your language):

export LANGUAGE="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"

If this file is ReadOnly you would be needing to follow the steps mentioned by The GeekyBoy. The answer given by Dr Beco in Superuser has details relating to saving readonly files.

After saving the file do:

$ source ~/.bashrc

Now you wont be facing the same problem anymore.

Why use multiple columns as primary keys (composite primary key)

Your second question

How many columns can be used together as a primary key in a given table?

is implementation specific: it's defined in the actual DBMS being used.[1],[2],[3] You have to inspect the technical specification of the database system you use. Some are very detailed, some are not. Searching the web about such limitations can be hard because the terminology varies. The term composite primary key should be mandatory ;)

If you cannot find explicit information, try creating a test database to ensure you can expect stable (and specific) handling of the limit violations (which are to be expected). Be careful to get the right information about this: sometimes the limits are accumulated, and you'll see different results with different database layouts.


Reading input files by line using read command in shell scripting skips last line

Use while loop like this:

while IFS= read -r line || [ -n "$line" ]; do
  echo "$line"
done <file

Or using grep with while loop:

while IFS= read -r line; do
  echo "$line"
done < <(grep "" file)

Using grep . instead of grep "" will skip the empty lines.

Note:

  1. Using IFS= keeps any line indentation intact.

  2. You should almost always use the -r option with read.

  3. Don't read lines with for

  4. File without a newline at the end isn't a standard unix text file.

Java decimal formatting using String.format?

Here is a small code snippet that does the job:

double a = 34.51234;

NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setRoundingMode(RoundingMode.DOWN);

System.out.println(df.format(a));

Using OpenSSL what does "unable to write 'random state'" mean?

Apparently, I needed to run OpenSSL as root in order for it to have permission to the seeding file.

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

"config": {
  "platform": {
    "ext-pcntl": "7.2",
    "ext-posix": "7.2"
  }
}

u'\ufeff' in Python string

I ran into this on Python 3 and found this question (and solution). When opening a file, Python 3 supports the encoding keyword to automatically handle the encoding.

Without it, the BOM is included in the read result:

>>> f = open('file', mode='r')
>>> f.read()
'\ufefftest'

Giving the correct encoding, the BOM is omitted in the result:

>>> f = open('file', mode='r', encoding='utf-8-sig')
>>> f.read()
'test'

Just my 2 cents.

Why has it failed to load main-class manifest attribute from a JAR file?

I'm not sure I believe your symptoms:

  • If the jre command isn't found, then running jre -cp app.jar should give the same error
  • Just adding a JAR file to the classpath shouldn't give the error you're seeing

I'd expect you to see this error if you run:

java -jar app.jar

The Main-Class header needs to be in the manifest for the JAR file - this is metadata about things like other required libraries. See the Sun documentation for how to create an appropriate manifest. Basically you need to create a text file which includes a line like this:

Main-Class: MainClass

Then run

jar cfm app.jar manifest.txt *.class

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

While editing include the id or primary key of the entity as a hidden field in the view

ie

      @Html.HiddenFor(m => m.Id)

that solves the problem.

Also if your model includes non-used item include that too and post that to the controller

SQL: set existing column as Primary Key in MySQL

Either run in SQL:

ALTER TABLE tableName
  ADD PRIMARY KEY (id)           ---or Drugid, whichever you want it to be PK

or use the PHPMyAdmin interface (Table Structure)

What is SuppressWarnings ("unchecked") in Java?

A warning by which the compiler indicates that it cannot ensure type safety. The term "unchecked" warning is misleading. It does not mean that the warning is unchecked in any way. The term "unchecked" refers to the fact that the compiler and the runtime system do not have enough type information to perform all type checks that would be necessary to ensure type safety. In this sense, certain operations are "unchecked".

The most common source of "unchecked" warnings is the use of raw types. "unchecked" warnings are issued when an object is accessed through a raw type variable, because the raw type does not provide enough type information to perform all necessary type checks.

Example (of unchecked warning in conjunction with raw types):

TreeSet set = new TreeSet(); 
set.add("abc");        // unchecked warning 
set.remove("abc");
warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.TreeSet 
               set.add("abc");  
                      ^

When the add method is invoked the compiler does not know whether it is safe to add a String object to the collection. If the TreeSet is a collection that contains String s (or a supertype thereof), then it would be safe. But from the type information provided by the raw type TreeSet the compiler cannot tell. Hence the call is potentially unsafe and an "unchecked" warning is issued.

"unchecked" warnings are also reported when the compiler finds a cast whose target type is either a parameterized type or a type parameter.

Example (of an unchecked warning in conjunction with a cast to a parameterized type or type variable):

  class Wrapper<T> { 
  private T wrapped ; 
  public Wrapper (T arg) {wrapped = arg;} 
  ... 
  public Wrapper <T> clone() { 
    Wrapper<T> clon = null; 
     try {  
       clon = (Wrapper<T>) super.clone(); // unchecked warning 
     } catch (CloneNotSupportedException e) {  
       throw new InternalError();  
     } 
     try {  
       Class<?> clzz = this.wrapped.getClass(); 
       Method   meth = clzz.getMethod("clone", new Class[0]); 
       Object   dupl = meth.invoke(this.wrapped, new Object[0]); 
       clon.wrapped = (T) dupl; // unchecked warning 
     } catch (Exception e) {} 
     return clon; 
  } 
} 
warning: [unchecked] unchecked cast 
found   : java.lang.Object 
required: Wrapper <T> 
                  clon = ( Wrapper <T>)super.clone();  
                                                ^ 
warning: [unchecked] unchecked cast 
found   : java.lang.Object 
required: T 
                  clon. wrapped = (T)dupl;

A cast whose target type is either a (concrete or bounded wildcard) parameterized type or a type parameter is unsafe, if a dynamic type check at runtime is involved. At runtime, only the type erasure is available, not the exact static type that is visible in the source code. As a result, the runtime part of the cast is performed based on the type erasure, not on the exact static type.

In the example, the cast to Wrapper would check whether the object returned from super.clone is a Wrapper , not whether it is a wrapper with a particular type of members. Similarly, the casts to the type parameter T are cast to type Object at runtime, and probably optimized away altogether. Due to type erasure, the runtime system is unable to perform more useful type checks at runtime.

In a way, the source code is misleading, because it suggests that a cast to the respective target type is performed, while in fact the dynamic part of the cast only checks against the type erasure of the target type. The "unchecked" warning is issued to draw the programmer's attention to this mismatch between the static and dynamic aspect of the cast.

Please refer: What is an "unchecked" warning?

How to prevent multiple definitions in C?

If you have added test.c to your Code::Blocks project, the definition will be seen twice - once via the #include and once by the linker. You need to:

  • remove the #include "test.c"
  • create a file test.h which contains the declaration: void test();
  • include the file test.h in main.c

jQuery - Redirect with post data

I included the jquery.redirect.min.js plugin in the head section together with this json solution to submit with data

<script type="text/javascript">     
    $(function () {
     $('form').on('submit', function(e) {
       $.ajax({
        type: 'post',
        url: 'your_POST_URL',
        data: $('form').serialize(),
        success: function () {
         // now redirect
         $().redirect('your_POST_URL', {
          'input1': $("value1").val(), 
          'input2': $("value2").val(),
      'input3': $("value3").val()
       });
      }
   });
   e.preventDefault();
 });
 });
 </script>

Then immediately after the form I added

 $(function(){
     $( '#your_form_Id' ).submit();
    });