Programs & Examples On #Numericstepper

How to stop (and restart) the Rails Server?

if you are not able to find the rails process to kill it might actually be not running. Delete the tmp folder and its sub-folders from where you are running the rails server and try again.

Capture Image from Camera and Display in Activity

Here you can open camera or gallery and set the selected image into imageview

private static final String IMAGE_DIRECTORY = "/YourDirectName";
private Context mContext;
private CircleImageView circleImageView;  // imageview
private int GALLERY = 1, CAMERA = 2;

Add permissions in manifest

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

In onCreate()

    requestMultiplePermissions(); // check permission 

    circleImageView = findViewById(;
    circleImageView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

Show options dialog box (to select image from camera or gallery)

private void showPictureDialog() {
    AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
    pictureDialog.setTitle("Select Action");
    String[] pictureDialogItems = {"Select photo from gallery", "Capture photo from camera"};
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                        case 1:

Get photo from Gallery

public void choosePhotoFromGallary() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent, GALLERY);

Get photo from Camera

private void takePhotoFromCamera() {
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAMERA);

Once the image is get selected or captured then ,

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == this.RESULT_CANCELED) {
    if (requestCode == GALLERY) {
        if (data != null) {
            Uri contentURI = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
                String path = saveImage(bitmap);
                Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();

            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();

    } else if (requestCode == CAMERA) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();

Now its time to store the picture

public String saveImage(Bitmap myBitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
    File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
    if (!wallpaperDirectory.exists()) {  // have the object build the directory structure, if needed.

    try {
        File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
        FileOutputStream fo = new FileOutputStream(f);
                new String[]{f.getPath()},
                new String[]{"image/jpeg"}, null);
        Log.d("TAG", "File Saved::---&gt;" + f.getAbsolutePath());

        return f.getAbsolutePath();
    } catch (IOException e1) {
    return "";

Request permission

    private void requestMultiplePermissions() {
            .withListener(new MultiplePermissionsListener() {
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {  // check if all permissions are granted
                        Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();

                    if (report.isAnyPermissionPermanentlyDenied()) { // check for permanent denial of any permission
                        // show alert dialog navigating to Settings

                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
            withErrorListener(new PermissionRequestErrorListener() {
                public void onError(DexterError error) {
                    Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();

change html text from link with jquery

You need J-query library to do this simply:

<script src="//"></script>

First you need to put your element in div like this:

<div id="divClickHere">
<a id="a_tbnotesverbergen" href="#nothing">click here</a>

Then you should write this J-Query Code:

<script type="text/javascript">
$("#divClickHere a").text('Your new text');

send checkbox value in PHP form

Here's how it should look like in order to return a simple Yes when it's checked.

<input type="checkbox" id="newsletter" name="newsletter" value="Yes" checked>
<label for="newsletter">i want to sign up for newsletter</label>

I also added the text as a label, it means you can click the text as well to check the box. Small but, personally I hate when sites make me aim my mouse at this tiny little check box.

When the form is submitted if the check box is checked $_POST['newsletter'] will equal Yes. Just how you are checking to see if $_POST['name'],$_POST['email'], and $_POST['tel'] are empty you could do the same.

Here is an example of how you would add this into your email on the php side:

Underneath your existing code:

$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];


$newsletter = $_POST['newsletter'];
if ($newsletter != 'Yes') {
    $newsletter = 'No';

If the check box is checked it will add Yes in your email if it was not checked it will add No.

Select rows of a matrix that meet a condition

If your matrix is called m, just use :

R> m[m$three == 11, ]

MySQL : transaction within a stored procedure

Just an alternative to the code by rkosegi,


    .. Declare statements ..

          .. set any flags etc  eg. SET @flag = 0; ..


        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    .. eg. SET @flag = 1; ..


Field 'browser' doesn't contain a valid alias configuration

In my case, to the very end of the webpack.config.js, where I should exports the config, there was a typo: export(should be exports), which led to failure with loading webpack.config.js at all.

const path = require('path');

const config = {
    mode: 'development',
    entry: "./lib/components/Index.js",
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'bundle.js'
    module: {
        rules: [
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: path.resolve(__dirname, "node_modules")

// pay attention to "export!s!" here
module.exports = config;

How to get the return value from a thread in python?

One usual solution is to wrap your function foo with a decorator like

result = queue.Queue()

def task_wrapper(*args):

Then the whole code may looks like that

result = queue.Queue()

def task_wrapper(*args):

threads = [threading.Thread(target=task_wrapper, args=args) for args in args_list]

for t in threads:
        if(len(threading.enumerate()) < max_num):
for t in threads:
return result


One important issue is that the return values may be unorderred. (In fact, the return value is not necessarily saved to the queue, since you can choose arbitrary thread-safe data structure )

How to load a xib file in a UIView

To get an object from a xib file programatically you can use: [[NSBundle mainBundle] loadNibNamed:@"MyXibName" owner:self options:nil] which returns an array of the top level objects in the xib.

So, you could do something like this:

UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:@"MyRootView" owner:self options:nil] objectAtIndex:0];
UIView *containerView = [[[NSBundle mainBundle] loadNibNamed:@"MyContainerView" owner:self options:nil] lastObject];
[rootView addSubview:containerView];
[self.view addSubview:rootView];

select dept names who have more than 2 employees whose salary is greater than 1000

My main advice would be to steer clear of the HAVING clause (see below):

WITH HighEarners AS
     ( SELECT EmpId, DeptId
        WHERE Salary > 1000 ), 
     DeptmentHighEarnerTallies AS 
     ( SELECT DeptId, COUNT(*) AS HighEarnerTally
         FROM HighEarners
           BY DeptId )
 WHERE HighEarnerTally > 2;

The very early SQL implementations lacked derived tables and HAVING was a workaround for one of its most obvious drawbacks (how to select on the result of a set function from the SELECT clause). Once derived tables had become a thing, the need for HAVING went away. Sadly, HAVING itself didn't go away (and never will) because nothing is ever removed from standard SQL. There is no need to learn HAVING and I encourage fledgling coders to avoid using this historical hangover.

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

For add new PCH file follow bellow steps :

(1) Add New fiew - Select iOS - Other and PCH File

(2) add path of this PCH file to your Project - BuildSetting - Apple LLVM 6.0 Language

Add Set Prefix Header Path YourApplicationName(root-path)/filename.pch

Using jQuery to programmatically click an <a> link

Try this for compatibility;

<script type="text/javascript">
        $(function() {
            setTimeout(function() {
                window.location.href = $('#myAnchor').attr("href");

            }, 1500);

Problems when trying to load a package in R due to rJava

The reason is probably linked to the fact you are using a 64-bit OS and R version but do not have Java installed with the same architecture. What you have to do is to download Java 64-bit from this page:

After that just try to reload the xlsx package. You shouldn't need to re-start R.

application/x-www-form-urlencoded or multipart/form-data?

I agree with much that Manuel has said. In fact, his comments refer to this url...

... which states:

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

However, for me it would come down to tool/framework support.

  • What tools and frameworks do you expect your API users to be building their apps with?
  • Do they have frameworks or components they can use that favour one method over the other?

If you get a clear idea of your users, and how they'll make use of your API, then that will help you decide. If you make the upload of files hard for your API users then they'll move away, of you'll spend a lot of time on supporting them.

Secondary to this would be the tool support YOU have for writing your API and how easy it is for your to accommodate one upload mechanism over the other.

Align image to left of text on same line - Twitter Bootstrap3

Use Nesting column

To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or fewer (it is not required that you use all 12 available columns).

enter image description here

<div class="row">_x000D_
  <div class="col-sm-9">_x000D_
    Level 1: .col-sm-9_x000D_
    <div class="row">_x000D_
      <div class="col-xs-8 col-sm-6">_x000D_
        Level 2: .col-xs-8 .col-sm-6_x000D_
      <div class="col-xs-4 col-sm-6">_x000D_
        Level 2: .col-xs-4 .col-sm-6_x000D_

async at console app in C#?

My solution. The JSONServer is a class I wrote for running an HttpListener server in a console window.

class Program
    public static JSONServer srv = null;

    static void Main(string[] args)
        Console.WriteLine("NLPS Core Server");

        srv = new JSONServer(100);




    private static async Task InputLoopProcessor()
        string line = "";

        Console.WriteLine("Core NLPS Server: Started on port 8080. " + DateTime.Now);

        while(line != "quit")
            Console.Write(": ");
            line = Console.ReadLine().ToLower();

            if(line == "?" || line == "help")
                Console.WriteLine("Core NLPS Server Help");
                Console.WriteLine("    ? or help: Show this help.");
                Console.WriteLine("    quit: Stop the server.");
        Console.WriteLine("Core Processor done at " + DateTime.Now);


ng-repeat finish event

Complementing Pavel's answer, something more readable and easily understandable would be:

    <li ng-repeat="item in items" 
        ng-init="$last ? doSomething() : angular.noop()">{{item}}</li>

Why else do you think angular.noop is there in the first place...?


You don't have to write a directive for this...

Angular ReactiveForms: Producing an array of checkbox values?

If you want to use an Angular reactive form (

You can use one form control to manage the outputted value of the group of checkboxes.


import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { flow } from 'lodash';
import { flatMap, filter } from 'lodash/fp';

  selector: 'multi-checkbox',
  templateUrl: './multi-checkbox.layout.html',
export class MultiChecboxComponent  {

  checklistState = [ 
        label: 'Frodo Baggins',
        value: 'frodo_baggins',
        checked: false
        label: 'Samwise Gamgee',
        value: 'samwise_gamgee',
        checked: true,
        label: 'Merry Brandybuck',
        value: 'merry_brandybuck',
        checked: false

  form = new FormGroup({
    checklist : new FormControl(this.flattenValues(this.checklistState)),

  checklist = this.form.get('checklist');

  onChecklistChange(checked, checkbox) {
    checkbox.checked = checked;

  flattenValues(checkboxes) {
    const flattenedValues = flow([
      filter(checkbox => checkbox.checked),
      flatMap(checkbox => checkbox.value )
    return flattenedValues.join(',');


<form [formGroup]="form">
    <label *ngFor="let checkbox of checklistState" class="checkbox-control">
    <input type="checkbox" (change)="onChecklistChange($, checkbox)" [checked]="checkbox.checked" [value]="checkbox.value" /> {{ checkbox.label }}


Manages the model/state of the checklist inputs. This model allows you to map the current state to whatever value format you need.


   label: 'Value 1',
   value: 'value_1',
   checked: false
  label: 'Samwise Gamgee',
  value: 'samwise_gamgee',
  checked: true,
  label: 'Merry Brandybuck',
  value: 'merry_brandybuck',
  checked: false

checklist Form Control

This control stores the value would like to save as e.g

value output: "value_1,value_2"

See demo at

How to delete columns that contain ONLY NAs?

It seeems like you want to remove ONLY columns with ALL NAs, leaving columns with some rows that do have NAs. I would do this (but I am sure there is an efficient vectorised soution:

#set seed for reproducibility
set.seed <- 103
df <- data.frame( id = 1:10 , nas = rep( NA , 10 ) , vals = sample( c( 1:3 , NA ) , 10 , repl = TRUE ) )
#      id nas vals
#   1   1  NA   NA
#   2   2  NA    2
#   3   3  NA    1
#   4   4  NA    2
#   5   5  NA    2
#   6   6  NA    3
#   7   7  NA    2
#   8   8  NA    3
#   9   9  NA    3
#   10 10  NA    2

#Use this command to remove columns that are entirely NA values, it will elave columns where only some vlaues are NA
df[ , ! apply( df , 2 , function(x) all( ) ]
#      id vals
#   1   1   NA
#   2   2    2
#   3   3    1
#   4   4    2
#   5   5    2
#   6   6    3
#   7   7    2
#   8   8    3
#   9   9    3
#   10 10    2

If you find yourself in the situation where you want to remove columns that have any NA values you can simply change the all command above to any.

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices

For more information on the format models you can use with TO_CHAR on a date, see

Convert number to month name in PHP


$name = jdmonthname(gregoriantojd($monthNumber, 1, 1), CAL_MONTH_GREGORIAN_LONG);

Best way to test if a row exists in a MySQL table

Suggest you not to use Count because count always makes extra loads for db use SELECT 1 and it returns 1 if your record right there otherwise it returns null and you can handle it.


You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).

We've been seeking for official data feed providing for our fantasy games ( and still staying with stats-com mainly (used opta, datafactory as well)

How to select id with max date group by category in PostgreSQL?

Try this one:

SELECT t1.* FROM Table1 t1
   SELECT category, MAX(date) AS MAXDATE
   FROM Table1
   GROUP BY category
) t2
ON T1.category = t2.category

See this SQLFiddle

Android Percentage Layout Height

Just as you said, I'd recommend weights. Percentages would be incredibly useful (don't know why they aren't supported), but one way you could do it is like so:


The takeaway being that you have an empty View that will take up the remaining space. Not ideal, but it does what you're looking for.

Jackson enum Serializing and DeSerializer

Here is another example that uses string values instead of a map.

public enum Operator {
    EQUAL(new String[]{"=","==","==="}),
    NOT_EQUAL(new String[]{"!=","<>"}),
    LESS_THAN(new String[]{"<"}),
    LESS_THAN_EQUAL(new String[]{"<="}),
    GREATER_THAN(new String[]{">"}),
    GREATER_THAN_EQUAL(new String[]{">="}),
    EXISTS(new String[]{"not null", "exists"}),
    NOT_EXISTS(new String[]{"is null", "not exists"}),
    MATCH(new String[]{"match"});

    private String[] value;

    Operator(String[] value) {
        this.value = value;

    public String toStringOperator(){
        return value[0];

    public static Operator fromStringOperator(String stringOperator) {
        if(stringOperator != null) {
            for(Operator operator : Operator.values()) {
                for(String operatorString : operator.value) {
                    if (stringOperator.equalsIgnoreCase(operatorString)) {
                        return operator;
        return null;

How to close the current fragment by using Button like the back button?

I change the code from getActivity().getFragmentManager().beginTransaction().remove(this).commit();



And it can close the fragment.

Spark Dataframe distinguish columns with duplicated name

Suppose the DataFrames you want to join are df1 and df2, and you are joining them on column 'a', then you have 2 methods

Method 1


This is an awsome method and it is highly recommended.

Method 2

df1.join(df2,df1.a == df2.a,'left_outer').drop(df2.a)

How to extract string following a pattern with grep, regex or perl

If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use to create a file object that'll encode for you as you write to the file:

import io

f =, 'w', encoding='utf8')

You may want to read:

before continuing.

Bootstrap 3 Horizontal and Vertical Divider

I know this is an "older" post. This question and the provided answers helped me get ideas for my own problem. I think this solution addresses the OP question (intersecting borders with 4 and 2 columns depending on display)


css based on OP information, media query at end is for med & lg view.

.vr-all {
    border-right:1px solid #CC0000;
.vr-xs {
.vr-md {
.hrspacing { padding:0px; }
.hrcolor {
    border-color: #CC0000;
    border-style: solid;
    border-bottom: 1px;
/* for medium and up */
    .vr-xs {
        border-right:1px solid #CC0000;

html adjustments to OP provided code. Red border and Img links for example.

<div class="container">
  <div class="row">
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="one">
            <h5>Rich Media Ad Production</h5>
            <img src="" />
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="two">
            <h5>Web Design & Development</h5>
            <img src="" >

        <!-- hr for only x-small/small viewports -->
        <div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="three">
            <h5>Mobile Apps Development</h5>
            <img src="" >
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="four">
            <h5>Creative Design</h5>
            <img src="" >

        <!-- hr for for all viewports -->
        <div class="col-xs-12 hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="five">
            <h5>Web Analytics</h5>
            <img src="" >
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="six">
            <h5>Search Engine Marketing</h5>
            <img src="" >

        <!-- hr for only x-small/small viewports -->
        <div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="seven">
            <h5>Mobile Apps Development</h5>
            <img src="" >
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="eight">
            <h5>Quality Assurance</h5>
            <img src="" >


How to find the mysql data directory from command line in windows

You can see the complete list of MySQL server options by running

mysqld --verbose --help

For example, to find out the path to the data directory on Linux, you can run:

mysqld --verbose --help | grep ^datadir

Example output:

datadir                                     /var/lib/mysql/

PHP display image BLOB from MySQL

Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:

echo "data: $mime" $result['$data']";

where: mime can be an image of any kind, text, word document, text document, PDF document, etc... content datatype is blob in database.

java.lang.IllegalArgumentException: No converter found for return value of type

The issue occurred in my case because spring framework couldn't fetch the properties of nested objects. Getters/Setters is one way of solving. Making the properties public is another quick and dirty solution to validate if this is indeed the problem.

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

If you are providing mappings like this:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        modelBuilder.Configurations.Add(new ClassificationMap());
        modelBuilder.Configurations.Add(new CompanyMap());
        modelBuilder.Configurations.Add(new GroupMap());

Remember to add the map for BaseCs.

You won't get a compile error if it is missing. But you will get a runtime error when you use the entity.

Sharing link on WhatsApp from mobile website (not application) for Android


Don't use:

The pre-filled message will automatically appear in the text field of a chat. Use where whatsappphonenumber is a full phone number in international format and urlencodedtext is the URL-encoded pre-filled message.


To create a link with just a pre-filled message, use


After clicking on the link, you’ll be shown a list of contacts you can send your message to.

How do I remove documents using Node.js Mongoose?

To generalize you can use:

SomeModel.find( $where, function(err,docs){
  if (err) return console.log(err);
  if (!docs || !Array.isArray(docs) || docs.length === 0) 
    return console.log('no docs found');
  docs.forEach( function (doc) {

Another way to achieve this is:

SomeModel.collection.remove( function (err) {
  if (err) throw err;
  // collection is now empty but not deleted

How to implement a read only property

You can do this:

public int Property { get { ... } private set { ... } }

How to calculate a mod b in Python?

mod = a % b

This stores the result of a mod b in the variable mod.

And you are right, 15 mod 4 is 3, which is exactly what python returns:

>>> 15 % 4

a %= b is also valid.

Horizontal list items

Here you can find a working example, with some more suggestions about dynamic resizing of the list.

I've used display:inline-block and a percentage padding so that the parent list can dynamically change size:

padding:10px 1%;
width: 30%

plus two more rules to remove padding for the first and last items.

ul#menuItems li:first-child{padding-left:0;}
ul#menuItems li:last-child{padding-right:0;}

How to validate an email address in PHP


Nowadays, if you use a HTML5 form with type=email then you're already by 80% safe since browser engines have their own validator. To complement it, add this regex to your preg_match_all() and negate it:

if (!preg_match_all("/(?![[:alnum:]]|@|-|_|\.)./",$email)) { .. }

Find the regex used by HTML5 forms for validation

is there a css hack for safari only NOT chrome?

Note: If iOS-only is sufficient (if you're willing to sacrifice Safari desktop), then this works:

    @supports (-webkit-overflow-scrolling: touch) {
    /* CSS specific to iOS devices */ 

How to pass multiple parameters in thread in VB

Something like this (I'm not a VB programmer)

Public Class MyParameters
    public Name As String
    public Number As Integer
End Class

newThread as thread = new Thread( AddressOf DoWork)
Dim parameters As New MyParameters
parameters.Name = "Arne"

public shared sub DoWork(byval data as object)
    dim parameters = CType(data, Parameters)


Removing Spaces from a String in C?

if you are still interested, this function removes spaces from the beginning of the string, and I just had it working in my code:

void removeSpaces(char *str1)  
    char *str2; 
    while (*str2==' ') str2++;  
    if (str2!=str1) memmove(str1,str2,strlen(str2)+1);  

Differences between C++ string == and compare()?

Internally, string::operator==() is using string::compare(). Please refer to: CPlusPlus - string::operator==()

I wrote a small application to compare the performance, and apparently if you compile and run your code on debug environment the string::compare() is slightly faster than string::operator==(). However if you compile and run your code in Release environment, both are pretty much the same.

FYI, I ran 1,000,000 iteration in order to come up with such conclusion.

In order to prove why in debug environment the string::compare is faster, I went to the assembly and here is the code:



        if (str1 == str2)
00D42A34  lea         eax,[str2]  
00D42A37  push        eax  
00D42A38  lea         ecx,[str1]  
00D42A3B  push        ecx  
00D42A3C  call        std::operator==<char,std::char_traits<char>,std::allocator<char> > (0D23EECh)  
00D42A41  add         esp,8  
00D42A44  movzx       edx,al  
00D42A47  test        edx,edx  
00D42A49  je          Algorithm::PerformanceTest::stringComparison_usingEqualOperator1+0C4h (0D42A54h)  


            if ( == 0)
00D424D4  lea         eax,[str2]  
00D424D7  push        eax  
00D424D8  lea         ecx,[str1]  
00D424DB  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0D23582h)  
00D424E0  test        eax,eax  
00D424E2  jne         Algorithm::PerformanceTest::stringComparison_usingCompare1+0BDh (0D424EDh)

You can see that in string::operator==(), it has to perform extra operations (add esp, 8 and movzx edx,al)



        if (str1 == str2)
008533F0  cmp         dword ptr [ebp-14h],10h  
008533F4  lea         eax,[str2]  
008533F7  push        dword ptr [ebp-18h]  
008533FA  cmovae      eax,dword ptr [str2]  
008533FE  push        eax  
008533FF  push        dword ptr [ebp-30h]  
00853402  push        ecx  
00853403  lea         ecx,[str1]  
00853406  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)  


            if ( == 0)
    00853830  cmp         dword ptr [ebp-14h],10h  
    00853834  lea         eax,[str2]  
    00853837  push        dword ptr [ebp-18h]  
    0085383A  cmovae      eax,dword ptr [str2]  
    0085383E  push        eax  
    0085383F  push        dword ptr [ebp-30h]  
    00853842  push        ecx  
00853843  lea         ecx,[str1]  
00853846  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)

Both assembly code are very similar as the compiler perform optimization.

Finally, in my opinion, the performance gain is negligible, hence I would really leave it to the developer to decide on which one is the preferred one as both achieve the same outcome (especially when it is release build).

Is it possible to make a Tree View with Angular?

When making something like this the best solution is an recursive directive. However, when you make such an directive you find out that AngularJS gets into an endless loop.

The solution for this is to let the directive remove the element during the compile event, and manually compile and add them in the link events.

I found out about this in this thread, and abstracted this functionality into a service.

module.factory('RecursionHelper', ['$compile', function($compile){
    return {
         * Manually compiles the element, fixing the recursion loop.
         * @param element
         * @param [link] A post-link function, or an object with function(s) registered via pre and post properties.
         * @returns An object containing the linking functions.
        compile: function(element, link){
            // Normalize the link parameter
                link = { post: link };

            // Break the recursion loop by removing the contents
            var contents = element.contents().remove();
            var compiledContents;
            return {
                pre: (link && link.pre) ? link.pre : null,
                 * Compiles and re-adds the contents
                post: function(scope, element){
                    // Compile the contents
                        compiledContents = $compile(contents);
                    // Re-add the compiled contents to the element
                    compiledContents(scope, function(clone){

                    // Call the post-linking function, if any
                    if(link &&{
              , arguments);

With this service you can easily make a tree directive (or other recursive directives). Here is an example of an tree directive:

module.directive("tree", function(RecursionHelper) {
    return {
        restrict: "E",
        scope: {family: '='},
            '<p>{{ }}</p>'+
            '<ul>' + 
                '<li ng-repeat="child in family.children">' + 
                    '<tree family="child"></tree>' +
                '</li>' +
        compile: function(element) {
            return RecursionHelper.compile(element);

See this Plunker for a demo. I like this solution best because:

  1. You don't need an special directive which makes your html less clean.
  2. The recursion logic is abstracted away into the RecursionHelper service, so you keep your directives clean.

Update: Added support for a custom linking functions.

Html.EditorFor Set Default Value

Here's what I've found:

@Html.TextBoxFor(c => c.Propertyname, new { @Value = "5" })

works with a capital V, not a lower case v (the assumption being value is a keyword used in setters typically) Lower vs upper value

@Html.EditorFor(c => c.Propertyname, new { @Value = "5" })

does not work

Your code ends up looking like this though

<input Value="5" id="Propertyname" name="Propertyname" type="text" value="" />

Value vs. value. Not sure I'd be too fond of that.

Why not just check in the controller action if the proprety has a value or not and if it doesn't just set it there in your view model to your defaulted value and let it bind so as to avoid all this monkey work in the view?

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

In my case, it was the meta tags.

I was using

const MetaTags = require('react-meta-tags');

I guess MetaTags is a default export, So changing to this solved it for me, took hours to figure out which one was causing it.

const { MetaTags } = require('react-meta-tags');

SQL- Ignore case while searching for a string

You should probably use SQL_Latin1_General_Cp1_CI_AS_KI_WI as your collation. The one you specify in your question is explictly case sensitive.

You can see a list of collations here.

missing private key in the distribution certificate on keychain

As long as you still have access to the mac which was used to generate the original distribution certificate it's very simple.

Just use that mac's Keychain Access application to export both the certificate and the private key. Select both using shift or command and right click to export to a .p12 file.

Attached a screenshot to make it very clear.

On your mac, import that .p12 file and you are good to go (just make sure you have a valid provisioning profile).

Just choose export

Unit Testing: DateTime.Now

A thread safe SystemClock using ThreadLocal<T> works great for me.

ThreadLocal<T> is available in the .Net Framework v4.0 and higher.

/// <summary>
/// Provides access to system time while allowing it to be set to a fixed <see cref="DateTime"/> value.
/// </summary>
/// <remarks>
/// This class is thread safe.
/// </remarks>
public static class SystemClock
    private static readonly ThreadLocal<Func<DateTime>> _getTime =
        new ThreadLocal<Func<DateTime>>(() => () => DateTime.Now);

    /// <inheritdoc cref="DateTime.Today"/>
    public static DateTime Today
        get { return _getTime.Value().Date; }

    /// <inheritdoc cref="DateTime.Now"/>
    public static DateTime Now
        get { return _getTime.Value(); }

    /// <inheritdoc cref="DateTime.UtcNow"/>
    public static DateTime UtcNow
        get { return _getTime.Value().ToUniversalTime(); }

    /// <summary>
    /// Sets a fixed (deterministic) time for the current thread to return by <see cref="SystemClock"/>.
    /// </summary>
    public static void Set(DateTime time)
        if (time.Kind != DateTimeKind.Local)
            time = time.ToLocalTime();

        _getTime.Value = () => time;

    /// <summary>
    /// Resets <see cref="SystemClock"/> to return the current <see cref="DateTime.Now"/>.
    /// </summary>
    public static void Reset()
        _getTime.Value = () => DateTime.Now;

Usage example:

public void Today()
    SystemClock.Set(new DateTime(2015, 4, 3));

    DateTime expectedDay = new DateTime(2015, 4, 2);
    DateTime yesterday = SystemClock.Today.AddDays(-1D);
    Assert.AreEqual(expectedDay, yesterday);


Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

I understand this is a very old thread. However, wanted to share how I encountered the message in my scenario and in case it might help others

  1. I created an Add-Migration <Migration_name> on my local machine. Didn't run the update-database yet.
  2. Meanwhile, there were series of commits in parent branch that I must down merge. The merge also had a migration to it and when I fixed conflicts, I ended up having 2 migrations that are added to my project but are not executed via update-database.
  3. Now I don't use enable-migrations -force in my application. Rather my preferred way is execute the update-database -script command to control the target migrations I need.
  4. So, when I attempted the above command, I get the error in question.

My solution was to run update-database -Script -TargetMigration <migration_name_from_merge> and then my update-database -Script -TargetMigration <migration_name> which generated 2 scripts that I was able to run manually on my local db.

Needless to say above experience is on my local machine.

Format numbers in thousands (K) in Excel

Non-Americans take note! If you use Excel with "." as 1000 separator, you need to replace the "," with a "." in the formula, such as:

[>=1000]€ #.##0." K";[<=-1000]-€ #.##0." K";0

The code above will display € 62.123 as "€ 62 K".

What is the best way to paginate results in SQL Server

This is a duplicate of the 2012 old SO question: efficient way to implement paging


Here the topic is discussed in greater details, and with alternate approaches.

jQuery selector regular expressions

$("input[name='option[colour]'] :checked ")

How do I disable orientation change on Android?

I've always found you need both

android:screenOrientation="nosensor" android:configChanges="keyboardHidden|orientation"

Getting all documents from one collection in Firestore

Try following LOCs

    let query = firestore.collection('events');
    let response = [];
    await query.get().then(querySnapshot => {
          let docs =;
          for (let doc of docs) {
              const selectedEvent = {
   return response;

Convert the values in a column into row names in an existing data frame

It looks like the one-liner got even simpler along the line (currently using R 3.5.3):

# generate original data.frame
df <- data.frame(a = letters[1:10], b = 1:10, c = LETTERS[1:10])
# use first column for row names
df <- data.frame(df, row.names = 1)

The column used for row names is removed automatically.

How to check if a variable is a dictionary in Python?

You could use if type(ele) is dict or use isinstance(ele, dict) which would work if you had subclassed dict:

d = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for element in d.values():
    if isinstance(element, dict):
       for k, v in element.items():
           print(k,' ',v)

When to use RDLC over RDL reports?

Q: What is the difference between RDL and RDLC formats?

A: RDL files are created by the SQL Server 2005 version of Report Designer. RDLC files are created by the Visual Studio 2008 version of Report Designer.

RDL and RDLC formats have the same XML schema. However, in RDLC files, some values (such as query text) are allowed to be empty, which means that they are not immediately ready to be published to a Report Server. The missing values can be entered by opening the RDLC file using the SQL Server 2005 version of Report Designer. (You have to rename .rdlc to .rdl first.)

RDL files are fully compatible with the ReportViewer control runtime. However, RDL files do not contain some information that the design-time of the ReportViewer control depends on for automatically generating data-binding code. By manually binding data, RDL files can be used in the ReportViewer control. New! See also the RDL Viewer sample program.

Note that the ReportViewer control does not contain any logic for connecting to databases or executing queries. By separating out such logic, the ReportViewer has been made compatible with all data sources, including non-database data sources. However this means that when an RDL file is used by the ReportViewer control, the SQL related information in the RDL file is simply ignored by the control. It is the host application's responsibility to connect to databases, execute queries and supply data to the ReportViewer control in the form of ADO.NET DataTables.

Using File.listFiles with FileNameExtensionFilter

Here's something I quickly just made and it should perform far better than File.getName().endsWith(".xxxx");


public class ExtensionsFilter implements FileFilter 
    private char[][] extensions;

    private ExtensionsFilter(String[] extensions)
        int length = extensions.length;
        this.extensions = new char[length][];
        for (String s : extensions)
            this.extensions[--length] = s.toCharArray();

    public boolean accept(File file)
        char[] path = file.getPath().toCharArray();
        for (char[] extension : extensions)
            if (extension.length > path.length)
            int pStart = path.length - 1;
            int eStart = extension.length - 1;
            boolean success = true;
            for (int i = 0; i <= eStart; i++)
                if ((path[pStart - i] | 0x20) != (extension[eStart - i] | 0x20))
                    success = false;
            if (success)
                return true;
        return false;

Here's an example for various images formats.

private static final ExtensionsFilter IMAGE_FILTER = 
      new ExtensionsFilter(new String[] {".png", ".jpg", ".bmp"});

How do you serve a file for download with AngularJS or Javascript?

This worked for me in angular:

var a = document.createElement("a");
a.href = 'fileURL'; = 'fileName';;

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

Happened to me on node 13.7.0 and npm 6.13.6 (macOS Mojave).

I had the following as part of my errors:

found X vulnerabilities (Y moderate, Z high)
  run `npm audit fix` to fix them, or `npm audit` for details

And running the following fixed the problem:

  1. $ npm audit fix

  2. $ npm install

How to use font-awesome icons from node-modules

SASS modules version

Soon, using @import in sass will be depreciated. SASS modules configuration works using @use instead.

@use "../node_modules/font-awesome/scss/font-awesome"  with (
  $fa-font-path: "../icons"

.icon-user {
  @extend .fa;
  @extend .fa-user;

Using :focus to style outer div?

While this can't be achieved with CSS/HTML alone, it can be achieved with JavaScript (without need of a library):

var textareas = document.getElementsByTagName('textarea');

for (i=0;i<textareas.length;i++){
    // you can omit the 'if' if you want to style the parent node regardless of its
    // element type
    if (textareas[i].parentNode.tagName.toString().toLowerCase() == 'div') {
        textareas[i].onfocus = function(){
   = 'solid';
        textareas[i].onblur = function(){
   = 'dashed';

JS Fiddle demo.

Incidentally, with a library, such as jQuery, the above could be condensed down to:


JS Fiddle demo.


What are database normal forms and can you give examples?

Here's a quick, admittedly butchered response, but in a sentence:

1NF : Your table is organized as an unordered set of data, and there are no repeating columns.

2NF: You don't repeat data in one column of your table because of another column.

3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.

For more detail, see wikipedia...

How can I stop a running MySQL query?

mysql>show processlist;

mysql> kill "number from first col";

How to know that a string starts/ends with a specific string in jQuery?

You do not really need jQuery for such tasks. In the ES6 specification they already have out of the box methods startsWith and endsWith.

var str = "To be, or not to be, that is the question.";
alert(str.startsWith("To be"));         // true
alert(str.startsWith("not to be"));     // false
alert(str.startsWith("not to be", 10)); // true

var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

Currently available in FF and Chrome. For old browsers you can use their polyfills or substr

Replace CRLF using powershell

For CMD one line LF-only:

powershell -NoProfile -command "((Get-Content 'prueba1.txt') -join \"`n\") + \"`n\" | Set-Content -NoNewline 'prueba1.txt'"

so you can create a .bat

Re-ordering columns in pandas dataframe based on column name

df = df.reindex(sorted(df.columns), axis=1)

This assumes that sorting the column names will give the order you want. If your column names won't sort lexicographically (e.g., if you want column Q10.3 to appear after Q9.1), you'll need to sort differently, but that has nothing to do with pandas.

Visual Studio opens the default browser instead of Internet Explorer

In Visual Studio 2010 the default browser gets reset often (just about every time an IDE setting is changed or even after restarting Visual Studio). There is now a default browser selector extension for 2010 to help combat this:

!!!Update!!! It appears that the WoVS Default Browser Switcher is no longer available for free according to @Cory. You might try Default Browser Changer instead but I have not tested it. If you already have the WoVS plugin I would recommend backing it up so that you can install it later.

The following solution may no longer work:

WoVS Default Browser Switcher:

WoVS Default Browser Switcher

Edit: This works with ASP.NET MVC applications as well.

Note: One negative side effect of installing this extension is that it seems to nag to be updated about once a month. This has caused some to uninstall it because, to them, its more bothersome then the problem it fixes. Regardless it is easily updated through the extension manager and I still find it very useful.

You will see the following error when starting VS:

The Default Browser Switcher beta bits have expired. Please use the Extension Manager or visit the VS Gallery to download updated bits.

How to do a GitHub pull request

I wrote a bash program that does all the work of setting up a PR branch for you. It performs forking if needed, syncing with the upstream, setting up upstream remote, etc. and you just need to commit your modifications, push and submit a PR.

Here is how you run it:

github-make-pr-branch ssh your-github-username orig_repo_user orig_repo_name new-feature

You will find the program here and its repository also includes a step-by-step guide to performing the same process manually if you'd like to understand how it works, and also extra information on how to keep your feature branch up-to-date with the upstream master and other useful tidbits.

Equivalent of String.format in jQuery

You can also closure array with replacements like this.

var url = '/getElement/_/_/_'.replace(/_/g, (_ =>[this.i++]).bind({ar: ["invoice", "id", 1337],i: 0}))
> '/getElement/invoice/id/1337

or you can try bind

'/getElement/_/_/_'.replace(/_/g, (function(_) {return[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))

Remove Blank option from Select Option with AngularJS

Also check whether you have any falsy value or not. Angularjs will insert an empty option if you do have falsy value. I struggled for 2 days just due to falsy value. I hope it will be helpful for someone.

I had options as [0, 1] and initially I was set the model to 0 due to that it was inserted empty option. Workaround for this was ["0" , "1"].

Preventing form resubmission

There are two parts to the answer:

  1. Ensure duplicate posts don't mess with your data on the server side. To do this, embed a unique identifier in the post so that you can reject subsequent requests server side. This pattern is called Idempotent Receiver in messaging terms.

  2. Ensure the user isn't bothered by the possibility of duplicate submits by both

    • redirecting to a GET after the POST (POST redirect GET pattern)
    • disabling the button using javascript

Nothing you do under 2. will totally prevent duplicate submits. People can click very fast and hackers can post anyway. You always need 1. if you want to be absolutely sure there are no duplicates.

Running a command in a new Mac OS X Terminal window

I call this script trun. I suggest putting it in a directory in your executable path. Make sure it is executable like this:

chmod +x ~/bin/trun

Then you can run commands in a new window by just adding trun before them, like this:

trun tail -f /var/log/system.log

Here's the script. It does some fancy things like pass your arguments, change the title bar, clear the screen to remove shell startup clutter, remove its file when its done. By using a unique file for each new window it can be used to create many windows at the same time.

# make this file executable with chmod +x trun
# create a unique file in /tmp
# make it cd back to where we are now
echo "cd `pwd`" >$trun_cmd
# make the title bar contain the command being run
echo 'echo -n -e "\033]0;'$*'\007"' >>$trun_cmd
# clear window
echo clear >>$trun_cmd
# the shell command to execute
echo $* >>$trun_cmd
# make the command remove itself
echo rm $trun_cmd >>$trun_cmd
# make the file executable
chmod +x $trun_cmd

# open it in Terminal to run it in a new Terminal window
open -b $trun_cmd

How can I get a specific number child using CSS?

For modern browsers, use td:nth-child(2) for the second td, and td:nth-child(3) for the third. Remember that these retrieve the second and third td for every row.

If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.

CSS Classes & SubClasses

That is the backbone of CSS, the "cascade" in Cascading Style Sheets.

If you write your CSS rules in a single line it makes it easier to see the structure:

.area1 .item { color:red; }
.area2 .item { color:blue; }
.area2 .item span { font-weight:bold; }

Using multiple classes is also a good intermediate/advanced use of CSS, unfortunately there is a well known IE6 bug which limits this usage when writing cross browser code:

<div class="area1 larger"> .... </div>

.area1 { width:200px; }
.area1.larger { width:300px; }

IE6 IGNORES the first selector in a multi-class rule, so IE6 actually applies the .area1.larger rule as

/*.area1*/.larger { ... }

Meaning it will affect ALL .larger elements.

It's a very nasty and unfortunate bug (one of many) in IE6 that forces you to pretty much never use that feature of CSS if you want one clean cross-browser CSS file.

The solution then is to use CSS classname prefixes to avoid colliding wiht generic classnames:

.area1 { ... }
.area1.area1Larger { ... }

.area2.area2Larger { ... }

May as well use just one class, but that way you can keep the CSS in the logic you intended, while knowing that .area1Larger only affects .area1, etc.

PHP Parse HTML code

Use PHP Document Object Model:

   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";

This outputs as:


[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

The issue is in your registration app. It seems django-registration calls get_user_module() in at a module level (when models are still being loaded by the application registration process). This will no longer work:

    from django.contrib.auth import get_user_model
    User = get_user_model()
except ImportError:
    from django.contrib.auth.models import User    

I'd change this models file to only call get_user_model() inside methods (and not at module level) and in FKs use something like:

user = ForeignKey(settings.AUTH_USER_MODEL)

BTW, the call to django.setup() shouldn't be required in your file, it's called for you in execute_from_command_line. (source)

Show Current Location and Update Location in MKMapView in Swift

For swift 3 and XCode 8 I find this answer:

  • First, you need set privacy into info.plist. Insert string NSLocationWhenInUseUsageDescription with your description why you want get user location. For example, set string "For map in application".

  • Second, use this code example

    @IBOutlet weak var mapView: MKMapView!
    private var locationManager: CLLocationManager!
    private var currentLocation: CLLocation?
    override func viewDidLoad() {
        mapView.delegate = self
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        // Check for Location Services
        if CLLocationManager.locationServicesEnabled() {
    // MARK - CLLocationManagerDelegate
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        defer { currentLocation = locations.last }
        if currentLocation == nil {
            // Zoom to user location
            if let userLocation = locations.last {
                let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
                mapView.setRegion(viewRegion, animated: false)
  • Third, set User Location flag in storyboard for mapView.

enumerate() for dictionary in python

You may find it useful to include index inside key:

d = {'a': 1, 'b': 2}
d = {(i, k): v for i, (k, v) in enumerate(d.items())}


{(0, 'a'): True, (1, 'b'): False}

I want to multiply two columns in a pandas DataFrame and add the result into a new column

If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:

In [22]: orders_df['C'] = orders_df.Action.apply(
               lambda x: (1 if x == 'Sell' else -1))

In [23]: orders_df   # New column C represents the sign of the transaction
   Prices  Amount Action  C
0       3      57   Sell  1
1      89      42   Sell  1
2      45      70    Buy -1
3       6      43   Sell  1
4      60      47   Sell  1
5      19      16    Buy -1
6      56      89   Sell  1
7       3      28    Buy -1
8      56      69   Sell  1
9      90      49    Buy -1

Now we have eliminated the need for the if statement. Using DataFrame.apply(), we also do away with the for loop. As Hayden noted, vectorized operations are always faster.

In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C

In [25]: orders_df   # The resulting dataframe
   Prices  Amount Action  C  Value
0       3      57   Sell  1    171
1      89      42   Sell  1   3738
2      45      70    Buy -1  -3150
3       6      43   Sell  1    258
4      60      47   Sell  1   2820
5      19      16    Buy -1   -304
6      56      89   Sell  1   4984
7       3      28    Buy -1    -84
8      56      69   Sell  1   3864
9      90      49    Buy -1  -4410

This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.

ScriptManager.RegisterStartupScript code not working - why?

Try this code...

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", "alert('Hi');", true);

Where UpdatePanel1 is the id for Updatepanel on your page

Adding minutes to date time in PHP

one line mysql datetime format

$mysql_date_time = (new DateTime())->modify('+15 minutes')->format("Y-m-d H:i:s");

MySQL: selecting rows where a column is null

SQL NULL's special, and you have to do WHERE field IS NULL, as NULL cannot be equal to anything,

including itself (ie: NULL = NULL is always false).

See Rule 3

How do I align views at the bottom of the screen?

The answer above (by Janusz) is quite correct, but I personnally don't feel 100% confortable with RelativeLayouts, so I prefer to introduce a 'filler', empty TextView, like this:

<!-- filler -->
<TextView android:layout_height="0dip" 
          android:layout_weight="1" />

before the element that should be at the bottom of the screen.

How do I rename a file using VBScript?

Rename filename by searching the last character of name. For example, 

Original Filename: TestFile.txt_001
Begin Character need to be removed: _
Result: TestFile.txt

Option Explicit

Dim oWSH
Dim vbsInterpreter
Dim arg1 'As String
Dim arg2 'As String
Dim newFilename 'As string

Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"


arg1 = WScript.Arguments(0)
arg2 = WScript.Arguments(1)

WScript.StdOut.WriteLine "This is a test script."
Dim result 
result = InstrRev(arg1, arg2, -1)
If result > 0 then
    newFilename = Mid(arg1, 1, result - 1)
    Dim Fso
    Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
    Fso.MoveFile arg1, newFilename
    WScript.StdOut.WriteLine newFilename
End If

Function ForceConsole()
    If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
        oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) &     WScript.ScriptFullName & Chr(34)
    End If
 End Function

Visual Studio : short cut Key : Duplicate Line

In Visual Studio 2019

Ctrl + D

In Visual Studio 2017 (v15.6 and after)

Ctrl + D

In Visual Studio 2017 (pre v15.6)

(edit) This feature is now built-in in VS2017: Ctrl + E, V duplicates a line if nothing is selected, or duplicates selection. You can assign it to a different key combination, or find it in the menu:

Duplicate line in VS2017

See this reference for more information.

Pre VS2017, built-in method using clipboard

As @cand mentioned, you can just do Ctrl + C ; Ctrl + V.

Ctrl + C will copy the line if nothing is selected.

Macro solution (pre VS2017)

If you'd like to implement a more complete solution, perhaps to create a simpler keyboard shortcut or you don't want to effect the clipboard, see this guide:

Duplicate line command for Visual Studio

Visual Basic:

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics

Public Module DuplicateLastLineModule
    Sub DuplicateLine()
        Dim line As String
        line = DTE.ActiveDocument.Selection.Text
        DTE.ActiveDocument.Selection.Text = line
    End Sub
End Module

To create the macro, just go to the macro explorer ("Tools->Macros->Macro Explorer" or Alt+F8) and copy paste the code in a new module. Now just assign a keyboard shortcut to it:

  1. go to Tools->Options...
  2. under Environment, click Keyboard
  3. in the "Show Commands Containing" textbox, enter "duplicate" (this according to the name you gave the module.)
  4. you should now see the macro in the list below
  5. choose "Text Editor" from the "Use new shortcut in" list
  6. set focus in the "Press shortcut keys" textbox and hit the combination on the keyboard you whish to use for it (Ctrl+Shift+D in my case)
  7. hit the "Assign" button
  8. you should now see the shortcut in the "Shortcuts for selected command" textbox
  9. hit the OK button

And that's it. Enjoy!

How to use a link to call JavaScript?

Unobtrusive JavaScript, no library dependency:

    <script type="text/javascript">

        // Wait for the page to load first
        window.onload = function() {

          //Get a reference to the link on the page
          // with an id of "mylink"
          var a = document.getElementById("mylink");

          //Set code to run when the link is clicked
          // by assigning a function to "onclick"
          a.onclick = function() {

            // Your code here...

            //If you don't want the link to actually 
            // redirect the browser to another page,
            // "" in our example here, then
            // return false at the end of this block.
            // Note that this also prevents event bubbling,
            // which is probably what we want here, but won't 
            // always be the case.
            return false;
    <a id="mylink" href="">linky</a>        

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

Restart your wampServer... that should solve it. and if it doesn't.. Resta

Cursor adapter and sqlite example

Really simple example.

Here is a really simple, but very effective, example. Once you have the basics down you can easily build off of it.

There are two main parts to using a Cursor Adapter with SQLite:

  1. Create a proper Cursor from the Database.

  2. Create a custom Cursor Adapter that takes the Cursor data from the database and pairs it with the View you intend to represent the data with.

1. Create a proper Cursor from the Database.

In your Activity:

SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper( 
        context, DATABASE_NAME, null, DATABASE_VERSION);

SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase();

String query = "SELECT * FROM clients ORDER BY company_name ASC"; // No trailing ';'

Cursor cursor = sqLiteDatabase.rawQuery(query, null); 

ClientCursorAdapter adapter = new ClientCursorAdapter(
        this, R.layout.clients_listview_row, cursor, 0 );


2. Create a Custom Cursor Adapter.

Note: Extending from ResourceCursorAdapter assumes you use XML to create your views.

public class ClientCursorAdapter extends ResourceCursorAdapter {

    public ClientCursorAdapter(Context context, int layout, Cursor cursor, int flags) {
        super(context, layout, cursor, flags);

    public void bindView(View view, Context context, Cursor cursor) {
        TextView name = (TextView) view.findViewById(;

        TextView phone = (TextView) view.findViewById(;

How to get current value of RxJS Subject or Observable?

const observable = of('response')

function hasValue(value: any) {
  return value !== null && value !== undefined;

function getValue<T>(observable: Observable<T>): Promise<T> {
  return observable

const result = await getValue(observable)
// Do the logic with the result
// .................
// .................
// .................

You can check the full article on how to implement it from here.

How to use Python's "easy_install" on Windows ... it's not so easy

If you are using Anaconda's Python distribution,

you can install it through pip

pip install setuptools

and then execute it as a module

python -m easy_install

How do I give ASP.NET permission to write to a folder in Windows 7?

The full command would be something like below, notice the quotes

icacls "c:\inetpub\wwwroot\tmp" /grant "IIS AppPool\DefaultAppPool:F"

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

1) Run below command in powershell with admin mode:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All

2) run below command in command prompt with admin mode:

bcdedit /set hypervisorlaunchtype off 

enter image description here

3) disabled Hyper-V: Control Panel\Programs\Programs and Features\ enter image description here

4) VMBox memory made it to: 3155 MB (VMbox->settings->system)

VM box Acceleration is deactivated. How do activate this? and fix above error? enter image description here

Restart your system.

Twitter Bootstrap date picker

Some people posted the link to this bootstrap-datepicker.js implementation. I used that one in the following way, it works with Bootstrap 3.

This is the markup I used:

<div class="input-group date col-md-3" data-date-format="dd-mm-yyyy" data-date="01-01-2014">                        
    <input id="txtHomeLoanStartDate" class="form-control" type="text" readonly="" value="01-01-2014" size="14" />
    <span class="input-group-addon add-on">
        <span class="glyphicon glyphicon-calendar"</span>

This is the javascript:


I also included the javascript file downloaded from the link above, along with it's css file, and of course, you should remove any bootstrap grid classes like the col-md-3 to suit your needs.

SQL - using alias in Group By

Caution that using alias in the Group By (for services that support it, such as postgres) can have unintended results. For example, if you create an alias that already exists in the inner statement, the Group By will chose the inner field name.

-- Working example in postgres
select col1 as col1_1, avg(col3) as col2_1
    (select gender as col1, maritalstatus as col2, 
    yearlyincome as col3 from customer) as layer_1
group by col1_1;

-- Failing example in postgres
select col2 as col1, avg(col3)
    (select gender as col1, maritalstatus as col2,
    yearlyincome as col3 from customer) as layer_1
group by col1;

How to print the current Stack Trace in .NET without any exception?

    new System.Diagnostics.StackTrace().ToString()

The output will be similar to:

at YourNamespace.Program.executeMethod(String msg)

at YourNamespace.Program.Main(String[] args)

Replace Console.WriteLine with your Log method. Actually, there is no need for .ToString() for the Console.WriteLine case as it accepts object. But you may need that for your Log(string msg) method.

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        else {
            console.log("Error: Unauthorized update of employee!");

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {

And here is a plunker demonstrating what it sounds like you're trying to do:

How to display HTML tags as plain text

As many others have said, htmlentities() will do the trick... but it will look like shit.

Wrap it up with a <pre> tag and you'll preserve your indentation.

echo '<pre>';
echo htmlspecialchars($YOUR_HTML);
echo '</pre>';

Write single CSV file using spark-csv

you can use rdd.coalesce(1, true).saveAsTextFile(path)

it will store data as singile file in path/part-00000

Creating columns in listView and add items

Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: (look at the comments on the code example at the bottom)

private void initListView()
    // Add columns
    lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
    lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
    lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);

You can also use the other overload, Add(string). E.g:


Reference for more overloads:

Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.

var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});

You can also store objects in the item's Tag property.

item2.Tag = person;

And then you can extract it

var person = item2.Tag as Person;

Let me know if you have any questions and I hope this helps!

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

This originally answered a supplemental question about the wisdom of downloading jQuery versus accessing it via a CDN, which is no longer present...

To answer the thing about Google. I have moved over to accessing JQuery and most other of these sorts of libraries via the corresponding CDN in my sites.

As more people do this means that it's more likely to be cached on user's machines, so my vote goes for good idea.

In the five years since I first offered this, it has become common wisdom.

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

What is the __del__ method, How to call it?

The __del__ method, it will be called when the object is garbage collected. Note that it isn't necessarily guaranteed to be called though. The following code by itself won't necessarily do it:

del obj

The reason being that del just decrements the reference count by one. If something else has a reference to the object, __del__ won't get called.

There are a few caveats to using __del__ though. Generally, they usually just aren't very useful. It sounds to me more like you want to use a close method or maybe a with statement.

See the python documentation on __del__ methods.

One other thing to note: __del__ methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a __del__ method won't get garbage collected. This is because the garbage collector doesn't know which one to call first. See the documentation on the gc module for more info.

MySQl Error #1064

Sometimes when your table has a similar name to the database name you should use back tick. so instead of:

INSERT INTO, field2) VALUES ('value1', 'value2');

You should have this:

INSERT INTO `books`.`book`(`field1`, `field2`) VALUES ('value1', 'value2');

Can't create handler inside thread which has not called Looper.prepare()

Try this

    Handler mHandler = new Handler(Looper.getMainLooper());
               Runnable() {
                            public void run() {
 //your code here that talks with the UI level widgets/ try to access the UI 
//elements from this block because this piece of snippet will run in the UI/MainThread.                                     

Ellipsis for overflow text in dropdown boxes

quirksmode has a good description of the 'text-overflow' property, but you may need to apply some additional properties like 'white-space: nowrap'

Whilst I'm not 100% how this will behave in a select object, it could be worth trying this first:

Javascript: How to pass a function with string parameters as a parameter to another function

Me, I'd do it something like this:


onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"


function myfunction(params)
  var path = params.path;

  /* do stuff */

  // on ok condition 

  // on cancel condition

But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.

Column count doesn't match value count at row 1

You should also look at new triggers.

MySQL doesn't show the table name in the error, so you're really left in a lurch. Here's a working example:

use test;
create table blah (id int primary key AUTO_INCREMENT, data varchar(100));
create table audit_blah (audit_id int primary key AUTO_INCREMENT, action enum('INSERT','UPDATE','DELETE'), id int, data varchar(100) null);
insert into audit_blah(action, id, data) values ('INSERT', 1, 'a');
select * from blah;
select * from audit_blah;
truncate table audit_blah;

delimiter //
/* I've commented out "id" below, so the insert fails with an ambiguous error: */
create trigger ai_blah after insert on blah for each row 
  insert into audit_blah (action, /*id,*/ data) values ('INSERT', /*,*/;

/* This insert is valid, but you'll get an exception from the trigger: */
insert into blah (data) values ('data1');

400 vs 422 response to POST of data

To reflect the status as of 2015:

Behaviorally both 400 and 422 response codes will be treated the same by clients and intermediaries, so it actually doesn't make a concrete difference which you use.

However I would expect to see 400 currently used more widely, and furthermore the clarifications that the HTTPbis spec provides make it the more appropriate of the two status codes:

  • The HTTPbis spec clarifies the intent of 400 to not be solely for syntax errors. The broader phrase "indicates that the server cannot or will not process the request due to something which is perceived to be a client error" is now used.
  • 422 is specifically a WebDAV extension, and is not referenced in RFC 2616 or in the newer HTTPbis specification.

For context, HTTPbis is a revision of the HTTP/1.1 spec that attempts to clarify areas that were unclear or inconsistent. Once it has reached approved status it will supersede RFC2616.

Is there a way to detach matplotlib plots so that the computation can continue?

In my opinion, the answers in this thread provide methods which don't work for every systems and in more complex situations like animations. I suggest to have a look at the answer of MiKTeX in the following thread, where a robust method has been found: How to wait until matplotlib animation ends?

Transpose a data frame

Take advantage of as.matrix:

# keep the first column 
names <-  df.aree[,1]

# Transpose everything other than the first column
df.aree.T <-[,-1])))

# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names

<strong> vs. font-weight:bold & <em> vs. font-style:italic

<strong> and <em> - unlike <b> and <i> - have clear purpose for web browsers for the blind.

A blind person doesn't browse the web visually, but by sound such as text readers. <strong> and <em>, in addition to encouraging something to be bold or italic, also convey loudness or stressing syllables respectively (OH MY! & Ooooooh Myyyyyyy!). Audio-only browsers are unpredictable when it comes to <b> and <i>... they may make them loud or stress them or they may not... you never can be sure unless you use <strong> and <em>.

How to escape strings in SQL Server using PHP?

function ms_escape_string($data) {
        if ( !isset($data) or empty($data) ) return '';
        if ( is_numeric($data) ) return $data;

        $non_displayables = array(
            '/%0[0-8bcef]/',            // url encoded 00-08, 11, 12, 14, 15
            '/%1[0-9a-f]/',             // url encoded 16-31
            '/[\x00-\x08]/',            // 00-08
            '/\x0b/',                   // 11
            '/\x0c/',                   // 12
            '/[\x0e-\x1f]/'             // 14-31
        foreach ( $non_displayables as $regex )
            $data = preg_replace( $regex, '', $data );
        $data = str_replace("'", "''", $data );
        return $data;

Some of the code here was ripped off from CodeIgniter. Works well and is a clean solution.

EDIT: There are plenty of issues with that code snippet above. Please don't use this without reading the comments to know what those are. Better yet, please don't use this at all. Parameterized queries are your friends:

Angular cli generate a service and include the provider in one step

In Command prompt go to project folder and execute following:

ng g s servicename

How to handle a lost KeyStore password in Android?

In my case I had upgraded my Android Studio from 2.3 to 3.0.1, When I trying to generate a signed apk for a new update I got "Keystore was tampered with, or password was incorrect" error. I had my previous Keystore and I was absolutely sure of the password, using them I had updated the app before a couple of times. After searching a lot none of the solutions worked for me. Here is what I did.

  • Opened another project.
  • Imported my project using File/New/Import Project
  • Once Gradle was built I tried to generate a signed apk. Build/Generate signed APK
  • Clicked on "Choose Existing" and provided the path to my Keystore.
  • typed in my key store password
  • selected the key alias
  • typed in my key password (In my case both key store password and key password are the same)
  • Clicked next and provided a path for the new Apk and checked both checkboxes.
  • New APK got generated successfully.

Hope this helps anyone.

How to calculate a Mod b in Casio fx-991ES calculator

type normal division first and then type shift + S->d

Select single item from a list

Just to complete the answer, If you are using the LINQ syntax, you can just wrap it since it returns an IEnumerable:

(from int x in intList
 where x > 5
 select x * 2).FirstOrDefault()

JavaScript alert not working in Android WebView

webView.setWebChromeClient(new WebChromeClient() {
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        return super.onJsAlert(view, url, message, result);

CSS text-overflow in a table cell?

When it's in percentage table width, or you can't set fixed width on table cell. You can apply table-layout: fixed; to make it work.

table {_x000D_
  table-layout: fixed;_x000D_
  width: 100%;_x000D_
td {_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  border: 1px solid red;_x000D_
    <td>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</td>_x000D_
    <td>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</td>_x000D_

What is the difference between DAO and Repository patterns?

Try to find out if DAO or the Repository pattern is most applicable to the following situation : Imagine you would like to provide a uniform data access API for a persistent mechanism to various types of data sources such as RDBMS, LDAP, OODB, XML repositories and flat files.

Also refer to the following links as well, if interested:

Host '' is not allowed to connect to this MySQL server

Just perform the following steps:

1a) Connect to mysql (via localhost)

mysql -uroot -p

1b) If the mysql server is running in Kubernetes (K8s) and being accessed via a NodePort

kubectl exec -it [pod-name] -- /bin/bash
mysql -uroot -p
  1. Create user

    CREATE USER 'user'@'%' IDENTIFIED BY 'password';

  2. Grant permissions


  3. Flush privileges


How to add DOM element script to head section?

I use PHP as my serverside language, so the example i will write in it - but i'm sure there is a method in your server side as well.

Just have your serverside language add it from a variable. w/ php something like that would go as follows.

Do note, that this will only work if the script is loaded with the page load. If you want to load it dynamically, this solution will not help you.



    <script type="text/javascript"> <?php echo $decodedstring ?> </script>

In Summary: Decode with serverside and put it in your HTML using the server language.

Codeigniter $this->db->get(), how do I return values for a specific row?

you can use row() instead of result().

$this->db->where('id', '3');
$q = $this->db->get('my_users_table')->row();

Git ignore file for Xcode projects

Here's the .gitignore that GitHub uses by default for new Xcode repositories:

It's likely to be reasonably correct at any given time.

Get current user id in ASP.NET Identity 2.0

In order to get CurrentUserId in Identity 2.0, at first import Microsoft.AspNet.Identity:


using Microsoft.AspNet.Identity;


Imports Microsoft.AspNet.Identity

And then call User.Identity.GetUserId() everywhere you want:

strCurrentUserId = User.Identity.GetUserId()

This method returns current user id as defined datatype for userid in database (the default is String).

How to I say Is Not Null in VBA

Use Not IsNull(Fields!W_O_Count.Value)

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

One important advantage of BFS would be that it can be used to find the shortest path between any two nodes in an unweighted graph. Whereas, we cannot use DFS for the same.

X-Frame-Options on apache

I found that if the application within the httpd server has a rule like "if the X-Frame-Options header exists and has a value, leave it alone; otherwise add the header X-Frame-Options: SAMEORIGIN" then an httpd.conf mod_headers rule like "Header always unset X-Frame-Options" would not suffice. The SAMEORIGIN value would always reach the client.

To remedy this, I add two, not one, mod_headers rules (in the outermost httpd.conf file):

Header set X-Frame-Options ALLOW-FROM early
Header unset X-Frame-Options

The first rule tells any internal request handler that some other agent has taken responsibility for clickjack prevention and it can skip its attempt to save the world. It runs with "early" processing. The second rule strips off the entirely unwanted X-Frame-Options header. It runs with "late" processing.

I also add the appropriate Content-Security-Policy headers so that the world remains protected yet multi-sourced Javascript from trusted sites still gets to run.

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

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

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

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

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

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

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

Jump into interface implementation in Eclipse IDE

If you are really looking to speed your code navigation, you might want to take a look at nWire for Java. It is a code exploration plugin for Eclipse. You can instantly see all the related artifacts. So, in that case, you will focus on the method call and instantly see all possible implementations, declarations, invocations, etc.

Programmatically Install Certificate into Mozilla

Just wanted to add to an old thread to hopefully aid other people. I needed programmatically add a cert to the firefox database using a GPO, this was how I did it for Windows

1, First download and unzip the precompiled firefox NSS

2, Add the cert manually to firefox Options-->Advanced--Certificates-->Authorities-->Import

3, from the downloaded NSS package, run

certutil -L -d c:\users\[username]\appdata\roaming\mozilla\firefox\[profile].default    

4, The above query will show you the certificate name and Trust Attributes e.g.

my company Ltd                                CT,C,C    

5, Delete the certificate in step 2. Options-->Advanced--Certificates-->Authorities-->Delete

6, Create a powershell script using the information from step 4 as follows. This script will get the users profile path and add the certificate. This only works if the user has one firefox profile (need somehow to retrieve the users firefox folder profile name)

#Script adds Radius Certificate to independent Firefox certificate store since the browser does not use the Windows built in certificate store    

#Get Firefox profile cert8.db file from users windows profile path
$ProfilePath = "C:\Users\" + $env:username + "\AppData\Roaming\Mozilla\Firefox\Profiles\"
$ProfilePath = $ProfilePath + (Get-ChildItem $ProfilePath | ForEach-Object { $_.Name }).ToString()

#Update firefox cert8.db file with Radius Certificate
certutil -A -n "UK my company" -t "CT,C,C" -i CertNameToAdd.crt -d $ProfilePath    

7, Create GPO as a User Configuration to run the PowerShell script

Hope that helps save someone time

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

The configuration here is working for me:

configurations {

dependencies {
        // Spring Boot dependencies


war {
    classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))

springBoot {
    providedConfiguration = "customProvidedRuntime"

Click event on select option element in chrome

<select id="myselect">
    <option value="0">sometext</option>
    <option value="2">Ready for Review</option>
    <option value="3">Registration Date</option>

$('#myselect').change(function() {
    if($('#myselect option:selected').val() == 0) {
    else {

How to pass values arguments to function in Bootstrap

You could do it like this:

<a class="btn btn-primary announce" data-toggle="modal" data-id="107" >Announce</a>

Then use jQuery to bind the click and send the Announce data-id as the value in the modals #cafeId:

   $(".announce").click(function(){ // Click to only happen on announce links

Round up double to 2 decimal places

Just a quick follow-up answer for noobs like me:

You can make the other answers super easily implementable by using a function with an output. E.g.

  func twoDecimals(number: Float) -> String{
    return String(format: "%.2f", number)

This way, whenever you want to grab a value to 2 decimal places you just type

twoDecimals('Your number here')



P.s. You could also make it return a Float value, or anything you want, by then converting it again after the String conversion as follows:

 func twoDecimals(number: Float) -> Float{
    let stringValue = String(format: "%.2f", number)
    return Float(stringValue)!

Hope that helps.

Entity Framework - Generating Classes

1) First you need to generate EDMX model using your database. To do that you should add new item to your project:

  • Select ADO.NET Entity Data Model from the Templates list.
  • On the Choose Model Contents page, select the Generate from Database option and click Next.
  • Choose your database.
  • On the Choose Your Database Objects page, check the Tables. Choose Views or Stored Procedures if you need.

So now you have Model1.edmx file in your project.

2) To generate classes using your model:

  • Open your EDMX model designer.
  • On the design surface Right Click –> Add Code Generation Item…
  • Select Online templates.
  • Select EF 4.x DbContext Generator for C#.
  • Click ‘Add’.

Notice that two items are added to your project:

  • (This template generates very simple POCO classes for each entity in your model)
  • (This template generates a derived DbContext to use for querying and persisting data)

3) Read/Write Data example:

 var dbContext = new YourModelClass(); //class derived from DbContext
 var contacts = from c in dbContext.Contacts select c; //read data
 contacts.FirstOrDefault().FirstName = "Alex"; //edit data
 dbContext.SaveChanges(); //save data to DB

Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.

Update and left outer join statements

If what you need is UPDATE from SELECT statement you can do something like this:

UPDATE suppliers    
SET city = (SELECT FROM customers

WHERE customers.customer_name = suppliers.supplier_name)

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Bad: (jsHint will throw a error)

for (var name in item) {


for (var name in item) {
  if (item.hasOwnProperty(name)) {

How do I find the absolute position of an element using jQuery?

.offset() will return the offset position of an element as a simple object, eg:

var position = $(element).offset(); // position = { left: 42, top: 567 }

You can use this return value to position other elements at the same spot:


jquery change style of a div on click

As what I have understand on your question, this is what you want.

Here is a jsFiddle of the below:

$('.childDiv').click(function() {_x000D_
  $(this).parent().find('.childDiv').css('background-color', '#ffffff');_x000D_
  $(this).css('background-color', '#ff0000');_x000D_
.parentDiv {_x000D_
  border: 1px solid black;_x000D_
  padding: 10px;_x000D_
  width: 80px;_x000D_
  margin: 5px;_x000D_
  display: relative;_x000D_
.childDiv {_x000D_
  border: 1px solid blue;_x000D_
  height: 50px;_x000D_
  margin: 10px;_x000D_
<script src=""></script>_x000D_
<div id="divParent1" class="parentDiv">_x000D_
  Group 1_x000D_
  <div id="child1" class="childDiv">_x000D_
    Child 1_x000D_
  <div id="child2" class="childDiv">_x000D_
    Child 2_x000D_
<div id="divParent2" class="parentDiv">_x000D_
  Group 2_x000D_
  <div id="child1" class="childDiv">_x000D_
    Child 1_x000D_
  <div id="child2" class="childDiv">_x000D_
    Child 2_x000D_

How to break out of multiple loops?

First, you may also consider making the process of getting and validating the input a function; within that function, you can just return the value if its correct, and keep spinning in the while loop if not. This essentially obviates the problem you solved, and can usually be applied in the more general case (breaking out of multiple loops). If you absolutely must keep this structure in your code, and really don't want to deal with bookkeeping booleans...

You may also use goto in the following way (using an April Fools module from here):

#import the stuff
from goto import goto, label

while True:
    #snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y": goto .breakall
        if ok == "n" or ok == "N": break
    #do more processing with menus and stuff
label .breakall

I know, I know, "thou shalt not use goto" and all that, but it works well in strange cases like this.

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Should image size be defined in the img tag height/width attributes or in CSS?

I'm using contentEditable to allow rich text editing in my app. I don't know how it slips through, but when an image is inserted, and then resized (by dragging the anchors on its side), it generates something like this:

  <img style="width:55px;height:55px" width="100" height="100" src="pic.gif" border=0/>

(subsequent testing shown that inserted images did not contain this "rogue" style attr+param).

When rendered by the browser (IE7), the width and height in the style overrides the img width/height param (so the image is shown like how I wanted it.. resized to 55px x 55px. So everything went well so it seems.

When I output the page to a ms-word document via setting the mime type application/msword or pasting the browser rendering to msword document, all the images reverted back to its default size. I finally found out that msword is discarding the style and using the img width and height tag (which has the value of the original image size).

Took me a while to found this out. Anyway... I've coded a javascript function to traverse all tags and "transferring" the img style.width and style.height values into the img.width and img.height, then clearing both the values in style, before I proceed saving this piece of html/richtext data into the database.


opps.. my answer is.. no. leave both attributes directly under img, rather than style.

Hello World in Python

print("Hello, World!")

You are probably using Python 3.0, where print is now a function (hence the parenthesis) instead of a statement.

Where to find free public Web Services? -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.

What are the basic rules and idioms for operator overloading?

The General Syntax of operator overloading in C++

You cannot change the meaning of operators for built-in types in C++, operators can only be overloaded for user-defined types1. That is, at least one of the operands has to be of a user-defined type. As with other overloaded functions, operators can be overloaded for a certain set of parameters only once.

Not all operators can be overloaded in C++. Among the operators that cannot be overloaded are: . :: sizeof typeid .* and the only ternary operator in C++, ?:

Among the operators that can be overloaded in C++ are these:

  • arithmetic operators: + - * / % and += -= *= /= %= (all binary infix); + - (unary prefix); ++ -- (unary prefix and postfix)
  • bit manipulation: & | ^ << >> and &= |= ^= <<= >>= (all binary infix); ~ (unary prefix)
  • boolean algebra: == != < > <= >= || && (all binary infix); ! (unary prefix)
  • memory management: new new[] delete delete[]
  • implicit conversion operators
  • miscellany: = [] -> ->* , (all binary infix); * & (all unary prefix) () (function call, n-ary infix)

However, the fact that you can overload all of these does not mean you should do so. See the basic rules of operator overloading.

In C++, operators are overloaded in the form of functions with special names. As with other functions, overloaded operators can generally be implemented either as a member function of their left operand's type or as non-member functions. Whether you are free to choose or bound to use either one depends on several criteria.2 A unary operator @3, applied to an object x, is invoked either as operator@(x) or as x.operator@(). A binary infix operator @, applied to the objects x and y, is called either as operator@(x,y) or as x.operator@(y).4

Operators that are implemented as non-member functions are sometimes friend of their operand’s type.

1 The term “user-defined” might be slightly misleading. C++ makes the distinction between built-in types and user-defined types. To the former belong for example int, char, and double; to the latter belong all struct, class, union, and enum types, including those from the standard library, even though they are not, as such, defined by users.

2 This is covered in a later part of this FAQ.

3 The @ is not a valid operator in C++ which is why I use it as a placeholder.

4 The only ternary operator in C++ cannot be overloaded and the only n-ary operator must always be implemented as a member function.

Continue to The Three Basic Rules of Operator Overloading in C++.

C# loop - break vs. continue

I used to always get confused whether I should use break, or continue. This is what helps me remember:

When to use break vs continue?

  1. Break - it's like breaking up. It's sad, you guys are parting. The loop is exited.


  1. Continue - means that you're gonna give today a rest and sort it all out tomorrow (i.e. skip the current iteration)!


MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In case anybody comes back to this, I think the problem here was failing to install the parent pom first, which all these submodules depend on, so the Maven Reactor can't collect the necessary dependencies to build the submodule.

So from the root directory (here D:\luna_workspace\empire_club\empirecl) it probably just needs a:

mvn clean install

(Aside: <relativePath>../pom.xml</relativePath> is not really necessary as it's the default value).

Is there a math nCr function in python?

The following program calculates nCr in an efficient manner (compared to calculating factorials etc.)

import operator as op
from functools import reduce

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom  # or / in Python 2

As of Python 3.8, binomial coefficients are available in the standard library as math.comb:

>>> from math import comb
>>> comb(10,3)

Name attribute in @Entity and @Table

@Table's name attribute is the actual table name. @Entitiy's name is useful if you have two @Entity classes with the same name and you need a way to differentiate them when running queries.

How to use this boolean in an if statement?

Since stop is boolean you can change that part to:

if(stop) // Or to: if (stop == true)
return sb.toString();

Return zero if no record is found

You can also try: (I tried this and it worked for me)

SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;

Sending data through POST request from a node.js server to a node.js server

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');'', {
    hello: 'world'
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)

Image inside div has extra space below the image

Another option suggested in this blog post is setting the style of the image as style="display: block;"

jQuery delete confirmation box

    if (!confirm("Do you want to delete")){
      return false;

How do I make a column unique and index it in a Ruby on Rails migration?

The short answer for old versions of Rails (see other answers for Rails 4+):

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name,

add_index :table_name, [:column_name_a, :column_name_b], unique: true

If you get "index name... is too long", you can add name: "whatever" to the add_index method to make the name shorter.

For fine-grained control, there's a "execute" method that executes straight SQL.

That's it!

If you are doing this as a replacement for regular old model validations, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 


string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           out date))

No 'Access-Control-Allow-Origin' header in Angular 2 app

Another simple way, without installing anything

  1. HTTP function

    authenticate(credentials) {
    let body = new URLSearchParams();
    body.set('username', credentials.username);
    body.set('password', credentials.password);
    return, body)
      data => this.loginResult = data,
      error => {
      () => {
      // function to execute after successfull api call
  2. Create a proxy.conf.json file

     "/rest": {
    "target": "",
    "pathRewrite": {
      "^/rest": ""
    "secure": false
  3. then ng serve --proxy-config proxy.conf.json (or) open package.json and replace

    "scripts": {
    "start": "ng serve --proxy-config proxy.conf.json",

and then npm start

That's it.

Check here for more options

What is the difference between compileSdkVersion and targetSdkVersion?

Late to the game.. and there are several great answers above-- essentially, that the compileSdkVersion is the version of the API the app is compiled against, while the targetSdkVersion indicates the version that the app was tested against.

I'd like to supplement those answers with the following notes:

  1. That targetSdkVersion impacts the way in which permissions are requested:
  • If the device is running Android 6.0 (API level 23) or higher, and the app's targetSdkVersion is 23 or higher, the app requests permissions from the user at run-time.
  • If the device is running Android 5.1 (API level 22) or lower, or the app's targetSdkVersion is 22 or lower, the system asks the user to grant the permissions when the user installs the app.
  1. If the compileSdkVersion is higher than the version declared by your app's targetSdkVersion, the system may enable compatibility behaviors to ensure that your app continues to work the way you expect. (ref)

  2. With each new Android release...

  • targetSdkVersion should be incremented to match the latest API level, then thoroughly test your application on the corresponding platform version
  • compileSdkVersion, on the other hand, does not need to be changed unless you're adding features exclusive to the new platform version
  • As a result, while targetSdkVersion is often (initially) less than than the compileSdkVersion, it's not uncommon to see a well-maintained/established app with targetSdkVersion > compileSdkVersion

What is the difference between a process and a thread?

For those who are more comfortable with learning by visualizing, here is a handy diagram I created to explain Process and Threads.
I used the information from MSDN - About Processes and Threads

Processes and Threads

Progress during large file copy (Copy-Item & Write-Progress?)

Trevor Sullivan has a write-up on how to add a command called Copy-ItemWithProgress to PowerShell on Robocopy.

How do I get a human-readable file size in bytes abbreviation using .NET?

If you are trying to match the size as shown in Windows Explorer's detail view, this is the code you want:

[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern long StrFormatKBSize(
    long qdw,
    [MarshalAs(UnmanagedType.LPTStr)] StringBuilder pszBuf,
    int cchBuf);

public static string BytesToString(long byteCount)
    var sb = new StringBuilder(32);
    StrFormatKBSize(byteCount, sb, sb.Capacity);
    return sb.ToString();

This will not only match Explorer exactly but will also provide the strings translated for you and match differences in Windows versions (for example in Win10, K = 1000 vs. previous versions K = 1024).

Post an object as data using Jquery Ajax

Is not necessary to pass the data as JSON string, you can pass the object directly, without defining contentType or dataType, like this:

    type: "POST",
    url: "TelephoneNumbers.aspx/DeleteNumber",
    data: data0,

    success: function(data)

Creating a daemon in Linux

In Linux i want to add a daemon that cannot be stopped and which monitors filesystem changes. If any changes would be detected it should write the path to the console where it was started + a newline.

Daemons work in the background and (usually...) don't belong to a TTY that's why you can't use stdout/stderr in the way you probably want. Usually a syslog daemon (syslogd) is used for logging messages to files (debug, error,...).

Besides that, there are a few required steps to daemonize a process.

If I remember correctly these steps are:

  • fork off the parent process & let it terminate if forking was successful. -> Because the parent process has terminated, the child process now runs in the background.
  • setsid - Create a new session. The calling process becomes the leader of the new session and the process group leader of the new process group. The process is now detached from its controlling terminal (CTTY).
  • Catch signals - Ignore and/or handle signals.
  • fork again & let the parent process terminate to ensure that you get rid of the session leading process. (Only session leaders may get a TTY again.)
  • chdir - Change the working directory of the daemon.
  • umask - Change the file mode mask according to the needs of the daemon.
  • close - Close all open file descriptors that may be inherited from the parent process.

To give you a starting point: Look at this skeleton code that shows the basic steps. This code can now also be forked on GitHub: Basic skeleton of a linux daemon

 * daemonize.c
 * This example daemonizes a process, writes a few log messages,
 * sleeps 20 seconds and terminates afterwards.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>

static void skeleton_daemon()
    pid_t pid;

    /* Fork off the parent process */
    pid = fork();

    /* An error occurred */
    if (pid < 0)

    /* Success: Let the parent terminate */
    if (pid > 0)

    /* On success: The child process becomes session leader */
    if (setsid() < 0)

    /* Catch, ignore and handle signals */
    //TODO: Implement a working signal handler */
    signal(SIGCHLD, SIG_IGN);
    signal(SIGHUP, SIG_IGN);

    /* Fork off for the second time*/
    pid = fork();

    /* An error occurred */
    if (pid < 0)

    /* Success: Let the parent terminate */
    if (pid > 0)

    /* Set new file permissions */

    /* Change the working directory to the root directory */
    /* or another appropriated directory */

    /* Close all open file descriptors */
    int x;
    for (x = sysconf(_SC_OPEN_MAX); x>=0; x--)
        close (x);

    /* Open the log file */
    openlog ("firstdaemon", LOG_PID, LOG_DAEMON);
int main()

    while (1)
        //TODO: Insert daemon code here.
        syslog (LOG_NOTICE, "First daemon started.");
        sleep (20);

    syslog (LOG_NOTICE, "First daemon terminated.");

    return EXIT_SUCCESS;

  • Compile the code: gcc -o firstdaemon daemonize.c
  • Start the daemon: ./firstdaemon
  • Check if everything is working properly: ps -xj | grep firstdaemon

  • The output should be similar to this one:

|    1 | 3387 | 3386 | 3386 | ?   |    -1 | S    | 1000 | 0:00 | ./  |

What you should see here is:

  • The daemon has no controlling terminal (TTY = ?)
  • The parent process ID (PPID) is 1 (The init process)
  • The PID != SID which means that our process is NOT the session leader
    (because of the second fork())
  • Because PID != SID our process can't take control of a TTY again

Reading the syslog:

  • Locate your syslog file. Mine is here: /var/log/syslog
  • Do a: grep firstdaemon /var/log/syslog

  • The output should be similar to this one:

  firstdaemon[3387]: First daemon started.
  firstdaemon[3387]: First daemon terminated.

A note: In reality you would also want to implement a signal handler and set up the logging properly (Files, log levels...).

Further reading:

Formula px to dp, dp to px android

px to dp:

int valueInpx = ...;
int valueInDp= (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, valueInpx , getResources()

Java ArrayList - how can I tell if two lists are equal, order not mattering?

It is an alternative way to check equality of array lists which can contain null values:

List listA = Arrays.asList(null, "b", "c");
List listB = Arrays.asList("b", "c", null);

System.out.println(checkEquality(listA, listB)); // will return TRUE

private List<String> getSortedArrayList(List<String> arrayList)
    String[] array = arrayList.toArray(new String[arrayList.size()]);

    Arrays.sort(array, new Comparator<String>()
        public int compare(String o1, String o2)
            if (o1 == null && o2 == null)
                return 0;
            if (o1 == null)
                return 1;
            if (o2 == null)
                return -1;
            return o1.compareTo(o2);

    return new ArrayList(Arrays.asList(array));

private Boolean checkEquality(List<String> listA, List<String> listB)
    listA = getSortedArrayList(listA);
    listB = getSortedArrayList(listB);

    String[] arrayA = listA.toArray(new String[listA.size()]);
    String[] arrayB = listB.toArray(new String[listB.size()]);

    return Arrays.deepEquals(arrayA, arrayB);

Difference between iCalendar (.ics) and the vCalendar (.vcs)

You can try VCS to ICS file converter (Java, works with Windows, Mac, Linux etc.). It has the feature of parsing events and todos. You can convert the VCS generated by your Nokia phone, with bluetooth export or via nbuexplorer.

  • Complete support for UTF-8
  • Quoted-printable encoded strings
  • Completely open source code (GPLv3 and Apache 2.0)
  • Standard iCalendar v2.0 output
  • Encodes multiple files at once (only one event per file)
  • Compatible with Android, iOS, Mozilla Lightning/Sunbird, Google Calendar and others
  • Multiplatform

Android/Java - Date Difference in days

There's a simple solution, that at least for me, is the only feasible solution.

The problem is that all the answers I see being tossed around - using Joda, or Calendar, or Date, or whatever - only take the amount of milliseconds into consideration. They end up counting the number of 24-hour cycles between two dates, rather than the actual number of days. So something from Jan 1st 11pm to Jan 2nd 1am will return 0 days.

To count the actual number of days between startDate and endDate, simply do:

// Find the sequential day from a date, essentially resetting time to start of the day
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;

// Find the difference, duh
long daysBetween = endDay - startDay;

This will return "1" between Jan 2nd and Jan 1st. If you need to count the end day, just add 1 to daysBetween (I needed to do that in my code since I wanted to count the total number of days in the range).

This is somewhat similar to what Daniel has suggested but smaller code I suppose.

Access PHP variable in JavaScript

I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>

And then in your JavaScript:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;

Debugging Spring configuration

Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or, If you are using log4j xml config you can do some thing like this

<category name="org.springframework.beans">
    <priority value="debug" />


<category name="org.springframework">
    <priority value="debug" />

I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here

public class SpringDAOTest 
    private SpringDAO dao;

    private ApplicationContext appContext;

    public void checkConfig()
        AnySpringBean bean =  appContext.getBean(AnySpringBean.class);


I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file



UPDATE log4j config file

I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="" debug="false">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />

    <appender name="springAppender" class="org.apache.log4j.RollingFileAppender"> 
        <param name="file" value="C:/tomcatLogs/webApp/spring-details.log" /> 
        <param name="append" value="true" /> 
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{MM/dd/yyyy HH:mm:ss}  [%t]:%c{5}.%M()%L %m%n" />

    <category name="org.springframework">
        <priority value="debug" />

    <category name="org.springframework.beans">
        <priority value="debug" />

    <category name="">
        <priority value="debug" />

        <priority value="debug" />

    <category name="org.springframework.jdbc.core">
        <priority value="debug" />

    <category name="">
        <priority value="debug" />

        <priority value="debug" />
        <appender-ref ref="springAppender" />
        <!-- <appender-ref ref="STDOUT"/>  -->

How to set a value for a selectize.js input?

Here is my full code using tag from remote search. Hope this is helpful.

valueField: 'id',
labelField: 'name',
searchField: 'name',
options: [],
delimiter: ',',
persist: false,
create: false,
load: function(query, callback) {
    if (!query.length) return callback();
        url: '/api/all_cities.php',
        type: 'GET',
        dataType: 'json',
        data: {
            name: query,
        error: function() {
        success: function(res) {
onInitialize: function(){
    var selectize = this;
    $.get("/api/selected_cities.php", function( data ) {
        selectize.addOption(data); // This is will add to option
        var selected_items = [];
        $.each(data, function( i, obj) {
        selectize.setValue(selected_items); //this will set option values as default

Number of visitors on a specific page

As Blexy already answered, go to "Behavior > Site Content > All Pages".

Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:


How can I center <ul> <li> into div

To center a block object (e.g. the ul) you need to set a width on it and then you can set that objects left and right margins to auto.

To center the inline content of block object (e.g. the inline content of li) you can set the css property text-align: center;.

Convert pyspark string to date format

possibly not so many answers so thinking to share my code which can help someone

from pyspark.sql import SparkSession
from pyspark.sql.functions import to_date

spark = SparkSession.builder.appName("Python Spark SQL basic example")\
    .config("spark.some.config.option", "some-value").getOrCreate()

df = spark.createDataFrame([('2019-06-22',)], ['t'])
df1 =, 'yyyy-MM-dd').alias('dt'))
print df1


DataFrame[dt: date]
|        dt|

the above code to convert to date if you want to convert datetime then use to_timestamp. let me know if you have any doubt.

What is the fastest way to transpose a matrix in C++?

This is going to depend on your application but in general the fastest way to transpose a matrix would be to invert your coordinates when you do a look up, then you do not have to actually move any data.

mysqli_fetch_array while loop columns

Try this...

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

How to kill zombie process

Sometimes the parent ppid cannot be killed, hence kill the zombie pid

kill -9 $(ps -A -ostat,pid | awk '/[zZ]/{ print $2 }')

Pandas column of lists, create a row for each list element

For those looking for a version of Roman Pekar's answer that avoids manual column naming:

column_to_explode = 'samples'
res = (df
       .set_index([x for x in df.columns if x != column_to_explode])[column_to_explode]
res = res.rename(columns={
          res.columns[-1]: '{}_exploded'.format(column_to_explode)})

System.Security.SecurityException when writing to Event Log

I ran into the same issue, but I had to go up one level and give full access to everyone to the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\ key, instead of going down to security, that cleared up the issue for me.

changing visibility using javascript

If you just want to display it when you get a response add this to your loadpage()

function loadpage(page_request, containerid){
   if (page_request.readyState == 4 && page_request.status==200) { 
      var container = document.getElementById(containerid);
      container.innerHTML=page_request.responseText; = 'visible';
      // or = 'block';

but this depend entirely on how you hid the div in the first place

How to create a multi line body in C# System.Net.Mail.MailMessage

Try using the verbatim operator "@" before your message:

message.Body = 

Consider that also the distance of the text from the left margin affects on the real distance from the email body left margin..

React Native - Image Require Module using Dynamic Names

As the React Native Documentation says, all your images sources needs to be loaded before compiling your bundle

So another way you can use dynamic images it's using a switch statement. Let's say you want to display a different avatar for a different character, you can do something like this:

class App extends Component {
  state = { avatar: "" }

  get avatarImage() {
    switch (this.state.avatar) {
      case "spiderman":
        return require('./spiderman.png');
      case "batman":
        return require('./batman.png');
      case "hulk":
        return require('./hulk.png');
        return require('./no-image.png');

  render() {
    return <Image source={this.avatarImage} />

Check the snack:

Also, remember if your image it's online you don't have any problems, you can do:

let superhero = "spiderman";

<Image source={{ uri: `${superhero}.png` }} />

How to get the Development/Staging/production Hosting Environment in ConfigureServices

You can easily access it in ConfigureServices, just persist it to a property during Startup method which is called first and gets it passed in, then you can access the property from ConfigureServices.

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    ...your code here...
    CurrentEnvironment = env;

private IHostingEnvironment CurrentEnvironment{ get; set; } 

public void ConfigureServices(IServiceCollection services)
    string envName = CurrentEnvironment.EnvironmentName;
    ... your code here...

Structure of a PDF file?

When I first started working with PDF, I found the PDF reference very hard to navigate. It might help you to know that the overview of the file structure is found in syntax, and what Adobe call the document structure is the object structure and not the file structure. That is also found in Syntax. The description of operators is hidden away in Appendix A - very useful for understanding what is happening in content streams. If you ever have the pain of working with colour spaces you will find that hidden in Graphics! Hopefully these pointers will help you find things more quickly than I did.

If you are using windows, pdftron CosEdit allows you to browse the object structure to understand it. There is a free demo available that allows you to examine the file but not save it.

Easy way to use variables of enum types as string in C?

The technique from Making something both a C identifier and a string? can be used here.

As usual with such preprocessor stuff, writing and understanding the preprocessor part can be hard, and includes passing macros to other macros and involves using # and ## operators, but using it is real easy. I find this style very useful for long enums, where maintaining the same list twice can be really troublesome.

Factory code - typed only once, usually hidden in the header:


// expansion macro for enum value definition
#define ENUM_VALUE(name,assign) name assign,

// expansion macro for enum to string conversion
#define ENUM_CASE(name,assign) case name: return #name;

// expansion macro for string to enum conversion
#define ENUM_STRCMP(name,assign) if (!strcmp(str,#name)) return name;

/// declare the access function and define enum values
#define DECLARE_ENUM(EnumType,ENUM_DEF) \
  enum EnumType { \
  }; \
  const char *GetString(EnumType dummy); \
  EnumType Get##EnumType##Value(const char *string); \

/// define the access function names
#define DEFINE_ENUM(EnumType,ENUM_DEF) \
  const char *GetString(EnumType value) \
  { \
    switch(value) \
    { \
      default: return ""; /* handle input error */ \
    } \
  } \
  EnumType Get##EnumType##Value(const char *str) \
  { \
    return (EnumType)0; /* handle input error */ \
  } \

Factory used


#include "enumFactory.h"
#define SOME_ENUM(XX) \
    XX(FirstValue,) \
    XX(SecondValue,) \
    XX(SomeOtherValue,=50) \
    XX(OneMoreValue,=100) \



#include "someEnum.h"

The technique can be easily extended so that XX macros accepts more arguments, and you can also have prepared more macros to substitute for XX for different needs, similar to the three I have provided in this sample.

Comparison to X-Macros using #include / #define / #undef

While this is similar to X-Macros others have mentioned, I think this solution is more elegant in that it does not require #undefing anything, which allows you to hide more of the complicated stuff is in the factory the header file - the header file is something you are not touching at all when you need to define a new enum, therefore new enum definition is a lot shorter and cleaner.

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

it's very simple we can use a parent element div to wrap all the element or we can use the Higher Order Component( HOC's ) concept i.e very useful for react js applications

render() {
  return (

or another best way is HOC its very simple not very complicated just add a file hoc.js in your project and simply add these codes

const aux = (props) => props.children;
export default aux;

now import hoc.js file where you want to use, now instead of wrapping with div element we can wrap with hoc.

import React, { Component } from 'react';
import Hoc from '../../../hoc';

    render() {
      return (

Are 2 dimensional Lists possible in c#?

another work around which i have used was...

List<int []> itemIDs = new List<int[]>();

itemIDs.Add( new int[2] { 101, 202 } );

The library i'm working on has a very formal class structure and i didn't wan't extra stuff in there effectively for the privilege of recording two 'related' ints.

Relies on the programmer entering only a 2 item array but as it's not a common item i think it works.

how to destroy bootstrap modal window completely?

if is bootstrap 3 you can use:

$("#mimodal").on('', function () {
    $(this).data('bs.modal', null);

bad operand types for binary operator "&" java

You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.

if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){


if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){

PHP absolute path to root

You can access the $_SERVER['DOCUMENT_ROOT'] variable :

   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/subdir1/yourdocument.txt";

Run Python script at startup in Ubuntu


  • Copy the python file to /bin:

    sudo cp -i /path/to/ /bin

  • Add A New Cron Job:

    sudo crontab -e

    Scroll to the bottom and add the following line (after all the #'s):

    @reboot python /bin/ &

    The “&” at the end of the line means the command is run in the background and it won’t stop the system booting up.

  • Test it:

    sudo reboot

Practical example:

  • Add this file to your Desktop: (run it to check that it works for you)

    from os.path import expanduser
    import datetime
    file = open(expanduser("~") + '/Desktop/HERE.txt', 'w')
    file.write("It worked!\n" + str(
  • Run the following commands:

    sudo cp -i ~/Desktop/ /bin

    sudo crontab -e

  • Add the following line and save it:

    @reboot python /bin/ &

  • Now reboot your computer and you should find a new file on your Desktop: HERE.txt

Fast Linux file count for a large number of files

ls spends more time sorting the files names. Use -f to disable the sorting, which will save some time:

ls -f | wc -l

Or you can use find:

find . -type f | wc -l

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

Yes it does. If you're using the emulator, it will show in the Logcat view under the System.out tag. Write something and try it in your emulator.