Programs & Examples On #Nss

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Check that you have the correct rights set on CA certificates bundle. Usually, that means read access for everyone to CA files in the /etc/ssl/certs directory, for instance /etc/ssl/certs/ca-certificates.crt.

You can see what files have been configured for you curl version with the

curl-config --configure
command :

$ curl-config --configure
 '--prefix=/usr' 
 '--mandir=/usr/share/man' 
 '--disable-dependency-tracking' 
 '--disable-ldap' 
 '--disable-ldaps' 
 '--enable-ipv6' 
 '--enable-manual' 
 '--enable-versioned-symbols' 
 '--enable-threaded-resolver' 
 '--without-libidn' 
 '--with-random=/dev/urandom' 
 '--with-ca-bundle=/etc/ssl/certs/ca-certificates.crt' 
 'CFLAGS=-march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4' 'LDFLAGS=-Wl,-O1,--sort-common,--as-needed,-z,relro' 
 'CPPFLAGS=-D_FORTIFY_SOURCE=2'

Here you need read access to /etc/ssl/certs/ca-certificates.crt

$ curl-config --configure
 '--build' 'i486-linux-gnu' 
 '--prefix=/usr' 
 '--mandir=/usr/share/man' 
 '--disable-dependency-tracking' 
 '--enable-ipv6' 
 '--with-lber-lib=lber' 
 '--enable-manual' 
 '--enable-versioned-symbols' 
 '--with-gssapi=/usr' 
 '--with-ca-path=/etc/ssl/certs' 
 'build_alias=i486-linux-gnu' 
 'CFLAGS=-g -O2' 
 'LDFLAGS=' 
 'CPPFLAGS='

And the same here.

Android Design Support Library expandable Floating Action Button(FAB) menu

  • First create the menu layouts in the your Activity layout xml file. For e.g. a linear layout with horizontal orientation and include a TextView for label then a Floating Action Button beside the TextView.

  • Create the menu layouts as per your need and number.

  • Create a Base Floating Action Button and on its click of that change the visibility of the Menu Layouts.

Please check the below code for the reference and for more info checkout my project from github

Checkout project from Github

<android.support.constraint.ConstraintLayout
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.app.fabmenu.MainActivity">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/baseFloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:clickable="true"
                android:onClick="@{FabHandler::onBaseFabClick}"
                android:tint="@android:color/white"
                app:fabSize="normal"
                app:layout_constraintBottom_toBottomOf="@+id/activity_main"
                app:layout_constraintRight_toRightOf="@+id/activity_main"
                app:srcCompat="@drawable/ic_add_black_24dp" />

            <LinearLayout
                android:id="@+id/shareLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="12dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/createLayout"
                app:layout_constraintLeft_toLeftOf="@+id/createLayout"
                app:layout_constraintRight_toRightOf="@+id/activity_main">

                <TextView
                    android:id="@+id/shareLabelTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:background="@drawable/shape_fab_label"
                    android:elevation="2dp"
                    android:fontFamily="sans-serif"
                    android:padding="5dip"
                    android:text="Share"
                    android:textColor="@android:color/white"
                    android:typeface="normal" />


                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/shareFab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:onClick="@{FabHandler::onShareFabClick}"
                    android:tint="@android:color/white"
                    app:fabSize="mini"
                    app:srcCompat="@drawable/ic_share_black_24dp" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/createLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="24dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/baseFloatingActionButton"
                app:layout_constraintRight_toRightOf="@+id/activity_main">

                <TextView
                    android:id="@+id/createLabelTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:background="@drawable/shape_fab_label"
                    android:elevation="2dp"
                    android:fontFamily="sans-serif"
                    android:padding="5dip"
                    android:text="Create"
                    android:textColor="@android:color/white"
                    android:typeface="normal" />

                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/createFab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:onClick="@{FabHandler::onCreateFabClick}"
                    android:tint="@android:color/white"
                    app:fabSize="mini"
                    app:srcCompat="@drawable/ic_create_black_24dp" />

            </LinearLayout>

        </android.support.constraint.ConstraintLayout>

These are the animations-

Opening animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
    android:duration="300"
    android:fromXScale="0"
    android:fromYScale="0"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="1"
    android:toYScale="1" />
<alpha
    android:duration="300"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />

</set>

Closing animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
    android:duration="300"
    android:fromXScale="1"
    android:fromYScale="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="0.0"
    android:toYScale="0.0" />
<alpha
    android:duration="300"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />
</set>

Then in my Activity I've simply used the animations above to show and hide the FAB menu :

Show Fab Menu:

  private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabOpenAnimation);
    binding.shareLayout.startAnimation(fabOpenAnimation);
    binding.createFab.setClickable(true);
    binding.shareFab.setClickable(true);
    isFabMenuOpen = true;

}

Close Fab Menu:

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabCloseAnimation);
    binding.shareLayout.startAnimation(fabCloseAnimation);
    binding.createFab.setClickable(false);
    binding.shareFab.setClickable(false);
    isFabMenuOpen = false;

}

Here is the the Activity class -

package com.app.fabmenu;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;

import com.app.fabmenu.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

private ActivityMainBinding binding;
private Animation fabOpenAnimation;
private Animation fabCloseAnimation;
private boolean isFabMenuOpen = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    binding = DataBindingUtil.setContentView(this,    R.layout.activity_main);
    binding.setFabHandler(new FabHandler());

    getAnimations();


}

private void getAnimations() {

    fabOpenAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_open);

    fabCloseAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_close);

}

private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabOpenAnimation);
    binding.shareLayout.startAnimation(fabOpenAnimation);
    binding.createFab.setClickable(true);
    binding.shareFab.setClickable(true);
    isFabMenuOpen = true;


}

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabCloseAnimation);
    binding.shareLayout.startAnimation(fabCloseAnimation);
    binding.createFab.setClickable(false);
    binding.shareFab.setClickable(false);
    isFabMenuOpen = false;

}


public class FabHandler {

    public void onBaseFabClick(View view) {

        if (isFabMenuOpen)
            collapseFabMenu();
        else
            expandFabMenu();


    }

    public void onCreateFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Create FAB tapped", Snackbar.LENGTH_SHORT).show();

    }

    public void onShareFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Share FAB tapped", Snackbar.LENGTH_SHORT).show();

    }


}

@Override
public void onBackPressed() {

    if (isFabMenuOpen)
        collapseFabMenu();
    else
        super.onBackPressed();
}
}

Here are the screenshots

Floating Action Menu with Label Textview in new Cursive Font Family of Android

Floating Action Menu with Label Textview in new Roboto Font Family of Android

iOS 7 status bar overlapping UI

Place this code snippet in your MainViewController.m file in the phonegap project.

- (void)viewDidLayoutSubviews{

    if ([self respondsToSelector:@selector(topLayoutGuide)]) // iOS 7 or above
    {
        CGFloat top = self.topLayoutGuide.length;
        if(self.webView.frame.origin.y == 0){
            // We only want to do this once, or 
            // if the view has somehow been "restored" by other    code.
            self.webView.frame = CGRectMake(self.webView.frame.origin.x,
                                           self.webView.frame.origin.y + top,
                                           self.webView.frame.size.width,
                                           self.webView.frame.size.height-top);
        } 
    } 
}

How to use SVG markers in Google Maps API v3

OK! I done this soon in my web,I try two ways to create the custom google map marker, this run code use canvg.js is the best compatibility for browser.the Commented-Out Code is not support IE11 urrently.

_x000D_
_x000D_
var marker;_x000D_
var CustomShapeCoords = [16, 1.14, 21, 2.1, 25, 4.2, 28, 7.4, 30, 11.3, 30.6, 15.74, 25.85, 26.49, 21.02, 31.89, 15.92, 43.86, 10.92, 31.89, 5.9, 26.26, 1.4, 15.74, 2.1, 11.3, 4, 7.4, 7.1, 4.2, 11, 2.1, 16, 1.14];_x000D_
_x000D_
function initMap() {_x000D_
  var map = new google.maps.Map(document.getElementById('map'), {_x000D_
    zoom: 13,_x000D_
    center: {_x000D_
      lat: 59.325,_x000D_
      lng: 18.070_x000D_
    }_x000D_
  });_x000D_
  var markerOption = {_x000D_
    latitude: 59.327,_x000D_
    longitude: 18.067,_x000D_
    color: "#" + "000",_x000D_
    text: "ha"_x000D_
  };_x000D_
  marker = createMarker(markerOption);_x000D_
  marker.setMap(map);_x000D_
  marker.addListener('click', changeColorAndText);_x000D_
};_x000D_
_x000D_
function changeColorAndText() {_x000D_
  var iconTmpObj = createSvgIcon( "#c00", "ok" );_x000D_
  marker.setOptions( {_x000D_
                icon: iconTmpObj_x000D_
            } );_x000D_
};_x000D_
_x000D_
function createMarker(options) {_x000D_
  //IE MarkerShape has problem_x000D_
  var markerObj = new google.maps.Marker({_x000D_
    icon: createSvgIcon(options.color, options.text),_x000D_
    position: {_x000D_
      lat: parseFloat(options.latitude),_x000D_
      lng: parseFloat(options.longitude)_x000D_
    },_x000D_
    draggable: false,_x000D_
    visible: true,_x000D_
    zIndex: 10,_x000D_
    shape: {_x000D_
      coords: CustomShapeCoords,_x000D_
      type: 'poly'_x000D_
    }_x000D_
  });_x000D_
_x000D_
  return markerObj;_x000D_
};_x000D_
_x000D_
function createSvgIcon(color, text) {_x000D_
  var div = $("<div></div>");_x000D_
_x000D_
  var svg = $(_x000D_
    '<svg width="32px" height="43px"  viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">' +_x000D_
    '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>' +_x000D_
    '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>' +_x000D_
    '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>' +_x000D_
    '</svg>'_x000D_
  );_x000D_
  div.append(svg);_x000D_
_x000D_
  var dd = $("<canvas height='50px' width='50px'></cancas>");_x000D_
_x000D_
  var svgHtml = div[0].innerHTML;_x000D_
_x000D_
  canvg(dd[0], svgHtml);_x000D_
_x000D_
  var imgSrc = dd[0].toDataURL("image/png");_x000D_
  //"scaledSize" and "optimized: false" together seems did the tricky ---IE11  &&  viewBox influent IE scaledSize_x000D_
  //var svg = '<svg width="32px" height="43px"  viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">'_x000D_
  //    + '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>'_x000D_
  //    + '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>'_x000D_
  //    + '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>'_x000D_
  //    + '</svg>';_x000D_
  //var imgSrc = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);_x000D_
_x000D_
  var iconObj = {_x000D_
    size: new google.maps.Size(32, 43),_x000D_
    url: imgSrc,_x000D_
    scaledSize: new google.maps.Size(32, 43)_x000D_
  };_x000D_
_x000D_
  return iconObj;_x000D_
};
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <title>Your Custom Marker </title>_x000D_
  <style>_x000D_
    /* Always set the map height explicitly to define the size of the div_x000D_
       * element that contains the map. */_x000D_
    #map {_x000D_
      height: 100%;_x000D_
    }_x000D_
    /* Optional: Makes the sample page fill the window. */_x000D_
    html,_x000D_
    body {_x000D_
      height: 100%;_x000D_
      margin: 0;_x000D_
      padding: 0;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="map"></div>_x000D_
    <script src="https://canvg.github.io/canvg/canvg.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

In JDBC world, the normal practice (according the JDBC API) is that you use Class#forName() to load a JDBC driver. The JDBC driver should namely register itself in DriverManager inside a static block:

package com.dbvendor.jdbc;

import java.sql.Driver;
import java.sql.DriverManager;

public class MyDriver implements Driver {

    static {
        DriverManager.registerDriver(new MyDriver());
    }

    public MyDriver() {
        //
    }

}

Invoking Class#forName() will execute all static initializers. This way the DriverManager can find the associated driver among the registered drivers by connection URL during getConnection() which roughly look like follows:

public static Connection getConnection(String url) throws SQLException {
    for (Driver driver : registeredDrivers) {
        if (driver.acceptsURL(url)) {
            return driver.connect(url);
        }
    }
    throw new SQLException("No suitable driver");
}

But there were also buggy JDBC drivers, starting with the org.gjt.mm.mysql.Driver as well known example, which incorrectly registers itself inside the Constructor instead of a static block:

package com.dbvendor.jdbc;

import java.sql.Driver;
import java.sql.DriverManager;

public class BadDriver implements Driver {

    public BadDriver() {
        DriverManager.registerDriver(this);
    }

}

The only way to get it to work dynamically is to call newInstance() afterwards! Otherwise you will face at first sight unexplainable "SQLException: no suitable driver". Once again, this is a bug in the JDBC driver, not in your own code. Nowadays, no one JDBC driver should contain this bug. So you can (and should) leave the newInstance() away.

What integer hash function are good that accepts an integer hash key?

  • 32-bits multiplicative method (very fast) see @rafal

    #define hash32(x) ((x)*2654435761)
    #define H_BITS 24 // Hashtable size
    #define H_SHIFT (32-H_BITS)
    unsigned hashtab[1<<H_BITS]  
    .... 
    unsigned slot = hash32(x) >> H_SHIFT
    
  • 32-bits and 64-bits (good distribution) at : MurmurHash

  • Integer Hash Function

Platform.runLater and Task in JavaFX

One reason to use an explicite Platform.runLater() could be that you bound a property in the ui to a service (result) property. So if you update the bound service property, you have to do this via runLater():

In UI thread also known as the JavaFX Application thread:

...    
listView.itemsProperty().bind(myListService.resultProperty());
...

in Service implementation (background worker):

...
Platform.runLater(() -> result.add("Element " + finalI));
...

How can I get a user's media from Instagram without authenticating as a user?

Well, as /?__a=1 stopped working by now, it's better to use curl and parse the instagram page as written at this answer: Generate access token Instagram API, without having to log in?

Ignoring new fields on JSON objects using Jackson

Starting with Jackson version 2.4 and above there have been some changes. Here is how you do it now:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

..........................................................................

 ObjectMapper mapper = new ObjectMapper();
    // to prevent exception when encountering unknown property:
 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

Note: The @annotation based solution remains the same so if you like to use that see the other answers.

For more information see the 10 minutes Configuration tutorial at: https://github.com/FasterXML/jackson-databind

Anonymous method in Invoke call

For the sake of completeness, this can also be accomplished via an Action method/anonymous method combination:

//Process is a method, invoked as a method group
Dispatcher.Current.BeginInvoke((Action) Process);
//or use an anonymous method
Dispatcher.Current.BeginInvoke((Action)delegate => {
  SomeFunc();
  SomeOtherFunc();
});

Stylesheet not updating

I had a similar problem, made all the more infuriating by simply being very SLOW to update. I couldn't get my changes to take effect while working on the site to save my life (trying all manner of clearing my browser cache and cookies), but if I came back to the site later in the day or opened another browser, there they were.

I also solved the problem by disabling the Supercacher software at my host's cpanel (Siteground). You can also use the "flush" button for individual directories to test if that's it before disabling.

C# difference between == and Equals()

Note that there are two different types of equality in C#

1- Value Equality (For value types like int, DateTime and struct)

2- Reference Equality (For objects)

There are two basic standard protocols for implement equality checks.

1- The == and != operators.

2- The virtual Equals method.

The == and != are statically resolve, which means C# will make a compile-time decision as to which type will perform the comparison.

For instance the value-type

 int x = 50;
 int y = 50;
 Console.WriteLine (x == y); // True

but for reference type

 object x = 50;
 object y = 50;
 Console.WriteLine (x == y); // False 

The Equals() originally resoled at runtime according to operand actual type.

For instance, in the following example, at runtime, it will be decided that the Equals() will apply on int values, the result is true.

object x = 5;
object y = 5;
Console.WriteLine (x.Equals (y)); // True

However, for a reference type, it will use a reference equality check.

MyObject x = new MyObject();
MyObject y = x;
Console.WriteLine (x.Equals (y)); // True

Note that Equals() uses structural comparison for struct, which means it calls Equals on each field of a struct.

Check if a path represents a file or a folder

Please stick to the nio API to perform these checks

import java.nio.file.*;

static Boolean isDir(Path path) {
  if (path == null || !Files.exists(path)) return false;
  else return Files.isDirectory(path);
}

SQL Query to concatenate column values from multiple rows in Oracle

The LISTAGG analytic function was introduced in Oracle 11g Release 2, making it very easy to aggregate strings. If you are using 11g Release 2 you should use this function for string aggregation. Please refer below url for more information about string concatenation.

http://www.oracle-base.com/articles/misc/StringAggregationTechniques.php

String Concatenation

Limit String Length

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

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

Why does Maven have such a bad rep?

great idea - poor implementation.

I moved a project from Ant to Maven recently. It worked well at the end, but I had to use two different versions of maven-assembly-plugin and maven-jar-plugin in the same pom (got two profiles) because what worked in one version was broken in another.

So it was quite a headache. Documentation isn't always great but I must admit that it was relatively easy to google answers.

make sure you always specify versions of plugings you use. Don't expect that new version will be backwards compatible.

I think controversy comes from the fact that maven still evolves and the process is painful sometimes.

regards

v.

How to set the default value for radio buttons in AngularJS?

In Angular 2 this is how we can set the default value for radio button:

HTML:

<label class="form-check-label">
          <input type="radio" class="form-check-input" name="gender" 
          [(ngModel)]="gender" id="optionsRadios1" value="male">
          Male
</label>

In the Component Class set the value of 'gender' variable equal to the value of radio button:

gender = 'male';

Converting a datetime string to timestamp in Javascript

For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:

function convertDate(date) {

    // # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
    var dateTimeParts = date.split(' ');

    // # this assumes time format has NO SPACE between time and am/pm marks.
    if (dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {

        var theTime = dateTimeParts[1];

        // # strip out all except numbers and colon
        var ampm = theTime.replace(/[0-9:]/g, '');

        // # strip out all except letters (for AM/PM)
        var time = theTime.replace(/[[^a-zA-Z]/g, '');

        if (ampm == 'pm') {

            time = time.split(':');

            // # if time is 12:00, don't add 12
            if (time[0] == 12) {
                time = parseInt(time[0]) + ':' + time[1] + ':00';
            } else {
                time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
            }

        } else { // if AM

            time = time.split(':');

            // # if AM is less than 10 o'clock, add leading zero
            if (time[0] < 10) {
                time = '0' + time[0] + ':' + time[1] + ':00';
            } else {
                time = time[0] + ':' + time[1] + ':00';
            }
        }
    }
    // # create a new date object from only the date part
    var dateObj = new Date(dateTimeParts[0]);

    // # add leading zero to date of the month if less than 10
    var dayOfMonth = (dateObj.getDate() < 10 ? ("0" + dateObj.getDate()) : dateObj.getDate());

    // # parse each date object part and put all parts together
    var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;

    // # finally combine re-formatted date and re-formatted time!
    var date = new Date(yearMoDay + 'T' + time);

    return date;
}

Usage:

date = convertDate('11/15/2016 2:00pm');

Android ListView with onClick items

You start new activities with intents. One method to send data to an intent is to pass a class that implements parcelable in the intent. Take note you are passing a copy of the class.

http://developer.android.com/reference/android/os/Parcelable.html

Here I have an onItemClick. I create intent and putExtra an entire class into the intent. The class I'm sending has implemented parcelable. Tip: You only need implement the parseable over what is minimally needed to re-create the class. Ie maybe a filename or something simple like a string something that a constructor can use to create the class. The new activity can later getExtras and it is essentially creating a copy of the class with its constructor method.

Here I launch the kmlreader class of my app when I recieve an onclick in the listview.

Note: below summary is a list of the class that I am passing so get(position) returns the class infact it is the same list that populates the listview

List<KmlSummary> summary = null;
...

public final static String EXTRA_KMLSUMMARY = "com.gosylvester.bestrides.util.KmlSummary";

...

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    lastshownitem = position;
    Intent intent = new Intent(context, KmlReader.class);
    intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
            summary.get(position));
    startActivity(intent);
}

later in the new activity I pull out the parseable class with

kmlSummary = intent.getExtras().getParcelable(
                ImageTextListViewActivity.EXTRA_KMLSUMMARY);

//note:
//KmlSummary implements parcelable.
//there is a constructor method for parcel in
// and a overridden writetoparcel method
// these are really easy to setup.

public KmlSummary(Parcel in) {
    this._id = in.readInt();
    this._description = in.readString();
    this._name = in.readString();
    this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
    in.readDouble());
    this._resrawid = in.readInt();
    this._resdrawableid = in.readInt();
     this._pathstring = in.readString();
    String s = in.readString();
    this.set_isThumbCreated(Boolean.parseBoolean(s));
}

@Override
public void writeToParcel(Parcel arg0, int arg1) {
    arg0.writeInt(this._id);
    arg0.writeString(this._description);
    arg0.writeString(this._name);
    arg0.writeDouble(this.get_bounds().southwest.latitude);
    arg0.writeDouble(this.get_bounds().southwest.longitude);
    arg0.writeDouble(this.get_bounds().northeast.latitude);
    arg0.writeDouble(this.get_bounds().northeast.longitude);
    arg0.writeInt(this._resrawid);
    arg0.writeInt(this._resdrawableid);
    arg0.writeString(this.get_pathstring());
    String s = Boolean.toString(this.isThumbCreated());
    arg0.writeString(s);
}

Good Luck Danny117

Java integer to byte array

byte[] conv = new byte[4];
conv[3] = (byte) input & 0xff;
input >>= 8;
conv[2] = (byte) input & 0xff;
input >>= 8;
conv[1] = (byte) input & 0xff;
input >>= 8;
conv[0] = (byte) input;

How to edit incorrect commit message in Mercurial?

EDIT: As pointed out by users, don't use MQ, use commit --amend. This answer is mostly of historic interest now.

As others have mentioned the MQ extension is much more suited for this task, and you don't run the risk of destroying your work. To do this:

  1. Enable the MQ extension, by adding something like this to your hgrc:

    [extensions]
    mq =
    
  2. Update to the changeset you want to edit, typically tip:

    hg up $rev
    
  3. Import the current changeset into the queue:

    hg qimport -r .
    
  4. Refresh the patch, and edit the commit message:

    hg qrefresh -e
    
  5. Finish all applied patches (one, in this case) and store them as regular changesets:

    hg qfinish -a
    

I'm not familiar with TortoiseHg, but the commands should be similar to those above. I also believe it's worth mentioning that editing history is risky; you should only do it if you're absolutely certain that the changeset hasn't been pushed to or pulled from anywhere else.

How can I get nth element from a list?

Haskell's standard list data type forall t. [t] in implementation closely resembles a canonical C linked list, and shares its essentially properties. Linked lists are very different from arrays. Most notably, access by index is a O(n) linear-, instead of a O(1) constant-time operation.

If you require frequent random access, consider the Data.Array standard.

!! is an unsafe partially defined function, provoking a crash for out-of-range indices. Be aware that the standard library contains some such partial functions (head, last, etc.). For safety, use an option type Maybe, or the Safe module.

Example of a reasonably efficient, robust total (for indices = 0) indexing function:

data Maybe a = Nothing | Just a

lookup :: Int -> [a] -> Maybe a
lookup _ []       = Nothing
lookup 0 (x : _)  = Just x
lookup i (_ : xs) = lookup (i - 1) xs

Working with linked lists, often ordinals are convenient:

nth :: Int -> [a] -> Maybe a
nth _ []       = Nothing
nth 1 (x : _)  = Just x
nth n (_ : xs) = nth (n - 1) xs

Applying an ellipsis to multiline text

_x000D_
_x000D_
p {_x000D_
    width:100%;_x000D_
    overflow: hidden;_x000D_
    display: -webkit-box;_x000D_
    -webkit-line-clamp: 2;_x000D_
    -webkit-box-orient: vertical;_x000D_
    background:#fff;_x000D_
    position:absolute;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>
_x000D_
_x000D_
_x000D_

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

How can I hash a password in Java?

Among all the standard hash schemes, LDAP ssha is the most secure one to use,

http://www.openldap.org/faq/data/cache/347.html

I would just follow the algorithms specified there and use MessageDigest to do the hash.

You need to store the salt in your database as you suggested.

Select columns in PySpark dataframe

First two columns and 5 rows

 df.select(df.columns[:2]).take(5)

Confused about Service vs Factory

Here are some more examples of services vs factories which may be useful in seeing the difference between them. Basically, a service has "new ..." called on it, it is already instantiated. A factory is not instantiated automatically.

Basic Examples

Return a class object which has a single method

Here is a service that has a single method:

angular.service('Hello', function () {
  this.sayHello = function () { /* ... */ };
});

Here is a factory that returns an object with a method:

angular.factory('ClassFactory', function () {
  return {
    sayHello: function () { /* ... */ }
  };
});

Return a value

A factory that returns a list of numbers:

angular.factory('NumberListFactory', function () {
  return [1, 2, 3, 4, 5];
});

console.log(NumberListFactory);

A service that returns a list of numbers:

angular.service('NumberLister', function () {
  this.numbers = [1, 2, 3, 4, 5];
});

console.log(NumberLister.numbers);

The output in both cases is the same, the list of numbers.

Advanced Examples

"Class" variables using factories

In this example we define a CounterFactory, it increments or decrements a counter and you can get the current count or get how many CounterFactory objects have been created:

angular.factory('CounterFactory', function () {
  var number_of_counter_factories = 0; // class variable

  return function () {
    var count = 0; // instance variable
    number_of_counter_factories += 1; // increment the class variable

    // this method accesses the class variable
    this.getNumberOfCounterFactories = function () {
      return number_of_counter_factories;
    };

    this.inc = function () {
      count += 1;
    };
    this.dec = function () {
      count -= 1;
    };
    this.getCount = function () {
      return count;
    };
  }

})

We use the CounterFactory to create multiple counters. We can access the class variable to see how many counters were created:

var people_counter;
var places_counter;

people_counter = new CounterFactory();
console.log('people', people_counter.getCount());
people_counter.inc();
console.log('people', people_counter.getCount());

console.log('counters', people_counter.getNumberOfCounterFactories());

places_counter = new CounterFactory();
console.log('places', places_counter.getCount());

console.log('counters', people_counter.getNumberOfCounterFactories());
console.log('counters', places_counter.getNumberOfCounterFactories());

The output of this code is:

people 0
people 1
counters 1
places 0
counters 2
counters 2

parsing JSONP $http.jsonp() response in angular.js

The MOST IMPORTANT THING I didn't understand for quite awhile is that the request MUST contain "callback=JSON_CALLBACK", because AngularJS modifies the request url, substituting a unique identifier for "JSON_CALLBACK". The server response must use the value of the 'callback' parameter instead of hard coding "JSON_CALLBACK":

JSON_CALLBACK(json_response);  // wrong!

Since I was writing my own PHP server script, I thought I knew what function name it wanted and didn't need to pass "callback=JSON_CALLBACK" in the request. Big mistake!

AngularJS replaces "JSON_CALLBACK" in the request with a unique function name (like "callback=angular.callbacks._0"), and the server response must return that value:

angular.callbacks._0(json_response);

Detect Browser Language in PHP

Try this one:

#########################################################
# Copyright © 2008 Darrin Yeager                        #
# https://www.dyeager.org/                               #
# Licensed under BSD license.                           #
#   https://www.dyeager.org/downloads/license-bsd.txt    #
#########################################################

function getDefaultLanguage() {
   if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"]))
      return parseDefaultLanguage($_SERVER["HTTP_ACCEPT_LANGUAGE"]);
   else
      return parseDefaultLanguage(NULL);
   }

function parseDefaultLanguage($http_accept, $deflang = "en") {
   if(isset($http_accept) && strlen($http_accept) > 1)  {
      # Split possible languages into array
      $x = explode(",",$http_accept);
      foreach ($x as $val) {
         #check for q-value and create associative array. No q-value means 1 by rule
         if(preg_match("/(.*);q=([0-1]{0,1}.\d{0,4})/i",$val,$matches))
            $lang[$matches[1]] = (float)$matches[2];
         else
            $lang[$val] = 1.0;
      }

      #return default language (highest q-value)
      $qval = 0.0;
      foreach ($lang as $key => $value) {
         if ($value > $qval) {
            $qval = (float)$value;
            $deflang = $key;
         }
      }
   }
   return strtolower($deflang);
}

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

How to send an object from one Android Activity to another using Intents?

First implement Parcelable in your class. Then pass object like this.

SendActivity.java

ObjectA obj = new ObjectA();

// Set values etc.

Intent i = new Intent(this, MyActivity.class);
i.putExtra("com.package.ObjectA", obj);

startActivity(i);

ReceiveActivity.java

Bundle b = getIntent().getExtras();
ObjectA obj = b.getParcelable("com.package.ObjectA");

The package string isn't necessary, just the string needs to be the same in both Activities

REFERENCE

Why does IE9 switch to compatibility mode on my website?

The site at http://www.HTML-5.com/index.html does have the X-UA-Compatible meta tag but still goes into Compatibility View as indicated by the "torn page" icon in the address bar. How do you get the menu option to force IE 9 (Final Version 9.0.8112.16421) to render a page in Standards Mode? I tried right clicking that torn page icon as well as the "Alt" key trick to display the additional menu options mentioned by Rene Geuze, but those didn't work.

Calculating the distance between 2 points

measure the square distance from one point to the other:

((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) < d*d

where d is the distance, (x1,y1) are the coordinates of the 'base point' and (x2,y2) the coordinates of the point you want to check.

or if you prefer:

(Math.Pow(x1-x2,2)+Math.Pow(y1-y2,2)) < (d*d);

Noticed that the preferred one does not call Pow at all for speed reasons, and the second one, probably slower, as well does not call Math.Sqrt, always for performance reasons. Maybe such optimization are premature in your case, but they are useful if that code has to be executed a lot of times.

Of course you are talking in meters and I supposed point coordinates are expressed in meters too.

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

How to test Spring Data repositories?

This may come a bit too late, but I have written something for this very purpose. My library will mock out the basic crud repository methods for you as well as interpret most of the functionalities of your query methods. You will have to inject functionalities for your own native queries, but the rest are done for you.

Take a look:

https://github.com/mmnaseri/spring-data-mock

UPDATE

This is now in Maven central and in pretty good shape.

How do I enable Java in Microsoft Edge web browser?

About this, java declares that on Windows 10, Edge browser does not support plugins, so it will NOT run java. (see https://www.java.com/it/download/win10.jsp --> only visible with edge in win10) It also reports a notice: java is not officially supported yet in Windows 10. (see https://www.java.com/it/download/faq/win10_faq.xml)

How to deal with SettingWithCopyWarning in Pandas

Here I answer the question directly. How to deal with it?

Make a .copy(deep=False) after you slice. See pandas.DataFrame.copy.

Wait, doesn't a slice return a copy? After all, this is what the warning message is attempting to say? Read the long answer:

import pandas as pd
df = pd.DataFrame({'x':[1,2,3]})

This gives a warning:

df0 = df[df.x>2]
df0['foo'] = 'bar'

This does not:

df1 = df[df.x>2].copy(deep=False)
df1['foo'] = 'bar'

Both df0 and df1 are DataFrame objects, but something about them is different that enables pandas to print the warning. Let's find out what it is.

import inspect
slice= df[df.x>2]
slice_copy = df[df.x>2].copy(deep=False)
inspect.getmembers(slice)
inspect.getmembers(slice_copy)

Using your diff tool of choice, you will see that beyond a couple of addresses, the only material difference is this:

|          | slice   | slice_copy |
| _is_copy | weakref | None       |

The method that decides whether to warn is DataFrame._check_setitem_copy which checks _is_copy. So here you go. Make a copy so that your DataFrame is not _is_copy.

The warning is suggesting to use .loc, but if you use .loc on a frame that _is_copy, you will still get the same warning. Misleading? Yes. Annoying? You bet. Helpful? Potentially, when chained assignment is used. But it cannot correctly detect chain assignment and prints the warning indiscriminately.

What's the difference between a word and byte?

BYTE

I am trying to answer this question from C++ perspective.

The C++ standard defines ‘byte’ as “Addressable unit of data large enough to hold any member of the basic character set of the execution environment.”

What this means is that the byte consists of at least enough adjacent bits to accommodate the basic character set for the implementation. That is, the number of possible values must equal or exceed the number of distinct characters. In the United States, the basic character sets are usually the ASCII and EBCDIC sets, each of which can be accommodated by 8 bits. Hence it is guaranteed that a byte will have at least 8 bits.

In other words, a byte is the amount of memory required to store a single character.

If you want to verify ‘number of bits’ in your C++ implementation, check the file ‘limits.h’. It should have an entry like below.

#define CHAR_BIT      8         /* number of bits in a char */

WORD

A Word is defined as specific number of bits which can be processed together (i.e. in one attempt) by the machine/system. Alternatively, we can say that Word defines the amount of data that can be transferred between CPU and RAM in a single operation.

The hardware registers in a computer machine are word sized. The Word size also defines the largest possible memory address (each memory address points to a byte sized memory).

Note – In C++ programs, the memory addresses points to a byte of memory and not to a word.

Validation for 10 digit mobile number and focus input field on invalid

for email validation, <input type="email"> is enough..

for mobile no use pattern attribute for input as follows:

<input type="number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" required>

you can check for more patterns on http://html5pattern.com.

for focusing on field, you can use onkeyup() event as:

function check()
{

    var mobile = document.getElementById('mobile');
   
    
    var message = document.getElementById('message');

   var goodColor = "#0C6";
    var badColor = "#FF9B37";
  
    if(mobile.value.length!=10){
       
        mobile.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "required 10 digits, match requested format!"
    }}

and your HTML code should be:

<input name="mobile"  id="mobile" type="number" required onkeyup="check(); return false;" ><span id="message"></span>

Set Background cell color in PHPExcel

  $objPHPExcel->getActiveSheet()->getStyle('B3:B7')->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFF0000');

It's in the documentation, located here: https://github.com/PHPOffice/PHPExcel/wiki/User-Documentation-Overview-and-Quickstart-Guide

How to return a specific status code and no contents from Controller?

this.HttpContext.Response.StatusCode = 418; // I'm a teapot

How to end the request?

Try other solution, just:

return StatusCode(418);


You could use StatusCode(???) to return any HTTP status code.


Also, you can use dedicated results:

Success:

  • return Ok() ? Http status code 200
  • return Created() ? Http status code 201
  • return NoContent(); ? Http status code 204

Client Error:

  • return BadRequest(); ? Http status code 400
  • return Unauthorized(); ? Http status code 401
  • return NotFound(); ? Http status code 404


More details:

Excel function to make SQL-like queries on worksheet data?

One quick way to do this is to create a column with a formula that evaluates to true for the rows you care about and then filter for the value TRUE in that column.

How do I find the parent directory in C#?

I've found variants of System.IO.Path.Combine(myPath, "..") to be the easiest and most reliable. Even more so if what northben says is true, that GetParent requires an extra call if there is a trailing slash. That, to me, is unreliable.

Path.Combine makes sure you never go wrong with slashes.

.. behaves exactly like it does everywhere else in Windows. You can add any number of \.. to a path in cmd or explorer and it will behave exactly as I describe below.

Some basic .. behavior:

  1. If there is a file name, .. will chop that off:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..") => D:\Grandparent\Parent\

  1. If the path is a directory, .. will move up a level:

Path.Combine(@"D:\Grandparent\Parent\", "..") => D:\Grandparent\

  1. ..\.. follows the same rules, twice in a row:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", @"..\..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", @"..\..") => D:\

  1. And this has the exact same effect:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..", "..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", "..", "..") => D:\

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

The live function is registering a click event handler. It'll do so every time you click the object. So if you click it twice, you're assigning two click handlers to the object. You're also assigning a click handler here:

onclick="feedback('the message html')";

And then that click handler is assigning another click handler via live().

Really what I think you want to do is this:

function feedback(message)
{
    $('#feedback').remove();

    $('.answers').append('<div id="feedback">'+message+'</div>');
}

Ok, per your comment, try taking out the onclick part of the <a> element and instead, putting this in a document.ready() handler.

$('#answer').live('click',function(){
                     $('#feedback').remove();
                     $('.answers').append('<div id="feedback">'+message+'</div>');
                 });

Java Pass Method as Parameter

Java do have a mechanism to pass name and call it. It is part of the reflection mechanism. Your function should take additional parameter of class Method.

public void YouMethod(..... Method methodToCall, Object objWithAllMethodsToBeCalled)
{
...
Object retobj = methodToCall.invoke(objWithAllMethodsToBeCalled, arglist);
...
}

Set selected item of spinner programmatically

This worked for me:

@Override
protected void onStart() {
    super.onStart();
    mySpinner.setSelection(position);
}

It's similar to @sberezin's solution but calling setSelection() in onStart().

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

You should install node.js with nvm, because that way you do not have to provide superuser privileges when installing global packages (you can simply execute "npm install -g packagename" without prepending 'sudo').

Brew is fantastic for other things, however. I tend to be biased towards Bower whenever I have the option to install something with Bower.

What's HTML character code 8203?

The ZERO WIDTH SPACE character is inserted when you use jQuery to add elements using DOM manipulation functions like .before() and .after()

I've run into this when adding hidden modal dialog frames at the end of my document and then finding that the ZERO WIDTH SPACE screws up the layout down there, adding unwanted space.

The quick fix was to insert it before the footer, not after it. Its hidden anyway.

I can't find anything in jQuery that does this:

https://github.com/jquery/jquery/blob/master/src/manipulation.js

So it might be the browser that adds it.

How to enable file upload on React's Material UI simple input?

Here an example:

return (
    <Box alignItems='center' display='flex' justifyContent='center' flexDirection='column'>
      <Box>
        <input accept="image/*" id="upload-company-logo" type='file' hidden />
        <label htmlFor="upload-company-logo">
          <Button component="span" >
            <Paper elevation={5}>
              <Avatar src={formik.values.logo} className={classes.avatar} variant='rounded' />
            </Paper>
          </Button>
        </label>
      </Box>
    </Box>
  )

Oracle SQL query for Date format

to_date() returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:

select * 
from table
where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')

You probably want to create an index on trunc(es_date) if that is something you are doing on a regular basis.

The literal '27-APR-12' can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date() with a proper format mask (or an ANSI literal: date '2012-04-27')

Although you did right in using to_date() and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'.

With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy') when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy' or 'yyyy-mm-dd'

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

The above one with JQuery is the easiest and mostly used way. However you can use pure javascript but try to define this script in the head so that it is read at the beginning. What you are looking for is window.onload event.

Below is a simple script that I created to run a counter. The counter then stops after 10 iterations

window.onload=function()
{
    var counter = 0;
    var interval1 = setInterval(function()
    { 
        document.getElementById("div1").textContent=counter;
        counter++; 
        if(counter==10)
        {
            clearInterval(interval1);
        }
    },1000);

}

Auto line-wrapping in SVG text

Text wrapping is not part of SVG1.1, the currently implemented spec. You should rather use HTML via the <foreignObject/> element.

<svg ...>

<switch>
<foreignObject x="20" y="90" width="150" height="200">
<p xmlns="http://www.w3.org/1999/xhtml">Text goes here</p>
</foreignObject>

<text x="20" y="20">Your SVG viewer cannot display html.</text>
</switch>

</svg>

How to run eclipse in clean mode? what happens if we do so?

This will clean the caches used to store bundle dependency resolution and eclipse extension registry data. Using this option will force eclipse to reinitialize these caches.

  1. Open command prompt (cmd)
  2. Go to eclipse application location (D:\eclipse)
  3. Run command eclipse -clean

Why is Dictionary preferred over Hashtable in C#?

According to what I see by using .NET Reflector:

[Serializable, ComVisible(true)]
public abstract class DictionaryBase : IDictionary, ICollection, IEnumerable
{
    // Fields
    private Hashtable hashtable;

    // Methods
    protected DictionaryBase();
    public void Clear();
.
.
.
}
Take note of these lines
// Fields
private Hashtable hashtable;

So we can be sure that DictionaryBase uses a HashTable internally.

C# binary literals

Basically, I think the answer is NO, there is no easy way. Use decimal or hexadecimal constants - they are simple and clear. @RoyTinkers answer is also good - use a comment.

int someHexFlag = 0x010; // 000000010000
int someDecFlag = 8;     // 000000001000

The others answers here present several useful work-a rounds, but I think they aren't better then the simple answer. C# language designers probably considered a '0b' prefix unnecessary. HEX is easy to convert to binary, and most programmers are going to have to know the DEC equivalents of 0-8 anyways.

Also, when examining values in the debugger, they will be displayed has HEX or DEC.

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

Select ID, IsNull(Cast(ParentID as varchar(max)),'') from Patients

This is needed because field ParentID is not varchar/nvarchar type. This will do the trick:

Select ID, IsNull(ParentID,'') from Patients

UTF-8 encoding in JSP page

The default JSP file encoding is specified by JSR315 as ISO-8859-1. This is the encoding that the JSP engine uses to read the JSP file and it is unrelated to the servlet request or response encoding.

If you have non-latin characters in your JSP files, save the JSP file as UTF-8 with BOM or set pageEncoding in the beginning of the JSP page:

<%@page pageEncoding="UTF-8" %>

However, you might want to change the default to UTF-8 globally for all JSP pages. That can be done via web.xml:

<jsp-config>
    <jsp-property-group>
        <url-pattern>/*</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
</jsp-config>

Or, when using Spring Boot with an (embedded) Tomcat, via a TomcatContextCustomizer:

@Component
public class JspConfig implements TomcatContextCustomizer {
    @Override
    public void customize(Context context) {
        JspPropertyGroup pg = new JspPropertyGroup();
        pg.addUrlPattern("/*");
        pg.setPageEncoding("UTF-8");
        pg.setTrimWhitespace("true"); // optional, but nice to have
        ArrayList<JspPropertyGroupDescriptor> pgs = new ArrayList<>();
        pgs.add(new JspPropertyGroupDescriptorImpl(pg));
        context.setJspConfigDescriptor(new JspConfigDescriptorImpl(pgs, new ArrayList<TaglibDescriptor>()));
    }
}

For JSP to work with Spring Boot, don't forget to include these dependencies:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

And to make a "runnable" .war file, repackage it:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
   . . .

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Paste this code to your pom.xml file. It works for me.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
    <scope>test</scope>
</dependency>

Select rows where column is null

You want to know if the column is null

select * from foo where bar is null

If you want to check for some value not equal to something and the column also contains null values you will not get the columns with null in it

does not work:

select * from foo where bar <> 'value'

does work:

select * from foo where bar <> 'value' or bar is null

in Oracle (don't know on other DBMS) some people use this

select * from foo where NVL(bar,'n/a') <> 'value'

if I read the answer from tdammers correctly then in MS SQL Server this is like that

select * from foo where ISNULL(bar,'n/a') <> 'value'

in my opinion it is a bit of a hack and the moment 'value' becomes a variable the statement tends to become buggy if the variable contains 'n/a'.

How do I pass a URL with multiple parameters into a URL?

You have to escape the & character. Turn your

&

into

&amp;

and you should be good.

How to autoplay HTML5 mp4 video on Android?

Chrome has disabled it. https://bugs.chromium.org/p/chromium/issues/detail?id=159336 Even the jQuery play() is blocked. They want user to initiate it so bandwidth can be saved.

Using jQuery to center a DIV on the screen

CSS solution In two lines only

It centralize your inner div horizontally and vertically.

#outer{
  display: flex;
}
#inner{
  margin: auto;
}

for only horizontal align, change

margin: 0 auto;

and for vertical, change

margin: auto 0;

How to encode URL parameters?

With urlsearchparams:

const params = new URLSearchParams()
params.append('imageurl', http://www.image.com/?username=unknown&password=unknown)
return `http://www.foobar.com/foo?${params.toString()}`

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

Try this

Check this How do i get the gmt time in php

date_default_timezone_set("UTC");
echo date("Y-m-d H:i:s", time()); 

jQuery to serialize only elements within a div

No problem. Just use the following. This will behave exactly like serializing a form but using a div's content instead.

$('#divId :input').serialize();

Check https://jsbin.com/xabureladi/1 for a demonstration (https://jsbin.com/xabureladi/1/edit for the code)

nginx error "conflicting server name" ignored

I assume that you're running a Linux, and you're using gEdit to edit your files. In the /etc/nginx/sites-enabled, it may have left a temp file e.g. default~ (watch the ~).

Depending on your editor, the file could be named .save or something like it. Just run $ ls -lah to see which files are unintended to be there and remove them (Thanks @Tisch for this).

Delete this file, and it will solve your problem.

How to put a Scanner input into an array... for example a couple of numbers

public static void main (String[] args)
{
    Scanner s = new Scanner(System.in);
    System.out.println("Please enter size of an array");
    int n=s.nextInt();
    double arr[] = new double[n];
    System.out.println("Please enter elements of array:");
    for (int i=0; i<n; i++)
    {
        arr[i] = s.nextDouble();
    }
}

Go To Definition: "Cannot navigate to the symbol under the caret."

Ran into this problem when using F12 to try and go to a method definition.

All of the mentioned items (except the /resetuserdata - which I didn't try because it would be a pain to recover from) didn't work.

What did work for me:

  • Exit Visual Studio
  • From a Command Prompt, go to the folder for your solution and run the following code (this deletes ALL bin and obj folders in your solution):

    FOR /F "tokens=*" %%G IN ('DIR /B /AD /S bin') DO RMDIR /S /Q "%%G"
    FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G"
    
  • Restart Visual Studio. Opening the solution should take a bit longer as it now rebuilds the obj folders.

After doing this F12 worked!

As a side note, I normally place this in a batch file in my solution's folder, along side the .sln file. This makes it easy to run later!

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.

For that we have provide one setter method for myobj and set the myobj value with mocked object.

class MyClass {
    MyInterface myObj;

    public void abc() {
        myObj.myMethodToBeVerified (new String("a"), new String("b"));
    }

    public void setMyObj(MyInterface obj)
    {
        this.myObj=obj;
    }
}

In our Test class, we have to write below code

class MyClassTest {

MyClass myClass = new MyClass();

    @Mock
    MyInterface myInterface;

    @test
    testAbc() {
        myclass.setMyObj(myInterface); //it is good to have in @before method
        myClass.abc();
        verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
     }
}

How to check if a directory containing a file exist?

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");
f.mkdirs();

How to create a DB link between two oracle instances

as a simple example:

CREATE DATABASE LINK _dblink_name_
  CONNECT TO _username_
    IDENTIFIED BY _passwd_
      USING '$_ORACLE_SID_'

for more info: http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_5005.htm

How to make a GridLayout fit screen size

Do you know View.getViewTreeObserver().addOnGlobalLayoutListener()

By this you can calculate the sizes.

I achieve your UI effect by GridView:

GridView g;
g.setNumColumns(2);
g.setStretchMode(GridView.STRETCH_SPACING_UNIFORM);

How to get your Netbeans project into Eclipse

You should be using Maven, as the structure is standardized. To do that (Once you have created your Maven project in Netbeans, just

  1. Go to File -> Import
  2. Open Maven tree node
  3. Select Existing Maven Project
  4. Browse to find your project from NetBeans
  5. Check Add project to Working Set
  6. Click finish.

As long as the project has no errors, I usually get none transferring to eclipse. This works for Maven web projects and regular projects.

How do I find the last column with data?

Lots of ways to do this. The most reliable is find.

Dim rLastCell As Range

Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)

MsgBox ("The last used column is: " & rLastCell.Column)

If you want to find the last column used in a particular row you can use:

Dim lColumn As Long

lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column

Using used range (less reliable):

Dim lColumn As Long

lColumn = ws.UsedRange.Columns.Count

Using used range wont work if you have no data in column A. See here for another issue with used range:

See Here regarding resetting used range.

slf4j: how to log formatted message, object array, exception

In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using

<encoder>
    <pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern> 
</encoder>

the %ex in pattern is what makes the difference

How to set the component size with GridLayout? Is there a better way?

An alternative to other layouts, might be to put your panel with the GridLayout, inside another panel that is a FlowLayout. That way your spacing will be intact but will not expand across the entire available space.

"Unable to find remote helper for 'https'" during git clone

I had to add a couple of extra installs running CentOS release 5.10 (Final):

yum install openssl097a.x86_64 
yum install openssl-perl.x86_64 

Using git-1.8.5: ./configure make clean make make install

git clone https://github.com/michaelficarra/CoffeeScriptRedux.git
Cloning into 'CoffeeScriptRedux'...
remote: Reusing existing pack: 4577, done.
remote: Counting objects: 24, done.
remote: Compressing objects: 100% (23/23), done.
remote: Total 4601 (delta 13), reused 11 (delta 1)
Receiving objects: 100% (4601/4601), 2.60 MiB | 126.00 KiB/s, done.
Resolving deltas: 100% (2654/2654), done.
Checking connectivity... done.

Uploading Images to Server android

Main activity class to take pick and upload

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;


public class MainActivity extends Activity {

    Button btpic, btnup;
    private Uri fileUri;
    String picturePath;
    Uri selectedImage;
    Bitmap photo;
    String ba1;
    public static String URL = "Paste your URL here";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btpic = (Button) findViewById(R.id.cpic);
        btpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickpic();
            }
        });

        btnup = (Button) findViewById(R.id.up);
        btnup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upload();
            }
        });
    }

    private void upload() {
        // Image location URL
        Log.e("path", "----------------" + picturePath);

        // Image
        Bitmap bm = BitmapFactory.decodeFile(picturePath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
       //ba1 = Base64.encodeBytes(ba);

        Log.e("base64", "-----" + ba1);

        // Upload image to server
        new uploadToServer().execute();

    }

    private void clickpic() {
        // Check Camera
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // Open default camera
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            // start the image capture Intent
            startActivityForResult(intent, 100);

        } else {
            Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {

            selectedImage = data.getData();
            photo = (Bitmap) data.getExtras().get("data");

            // Cursor to get image uri to display

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            Bitmap photo = (Bitmap) data.getExtras().get("data");
            ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
            imageView.setImageBitmap(photo);
        }
    }

    public class uploadToServer extends AsyncTask<Void, Void, String> {

        private ProgressDialog pd = new ProgressDialog(MainActivity.this);
        protected void onPreExecute() {
            super.onPreExecute();
            pd.setMessage("Wait image uploading!");
            pd.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("base64", ba1));
            nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(URL);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                String st = EntityUtils.toString(response.getEntity());
                Log.v("log_tag", "In the try Loop" + st);

            } catch (Exception e) {
                Log.v("log_tag", "Error in http connection " + e.toString());
            }
            return "Success";

        }

        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pd.hide();
            pd.dismiss();
        }
    }
}

php code to handle upload image and also create image from base64 encoded data

<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
 echo "Image uploaded";
}else{
 echo "Error uploading image";
}
}
?>

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

Add a duration to a moment (moment.js)

I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.

So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:

var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format

var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes 

var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format

It fulfills my requirement. May be it can help you.

Jquery click event not working after append method

** Problem Solved ** enter image description here // Changed to delegate() method to use delegation from the body

$("body").delegate("#boundOnPageLoaded", "click", function(){
   alert("Delegated Button Clicked")
});

How to convert string to datetime format in pandas python?

Approach: 1

Given original string format: 2019/03/04 00:08:48

you can use

updated_df = df['timestamp'].astype('datetime64[ns]')

The result will be in this datetime format: 2019-03-04 00:08:48

Approach: 2

updated_df = df.astype({'timestamp':'datetime64[ns]'})

PHP: Limit foreach() statement?

In PHP 5.5+, you can do

function limit($iterable, $limit) {
    foreach ($iterable as $key => $value) {
        if (!$limit--) break;
        yield $key => $value;
    }
}

foreach (limit($arr, 10) as $key => $value) {
    // do stuff
}

Generators rock.

Difference between checkout and export in SVN

svn export simply extracts all the files from a revision and does not allow revision control on it. It also does not litter each directory with .svn directories.

svn checkout allows you to use version control in the directory made, e.g. your standard commands such as svn update and svn commit.

Initialize a string in C to empty string

It's a bit late but I think your issue may be that you've created a zero-length array, rather than an array of length 1.

A string is a series of characters followed by a string terminator ('\0'). An empty string ("") consists of no characters followed by a single string terminator character - i.e. one character in total.

So I would try the following:

string[1] = ""

Note that this behaviour is not the emulated by strlen, which does not count the terminator as part of the string length.

How to Reload ReCaptcha using JavaScript?

For reCaptcha v2, use:

grecaptcha.reset();

If you're using reCaptcha v1 (probably not):

Recaptcha.reload();

This will do if there is an already loaded Recaptcha on the window.

(Updated based on @SebiH's comment below.)

.mp4 file not playing in chrome

Encountering the same problem, I solved this by reconverting the file with default mp4 settings in iMovie.

Getting error "The package appears to be corrupt" while installing apk file

This is weird. I don't know why this was happening with me while generating signed apk but below steps worked for me.

  1. Go to file and select invalidate caches/restarts
  2. After that go to build select clean project
  3. And then select Rebuild project

That's it.

Replacing Numpy elements if condition is met

>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[0, 3, 3, 2],
       [4, 1, 1, 2],
       [3, 4, 2, 4],
       [2, 4, 3, 0],
       [1, 2, 3, 4]])
>>> 
>>> a[a > 3] = -101
>>> a
array([[   0,    3,    3,    2],
       [-101,    1,    1,    2],
       [   3, -101,    2, -101],
       [   2, -101,    3,    0],
       [   1,    2,    3, -101]])
>>>

See, eg, Indexing with boolean arrays.

How to add a downloaded .box file to Vagrant?

Alternatively to add downloaded box, a json file with metadata can be created. This way some additional details can be applied. For example to import box and specifying its version create file:

{
  "name": "laravel/homestead",
  "versions": [
    {
      "version": "7.0.0",
      "providers": [
        {
          "name": "virtualbox",
          "url": "file:///path/to/box/virtualbox.box"
        }
      ]
    }
  ]
}

Then run vagrant box add command with parameter:

vagrant box add laravel/homestead /path/to/metadata.json

CreateProcess error=206, The filename or extension is too long when running main() method

Try updating your Eclipse version, the issue was closed recently (2013-03-12). Check the bug report https://bugs.eclipse.org/bugs/show_bug.cgi?id=327193

How to match "anything up until this sequence of characters" in a regular expression?

The $ marks the end of a string, so something like this should work: [[^abc]*]$ where you're looking for anything NOT ENDING in any iteration of abc, but it would have to be at the end

Also if you're using a scripting language with regex (like php or js), they have a search function that stops when it first encounters a pattern (and you can specify start from the left or start from the right, or with php, you can do an implode to mirror the string).

Storing query results into a variable and modifying it inside a Stored Procedure

Or you can use one SQL-command instead of create and call stored procedure

INSERT INTO [order_cart](orId,caId)
OUTPUT inserted.*
SELECT
   (SELECT MAX(orId) FROM [order]) as orId,
   (SELECT MAX(caId) FROM [cart]) as caId;

subsetting a Python DataFrame

I'll assume that Time and Product are columns in a DataFrame, df is an instance of DataFrame, and that other variables are scalar values:

For now, you'll have to reference the DataFrame instance:

k1 = df.loc[(df.Product == p_id) & (df.Time >= start_time) & (df.Time < end_time), ['Time', 'Product']]

The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators. The & operator is actually an overloaded bitwise operator which has the same precedence as arithmetic operators which in turn have a higher precedence than comparison operators.

In pandas 0.13 a new experimental DataFrame.query() method will be available. It's extremely similar to subset modulo the select argument:

With query() you'd do it like this:

df[['Time', 'Product']].query('Product == p_id and Month < mn and Year == yr')

Here's a simple example:

In [9]: df = DataFrame({'gender': np.random.choice(['m', 'f'], size=10), 'price': poisson(100, size=10)})

In [10]: df
Out[10]:
  gender  price
0      m     89
1      f    123
2      f    100
3      m    104
4      m     98
5      m    103
6      f    100
7      f    109
8      f     95
9      m     87

In [11]: df.query('gender == "m" and price < 100')
Out[11]:
  gender  price
0      m     89
4      m     98
9      m     87

The final query that you're interested will even be able to take advantage of chained comparisons, like this:

k1 = df[['Time', 'Product']].query('Product == p_id and start_time <= Time < end_time')

What's a standard way to do a no-op in python?

If you need a function that behaves as a nop, try

nop = lambda *a, **k: None
nop()

Sometimes I do stuff like this when I'm making dependencies optional:

try:
    import foo
    bar=foo.bar
    baz=foo.baz
except:
    bar=nop
    baz=nop

# Doesn't break when foo is missing:
bar()
baz()

Select multiple columns from a table, but group by one

==EDIT==

I checked your question again and have concluded this can't be done.

ProductName is not unique, It must either be part of the Group By or excluded from your results.

For example how would SQL present these results to you if you Group By only ProductID?

ProductID | ProductName | OrderQuantity 
---------------------------------------
1234      | abc         | 1
1234      | def         | 1
1234      | ghi         | 1
1234      | jkl         | 1

How to set a session variable when clicking a <a> link

Is your link to another web page? If so, perhaps you could put the variable in the query string and set the session variable when the page being linked to is loaded.

So the link looks like this:

<a href="home.php?variable=value" name="home">home</a>

And the homge page would parse the query string and set the session variable.

How to move all files including hidden files into parent directory via *

This will move all files to parent directory like expected but will not move hidden files. How to do that?

You could turn on dotglob:

shopt -s dotglob               # This would cause mv below to match hidden files
mv /path/subfolder/* /path/

In order to turn off dotglob, you'd need to say:

shopt -u dotglob

How to check list A contains any value from list B?

If you didn't care about performance, you could try:

a.Any(item => b.Contains(item))
// or, as in the column using a method group
a.Any(b.Contains)

But I would try this first:

a.Intersect(b).Any()

percentage of two int?

Well to make the decimal into a percent you can do this,

float percentage = (correct * 100.0f) / questionNum;

What __init__ and self do in Python?

Here, the guy has written pretty well and simple: https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/

Read above link as a reference to this:

self? So what's with that self parameter to all of the Customer methods? What is it? Why, it's the instance, of course! Put another way, a method like withdraw defines the instructions for withdrawing money from some abstract customer's account. Calling jeff.withdraw(100.0) puts those instructions to use on the jeff instance.

So when we say def withdraw(self, amount):, we're saying, "here's how you withdraw money from a Customer object (which we'll call self) and a dollar figure (which we'll call amount). self is the instance of the Customer that withdraw is being called on. That's not me making analogies, either. jeff.withdraw(100.0) is just shorthand for Customer.withdraw(jeff, 100.0), which is perfectly valid (if not often seen) code.

init self may make sense for other methods, but what about init? When we call init, we're in the process of creating an object, so how can there already be a self? Python allows us to extend the self pattern to when objects are constructed as well, even though it doesn't exactly fit. Just imagine that jeff = Customer('Jeff Knupp', 1000.0) is the same as calling jeff = Customer(jeff, 'Jeff Knupp', 1000.0); the jeff that's passed in is also made the result.

This is why when we call init, we initialize objects by saying things like self.name = name. Remember, since self is the instance, this is equivalent to saying jeff.name = name, which is the same as jeff.name = 'Jeff Knupp. Similarly, self.balance = balance is the same as jeff.balance = 1000.0. After these two lines, we consider the Customer object "initialized" and ready for use.

Be careful what you __init__

After init has finished, the caller can rightly assume that the object is ready to use. That is, after jeff = Customer('Jeff Knupp', 1000.0), we can start making deposit and withdraw calls on jeff; jeff is a fully-initialized object.

MySQL: How to allow remote connection to mysql

And for OS X people out there be aware that the bind-address parameter is typically set in the launchd plist and not in the my.ini file. So in my case, I removed <string>--bind-address=127.0.0.1</string> from /Library/LaunchDaemons/homebrew.mxcl.mariadb.plist.

How can I add a box-shadow on one side of an element?

Yes, you can use the shadow spread property of the box-shadow rule:

_x000D_
_x000D_
.myDiv_x000D_
{_x000D_
  border: 1px solid #333;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  box-shadow: 10px 0 5px -2px #888;_x000D_
}
_x000D_
<div class="myDiv"></div>
_x000D_
_x000D_
_x000D_

The fourth property there -2px is the shadow spread, you can use it to change the spread of the shadow, making it appear that the shadow is on one side only.

This also uses the shadow positioning rules 10px sends it to the right (horizontal offset) and 0px keeps it under the element (vertical offset.)

5px is the blur radius :)

Example for you here.

How to set env variable in Jupyter notebook

You can setup environment variables in your code as follows:

import sys,os,os.path
sys.path.append(os.path.expanduser('~/code/eol_hsrl_python'))
os.environ['HSRL_INSTRUMENT']='gvhsrl'
os.environ['HSRL_CONFIG']=os.path.expanduser('~/hsrl_config')

This if of course a temporary fix, to get a permanent one, you probably need to export the variables into your ~.profile, more information can be found here

Two Divs on the same row and center align both of them

I would vote against display: inline-block since its not supported across browsers, IE < 8 specifically.

.wrapper {
    width:500px; /* Adjust to a total width of both .left and .right */
    margin: 0 auto;
}
.left {
    float: left;
    width: 49%; /* Not 50% because of 1px border. */
    border: 1px solid #000;
}
.right {
    float: right;
    width: 49%; /* Not 50% because of 1px border. */
    border: 1px solid #F00;
}

<div class="wrapper">
    <div class="left">Div 1</div>
    <div class="right">Div 2</div>
</div>

EDIT: If no spacing between the cells is desired just change both .left and .right to use float: left;

Why does instanceof return false for some literals?

In JavaScript everything is an object (or may at least be treated as an object), except primitives (booleans, null, numbers, strings and the value undefined (and symbol in ES6)):

console.log(typeof true);           // boolean
console.log(typeof 0);              // number
console.log(typeof "");             // string
console.log(typeof undefined);      // undefined
console.log(typeof null);           // object
console.log(typeof []);             // object
console.log(typeof {});             // object
console.log(typeof function () {}); // function

As you can see objects, arrays and the value null are all considered objects (null is a reference to an object which doesn't exist). Functions are distinguished because they are a special type of callable objects. However they are still objects.

On the other hand the literals true, 0, "" and undefined are not objects. They are primitive values in JavaScript. However booleans, numbers and strings also have constructors Boolean, Number and String respectively which wrap their respective primitives to provide added functionality:

console.log(typeof new Boolean(true)); // object
console.log(typeof new Number(0));     // object
console.log(typeof new String(""));    // object

As you can see when primitive values are wrapped within the Boolean, Number and String constructors respectively they become objects. The instanceof operator only works for objects (which is why it returns false for primitive values):

console.log(true instanceof Boolean);              // false
console.log(0 instanceof Number);                  // false
console.log("" instanceof String);                 // false
console.log(new Boolean(true) instanceof Boolean); // true
console.log(new Number(0) instanceof Number);      // true
console.log(new String("") instanceof String);     // true

As you can see both typeof and instanceof are insufficient to test whether a value is a boolean, a number or a string - typeof only works for primitive booleans, numbers and strings; and instanceof doesn't work for primitive booleans, numbers and strings.

Fortunately there's a simple solution to this problem. The default implementation of toString (i.e. as it's natively defined on Object.prototype.toString) returns the internal [[Class]] property of both primitive values and objects:

function classOf(value) {
    return Object.prototype.toString.call(value);
}

console.log(classOf(true));              // [object Boolean]
console.log(classOf(0));                 // [object Number]
console.log(classOf(""));                // [object String]
console.log(classOf(new Boolean(true))); // [object Boolean]
console.log(classOf(new Number(0)));     // [object Number]
console.log(classOf(new String("")));    // [object String]

The internal [[Class]] property of a value is much more useful than the typeof the value. We can use Object.prototype.toString to create our own (more useful) version of the typeof operator as follows:

function typeOf(value) {
    return Object.prototype.toString.call(value).slice(8, -1);
}

console.log(typeOf(true));              // Boolean
console.log(typeOf(0));                 // Number
console.log(typeOf(""));                // String
console.log(typeOf(new Boolean(true))); // Boolean
console.log(typeOf(new Number(0)));     // Number
console.log(typeOf(new String("")));    // String

Hope this article helped. To know more about the differences between primitives and wrapped objects read the following blog post: The Secret Life of JavaScript Primitives

Check box size change with CSS

Try this

<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */

VBA Macro to compare all cells of two Excel files

A very simple check you can do with Cell formulas:

Sheet 1 (new - old)

=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")

Sheet 2 (old - new)

=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")

This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)

You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".

Doe the same for Sheet two.

Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.

But two cases are not covered here:

  1. In the compared cell of New and Old is the same data (Resulting Cell will be empty)
  2. In the compared cell of New and Old is diffe data (Resulting Cell will be empty)

To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com

Hosting a Maven repository on github

As an alternative, Bintray provides free hosting of maven repositories. That's probably a good alternative to Sonatype OSS and Maven Central if you absolutely don't want to rename the groupId. But please, at least make an effort to get your changes integrated upstream or rename and publish to Central. It makes it much easier for others to use your fork.

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

you have to add fulltext index on specific fields you want to search.

ALTER TABLE news ADD FULLTEXT(headline, story);

where "news" is your table and "headline, story" fields you wont to enable for fulltext search

Create a date from day month and year with T-SQL

You can also use

select DATEFROMPARTS(year, month, day) as ColDate, Col2, Col3 
From MyTable Where DATEFROMPARTS(year, month, day) Between @DateIni and @DateEnd

Works in SQL since ver.2012 and AzureSQL

How to call a method function from another class?

In class WeatherRecord:

First import the class if they are in different package else this statement is not requires

Import <path>.ClassName



Then, just referene or call your object like:

Date d;
TempratureRange tr;
d = new Date();
tr = new TempratureRange;
//this can be done in Single Line also like :
// Date d = new Date();



But in your code you are not required to create an object to call function of Date and TempratureRange. As both of the Classes contain Static Function , you cannot call the thoes function by creating object.

Date.date(date,month,year);   // this is enough to call those static function 


Have clear concept on Object and Static functions. Click me

How to make an AlertDialog in Flutter?

One Button

showAlertDialog(BuildContext context) {

  // set up the button
  Widget okButton = FlatButton(
    child: Text("OK"),
    onPressed: () { },
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("My title"),
    content: Text("This is my message."),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

Two Buttons

showAlertDialog(BuildContext context) {

  // set up the buttons
  Widget cancelButton = FlatButton(
    child: Text("Cancel"),
    onPressed:  () {},
  );
  Widget continueButton = FlatButton(
    child: Text("Continue"),
    onPressed:  () {},
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("AlertDialog"),
    content: Text("Would you like to continue learning how to use Flutter alerts?"),
    actions: [
      cancelButton,
      continueButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

Three Buttons

showAlertDialog(BuildContext context) {

  // set up the buttons
  Widget remindButton = FlatButton(
    child: Text("Remind me later"),
    onPressed:  () {},
  );
  Widget cancelButton = FlatButton(
    child: Text("Cancel"),
    onPressed:  () {},
  );
  Widget launchButton = FlatButton(
    child: Text("Launch missile"),
    onPressed:  () {},
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("Notice"),
    content: Text("Launching this missile will destroy the entire universe. Is this what you intended to do?"),
    actions: [
      remindButton,
      cancelButton,
      launchButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

Handling button presses

The onPressed callback for the buttons in the examples above were empty, but you could add something like this:

Widget launchButton = FlatButton(
  child: Text("Launch missile"),
  onPressed:  () {
    Navigator.of(context).pop(); // dismiss dialog
    launchMissile();
  },
);

If you make the callback null, then the button will be disabled.

onPressed: null,

enter image description here

Supplemental code

Here is the code for main.dart in case you weren't getting the functions above to run.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter'),
        ),
        body: MyLayout()),
    );
  }
}

class MyLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: RaisedButton(
        child: Text('Show alert'),
        onPressed: () {
          showAlertDialog(context);
        },
      ),
    );
  }
}

// replace this function with the examples above
showAlertDialog(BuildContext context) { ... }

Batch files: How to read a file?

One very easy way to do it is use the following command:

set /p mytextfile=< %pathtotextfile%\textfile.txt
echo %mytextfile%

This will only display the first line of text in a text file. The other way you can do it is use the following command:

type %pathtotextfile%\textfile.txt

This will put all the data in the text file on the screen. Hope this helps!

Make a link open a new window (not tab)

I know that its bit old Q but if u get here by searching a solution so i got a nice one via jquery

  jQuery('a[target^="_new"]').click(function() {
    var width = window.innerWidth * 0.66 ;
    // define the height in
    var height = width * window.innerHeight / window.innerWidth ;
    // Ratio the hight to the width as the user screen ratio
    window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));

});

it will open all the <a target="_new"> in a new window

EDIT:

1st, I did some little changes in the original code now it open the new window perfectly followed the user screen ratio (for landscape desktops)

but, I would like to recommend you to use the following code that open the link in new tab if you in mobile (thanks to zvona answer in other question):

jQuery('a[target^="_new"]').click(function() {
    return openWindow(this.href);
}


function openWindow(url) {

    if (window.innerWidth <= 640) {
        // if width is smaller then 640px, create a temporary a elm that will open the link in new tab
        var a = document.createElement('a');
        a.setAttribute("href", url);
        a.setAttribute("target", "_blank");

        var dispatch = document.createEvent("HTMLEvents");
        dispatch.initEvent("click", true, true);

        a.dispatchEvent(dispatch);
    }
    else {
        var width = window.innerWidth * 0.66 ;
        // define the height in
        var height = width * window.innerHeight / window.innerWidth ;
        // Ratio the hight to the width as the user screen ratio
        window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
    }
    return false;
}

Android: failed to convert @drawable/picture into a drawable

It can be even more trivial than what the other posters suggested: if you have multiple projects make sure you did not create the xml layout file in the wrong project.

After creation, the file will open automatically so this might go unnoticed and you assume it is in the correct project. Obviously any references to drawables or other resources will be invalid.

And yes, I am that stupid. I'll close any unused projects from now on :)

Change Image of ImageView programmatically in Android

In your XML for the image view, where you have android:background="@drawable/thumbs_down change this to android:src="@drawable/thumbs_down"

Currently it is placing that image as the background to the view and not the actual image in it.

ORA-00060: deadlock detected while waiting for resource

I ran into this issue as well. I don't know the technical details of what was actually happening. However, in my situation, the root cause was that there was cascading deletes setup in the Oracle database and my JPA/Hibernate code was also trying to do the cascading delete calls. So my advice is to make sure that you know exactly what is happening.

Scale an equation to fit exact page width

I just had the situation that I wanted this only for lines exceeding \linewidth, that is: Squeezing long lines slightly. Since it took me hours to figure this out, I would like to add it here.

I want to emphasize that scaling fonts in LaTeX is a deadly sin! In nearly every situation, there is a better way (e.g. multline of the mathtools package). So use it conscious.

In this particular case, I had no influence on the code base apart the preamble and some lines slightly overshooting the page border when I compiled it as an eBook-scaled pdf.

\usepackage{environ}         % provides \BODY
\usepackage{etoolbox}        % provides \ifdimcomp
\usepackage{graphicx}        % provides \resizebox

\newlength{\myl}
\let\origequation=\equation
\let\origendequation=\endequation

\RenewEnviron{equation}{
  \settowidth{\myl}{$\BODY$}                       % calculate width and save as \myl
  \origequation
  \ifdimcomp{\the\linewidth}{>}{\the\myl}
  {\ensuremath{\BODY}}                             % True
  {\resizebox{\linewidth}{!}{\ensuremath{\BODY}}}  % False
  \origendequation
}

Before before After after

Where do I find the current C or C++ standard documents?

The ISO C and C++ standards are bloody expensive. On the other hand, the INCITS republishes them for a lot less. http://www.techstreet.com/ seems to have the PDF for $30 (search for INCITS/ISO/IEC 14882:2003).

Hardcopy versions are available, too. Look for the British Standards Institute versions, published by Wiley.

How can I determine the direction of a jQuery scroll event?

You can use this as well

_x000D_
_x000D_
$(document).ready(function(){_x000D_
_x000D_
  var currentscroll_position = $(window).scrollTop();_x000D_
$(window).on('scroll', function(){_x000D_
Get_page_scroll_direction();_x000D_
});_x000D_
_x000D_
function Get_page_scroll_direction(){_x000D_
  var running_scroll_position = $(window).scrollTop();_x000D_
  if(running_scroll_position > currentscroll_position) {_x000D_
      _x000D_
      $('.direction_value').text('Scrolling Down Scripts');_x000D_
_x000D_
  } else {_x000D_
       _x000D_
       $('.direction_value').text('Scrolling Up Scripts');_x000D_
_x000D_
  }_x000D_
  currentscroll_position = running_scroll_position;_x000D_
}_x000D_
_x000D_
});
_x000D_
.direction_value{_x000D_
  position: fixed;_x000D_
  height: 30px;_x000D_
  background-color: #333;_x000D_
  color: #fff;_x000D_
  text-align: center;_x000D_
  z-index: 99;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="direction_value">_x000D_
</div>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
_x000D_
_x000D_
_x000D_

How to cancel a local git commit

If you're in the middle of a commit (i.e. in your editor already), you can cancel it by deleting all lines above the first #. That will abort the commit.

So you can delete all lines so that the commit message is empty, then save the file:

It should look like this.

You'll then get a message that says Aborting commit due to empty commit message..

EDIT:

You can also delete all the lines and the result will be exactly the same.

To delete all lines in vim (if that is your default editor), once you're in the editor, type gg to go to the first line, then dG to delete all lines. Finally, write and quit the file with wq and your commit will be aborted.

What is the preferred/idiomatic way to insert into a map?

First of all, operator[] and insert member functions are not functionally equivalent :

  • The operator[] will search for the key, insert a default constructed value if not found, and return a reference to which you assign a value. Obviously, this can be inefficient if the mapped_type can benefit from being directly initialized instead of default constructed and assigned. This method also makes it impossible to determine if an insertion has indeed taken place or if you have only overwritten the value for an previously inserted key
  • The insert member function will have no effect if the key is already present in the map and, although it is often forgotten, returns an std::pair<iterator, bool> which can be of interest (most notably to determine if insertion has actually been done).

From all the listed possibilities to call insert, all three are almost equivalent. As a reminder, let's have look at insert signature in the standard :

typedef pair<const Key, T> value_type;

  /* ... */

pair<iterator, bool> insert(const value_type& x);

So how are the three calls different ?

  • std::make_pair relies on template argument deduction and could (and in this case will) produce something of a different type than the actual value_type of the map, which will require an additional call to std::pair template constructor in order to convert to value_type (ie : adding const to first_type)
  • std::pair<int, int> will also require an additional call to the template constructor of std::pair in order to convert the parameter to value_type (ie : adding const to first_type)
  • std::map<int, int>::value_type leaves absolutely no place for doubt as it is directly the parameter type expected by the insert member function.

In the end, I would avoid using operator[] when the objective is to insert, unless there is no additional cost in default-constructing and assigning the mapped_type, and that I don't care about determining if a new key has effectively inserted. When using insert, constructing a value_type is probably the way to go.

Find if listA contains any elements not in listB

Get the difference of two lists using Any(). The Linq Any() function returns a boolean if a condition is met but you can use it to return the difference of two lists:

var difference = ListA.Where(a => !ListB.Any(b => b.ListItem == a.ListItem)).ToList();

using setTimeout on promise chain

To keep the promise chain going, you can't use setTimeout() the way you did because you aren't returning a promise from the .then() handler - you're returning it from the setTimeout() callback which does you no good.

Instead, you can make a simple little delay function like this:

function delay(t, v) {
   return new Promise(function(resolve) { 
       setTimeout(resolve.bind(null, v), t)
   });
}

And, then use it like this:

getLinks('links.txt').then(function(links){
    let all_links = (JSON.parse(links));
    globalObj=all_links;

    return getLinks(globalObj["one"]+".txt");

}).then(function(topic){
    writeToBody(topic);
    // return a promise here that will be chained to prior promise
    return delay(1000).then(function() {
        return getLinks(globalObj["two"]+".txt");
    });
});

Here you're returning a promise from the .then() handler and thus it is chained appropriately.


You can also add a delay method to the Promise object and then directly use a .delay(x) method on your promises like this:

_x000D_
_x000D_
function delay(t, v) {_x000D_
   return new Promise(function(resolve) { _x000D_
       setTimeout(resolve.bind(null, v), t)_x000D_
   });_x000D_
}_x000D_
_x000D_
Promise.prototype.delay = function(t) {_x000D_
    return this.then(function(v) {_x000D_
        return delay(t, v);_x000D_
    });_x000D_
}_x000D_
_x000D_
_x000D_
Promise.resolve("hello").delay(500).then(function(v) {_x000D_
    console.log(v);_x000D_
});
_x000D_
_x000D_
_x000D_

Or, use the Bluebird promise library which already has the .delay() method built-in.

Detect iPad users using jQuery?

I use this:

function fnIsAppleMobile() 
{
    if (navigator && navigator.userAgent && navigator.userAgent != null) 
    {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches != null) 
             return true;
    } // End if (navigator && navigator.userAgent) 

    return false;
} // End Function fnIsAppleMobile


var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove

Select query to remove non-numeric characters

This works well for me:

CREATE FUNCTION [dbo].[StripNonNumerics]
(
  @Temp varchar(255)
)
RETURNS varchar(255)
AS
Begin

    Declare @KeepValues as varchar(50)
    Set @KeepValues = '%[^0-9]%'
    While PatIndex(@KeepValues, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')

    Return @Temp
End

Then call the function like so to see the original something next to the sanitized something:

SELECT Something, dbo.StripNonNumerics(Something) FROM TableA

How to get the hostname of the docker host from inside a docker container on that host without env vars

I think the reason that I have the same issue is a bug in the latest Docker for Mac beta, but buried in the comments there I was able to find a solution that worked for me & my team. We're using this for local development, where we need our containerized services to talk to a monolith as we work to replace it. This is probably not a production-viable solution.

On the host machine, alias a known available IP address to the loopback interface:

$ sudo ifconfig lo0 alias 10.200.10.1/24

Then add that IP with a hostname to your docker config. In my case, I'm using docker-compose, so I added this to my docker-compose.yml:

extra_hosts:
# configure your host to alias 10.200.10.1 to the loopback interface:
#       sudo ifconfig lo0 alias 10.200.10.1/24
- "relevant_hostname:10.200.10.1"

I then verified that the desired host service (a web server) was available from inside the container by attaching to a bash session, and using wget to request a page from the host's web server:

$ docker exec -it container_name /bin/bash
$ wget relevant_hostname/index.html
$ cat index.html

How to add a line to a multiline TextBox?

If you know how many lines you want, create an array of String with that many members (e.g. myStringArray). Then use myListBox.Lines = myStringArray;

jQuery UI Datepicker - Multiple Date Selections

<div id="calendar"></div>
<script>
$(document).ready(function() {
    var days = [];

    $('#calendar').datepicker({
        dateFormat: 'yymmdd',
        showWeek: true, showOtherMonths: false, selectOtherMonths: false,
        navigationAsDateFormat: true, prevText: 'MM', nextText: 'MM',
        onSelect: function(d) {
            var i = $.inArray(d, days);

            if (i == -1)
                days.push(d);
            else
                days.splice(i, 1);
        },
        beforeShowDay: function(d) {
            return ([true, $.inArray($.datepicker.formatDate('yymmdd', d), days) == -1 ? 'ui-state-free' : 'ui-state-busy']);
        }
    });
});
</script>

NOTE: You can prefill days with a list of dates like '20190101' with a piece of code in PHP.

Add 2 lines to your CSS:

#calendar .ui-state-busy a {background:#e6e6e6 !important;}
#calendar .ui-state-free a {background:none !important;}

To get the list of days selected by the calendar in a <form>:

<div id="calendar"></div>
<form method="post">
<input type="submit" name="calendar_get" id="calendar_get" value="Validate" />
</form>

Add this to the <script>:

    $('#calendar_get').click(function() {
        $(this).append('<input type="hidden" name="calendar_days" value="' + days.join(',') + '" />');
    });

Apply implode on the string in $_POST['calendar_days'] and map strtotime to all the formatted dates.

How can I check MySQL engine type for a specific table?

SHOW TABLE STATUS WHERE Name = 'xxx'

This will give you (among other things) an Engine column, which is what you want.

Load image from resources

ResourceManager will work if your image is in a resource file. If it is just a file in your project (let's say the root) you can get it using something like this:

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file = assembly .GetManifestResourceStream("AssemblyName." + channel);
this.pictureBox1.Image = Image.FromStream(file);

Or if you're in WPF:

    private ImageSource GetImage(string channel)
    {
        StreamResourceInfo sri = Application.GetResourceStream(new Uri("/TestApp;component/" + channel, UriKind.Relative));
        BitmapImage bmp = new BitmapImage();
        bmp.BeginInit();
        bmp.StreamSource = sri.Stream;
        bmp.EndInit();

        return bmp;
    }

How to create a DB for MongoDB container on start up?

UPD Today I avoid Docker Swarm, secrets, and configs. I'd run it with docker-compose and the .env file. As long as I don't need autoscaling. If I do, I'd probably choose k8s. And database passwords, root account or not... Do they really matter when you're running a single database in a container not connected to the outside world?.. I'd like to know what you think about it, but Stack Overflow is probably not well suited for this sort of communication.

Mongo image can be affected by MONGO_INITDB_DATABASE variable, but it won't create the database. This variable determines current database when running /docker-entrypoint-initdb.d/* scripts. Since you can't use environment variables in scripts executed by Mongo, I went with a shell script:

docker-swarm.yml:

version: '3.1'

secrets:
  mongo-root-passwd:
    file: mongo-root-passwd
  mongo-user-passwd:
    file: mongo-user-passwd

services:
  mongo:
    image: mongo:3.2
    environment:
      MONGO_INITDB_ROOT_USERNAME: $MONGO_ROOT_USER
      MONGO_INITDB_ROOT_PASSWORD_FILE: /run/secrets/mongo-root-passwd
      MONGO_INITDB_USERNAME: $MONGO_USER
      MONGO_INITDB_PASSWORD_FILE: /run/secrets/mongo-user-passwd
      MONGO_INITDB_DATABASE: $MONGO_DB
    volumes:
      - ./init-mongo.sh:/docker-entrypoint-initdb.d/init-mongo.sh
    secrets:
      - mongo-root-passwd
      - mongo-user-passwd

init-mongo.sh:

mongo -- "$MONGO_INITDB_DATABASE" <<EOF
    var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
    var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
    var admin = db.getSiblingDB('admin');
    admin.auth(rootUser, rootPassword);

    var user = '$MONGO_INITDB_USERNAME';
    var passwd = '$(cat "$MONGO_INITDB_PASSWORD_FILE")';
    db.createUser({user: user, pwd: passwd, roles: ["readWrite"]});
EOF

Alternatively, you can store init-mongo.sh in configs (docker config create) and mount it with:

configs:
    init-mongo.sh:
        external: true
...
services:
    mongo:
        ...
        configs:
            - source: init-mongo.sh
              target: /docker-entrypoint-initdb.d/init-mongo.sh

And secrets can be not stored in a file.

A couple of gists on the matter.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

Same answer as Claudius with a for loop:

for (Iterator<Object> it = objects.iterator(); it.hasNext();) {
    Object object = it.next();
    if (test) {
        it.remove();
    }
}

Rendering React Components from Array of Objects

this.data presumably contains all the data, so you would need to do something like this:

var stations = [];
var stationData = this.data.stations;

for (var i = 0; i < stationData.length; i++) {
    stations.push(
        <div key={stationData[i].call} className="station">
            Call: {stationData[i].call}, Freq: {stationData[i].frequency}
        </div>
    )
}

render() {
  return (
    <div className="stations">{stations}</div>
  )
}

Or you can use map and arrow functions if you're using ES6:

const stations = this.data.stations.map(station =>
    <div key={station.call} className="station">
      Call: {station.call}, Freq: {station.frequency}
    </div>
);

How to change value of ArrayList element in java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

Is JavaScript object-oriented?

Javascript is not an object oriented language as typically considered, mainly due to lack of true inheritance, DUCK typing allows for a semi-true form of inheritance/polymorphism along with the Object.prototype allowing for complex function sharing. At its heart however the lack of inheritance leads to a weak polymorphism to take place since the DUCK typing will insist some object with the same attribute names are an instance of an Object which they were not intended to be used as. Thus adding attributes to random object transforms their type's base in a manner of speaking.

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

For adding a RelativeLayout attribute whose value is true or false use 0 for false and RelativeLayout.TRUE for true:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) button.getLayoutParams()
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE)

It doesn't matter whether or not the attribute was already added, you still use addRule(verb, subject) to enable/disable it. However, post-API 17 you can use removeRule(verb) which is just a shortcut for addRule(verb, 0).

How can one see the structure of a table in SQLite?

If you are using PHP you can get it this way:

<?php
    $dbname = 'base.db';
    $db = new SQLite3($dbname);
    $sturturequery = $db->query("SELECT sql FROM sqlite_master WHERE name='foo'");

    $table = $sturturequery->fetchArray();
    echo '<pre>' . $table['sql'] . '</pre>';

    $db->close();
?>

How do I install and use curl on Windows?

Note also that installing Git for Windows from git-scm.com also installs Curl. You can then run Curl from Git for Windows' BASH terminal (not the default Windows CMD terminal).

How to write an async method with out parameter?

I love the Try pattern. It's a tidy pattern.

if (double.TryParse(name, out var result))
{
    // handle success
}
else
{
    // handle error
}

But, it's challenging with async. That doesn't mean we don't have real options. Here are the three core approaches you can consider for async methods in a quasi-version of the Try pattern.

Approach 1 - output a structure

This looks most like a sync Try method only returning a tuple instead of a bool with an out parameter, which we all know is not permitted in C#.

var result = await DoAsync(name);
if (result.Success)
{
    // handle success
}
else
{
    // handle error
}

With a method that returns true of false and never throws an exception.

Remember, throwing an exception in a Try method breaks the whole purpose of the pattern.

async Task<(bool Success, StorageFile File, Exception exception)> DoAsync(string fileName)
{
    try
    {
        var folder = ApplicationData.Current.LocalCacheFolder;
        return (true, await folder.GetFileAsync(fileName), null);
    }
    catch (Exception exception)
    {
        return (false, null, exception);
    }
}

Approach 2 - pass in callback methods

We can use anonymous methods to set external variables. It's clever syntax, though slightly complicated. In small doses, it's fine.

var file = default(StorageFile);
var exception = default(Exception);
if (await DoAsync(name, x => file = x, x => exception = x))
{
    // handle success
}
else
{
    // handle failure
}

The method obeys the basics of the Try pattern but sets out parameters to passed in callback methods. It's done like this.

async Task<bool> DoAsync(string fileName, Action<StorageFile> file, Action<Exception> error)
{
    try
    {
        var folder = ApplicationData.Current.LocalCacheFolder;
        file?.Invoke(await folder.GetFileAsync(fileName));
        return true;
    }
    catch (Exception exception)
    {
        error?.Invoke(exception);
        return false;
    }
}

There's a question in my mind about performance here. But, the C# compiler is so freaking smart, that I think you're safe choosing this option, almost for sure.

Approach 3 - use ContinueWith

What if you just use the TPL as designed? No tuples. The idea here is that we use exceptions to redirect ContinueWith to two different paths.

await DoAsync(name).ContinueWith(task =>
{
    if (task.Exception != null)
    {
        // handle fail
    }
    if (task.Result is StorageFile sf)
    {
        // handle success
    }
});

With a method that throws an exception when there is any kind of failure. That's different than returning a boolean. It's a way to communicate with the TPL.

async Task<StorageFile> DoAsync(string fileName)
{
    var folder = ApplicationData.Current.LocalCacheFolder;
    return await folder.GetFileAsync(fileName);
}

In the code above, if the file is not found, an exception is thrown. This will invoke the failure ContinueWith that will handle Task.Exception in its logic block. Neat, huh?

Listen, there's a reason we love the Try pattern. It's fundamentally so neat and readable and, as a result, maintainable. As you choose your approach, watchdog for readability. Remember the next developer who in 6 months and doesn't have you to answer clarifying questions. Your code can be the only documentation a developer will ever have.

Best of luck.

Import Certificate to Trusted Root but not to Personal [Command Line]

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx this works but still a password is needed to be typed in manually for private key. Including -p and "password" cause error too many arguments for certutil on XP

Writing to a new file if it doesn't exist, and appending to a file if it does

Have you tried mode 'a+'?

with open(filename, 'a+') as f:
    f.write(...)

Note however that f.tell() will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.

jquery toggle slide from left to right and back

Hide #categories initially

#categories {
    display: none;
}

and then, using JQuery UI, animate the Menu slowly

var duration = 'slow';

$('#cat_icon').click(function () {
    $('#cat_icon').hide(duration, function() {
        $('#categories').show('slide', {direction: 'left'}, duration);});
});
$('.panel_title').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

You can use any time in milliseconds as well

var duration = 2000;

If you want to hide on class='panel_item' too, select both panel_title and panel_item

$('.panel_title,.panel_item').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

What is more efficient? Using pow to square or just multiply it with itself?

If the exponent is constant and small, expand it out, minimizing the number of multiplications. (For example, x^4 is not optimally x*x*x*x, but y*y where y=x*x. And x^5 is y*y*x where y=x*x. And so on.) For constant integer exponents, just write out the optimized form already; with small exponents, this is a standard optimization that should be performed whether the code has been profiled or not. The optimized form will be quicker in so large a percentage of cases that it's basically always worth doing.

(If you use Visual C++, std::pow(float,int) performs the optimization I allude to, whereby the sequence of operations is related to the bit pattern of the exponent. I make no guarantee that the compiler will unroll the loop for you, though, so it's still worth doing it by hand.)

[edit] BTW pow has a (un)surprising tendency to crop up on the profiler results. If you don't absolutely need it (i.e., the exponent is large or not a constant), and you're at all concerned about performance, then best to write out the optimal code and wait for the profiler to tell you it's (surprisingly) wasting time before thinking further. (The alternative is to call pow and have the profiler tell you it's (unsurprisingly) wasting time -- you're cutting out this step by doing it intelligently.)

Read remote file with node.js (http.get)

http.get(options).on('response', function (response) {
    var body = '';
    var i = 0;
    response.on('data', function (chunk) {
        i++;
        body += chunk;
        console.log('BODY Part: ' + i);
    });
    response.on('end', function () {

        console.log(body);
        console.log('Finished');
    });
});

Changes to this, which works. Any comments?

How can I pretty-print JSON using Go?

By pretty-print, I assume you mean indented, like so

{
    "data": 1234
}

rather than

{"data":1234}

The easiest way to do this is with MarshalIndent, which will let you specify how you would like it indented via the indent argument. Thus, json.MarshalIndent(data, "", " ") will pretty-print using four spaces for indentation.

How do I check if an element is hidden in jQuery?

if($('#id_element').is(":visible")){
   alert('shown');
}else{
   alert('hidden');
}

pip broke. how to fix DistributionNotFound error?

I had this problem because I installed python/pip with a weird ~/.pydistutils.cfg that I didn't remember writing. Deleted it, reinstalled (with pybrew), and everything was fine.

Elegant way to read file into byte[] array in Java

A long time ago:

Call any of these

byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 

From

http://commons.apache.org/io/

If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library

Today (Java 7+ or Android API Level 26+)

Luckily, we now have a couple of convenience methods in the nio packages. For instance:

byte[] java.nio.file.Files.readAllBytes(Path path)

Javadoc here

fatal: 'origin' does not appear to be a git repository

I faced the same problem when I renamed my repository on GitHub. I tried to push at which point I got the error

fatal: 'origin' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

I had to change the URL using

git remote set-url origin ssh://[email protected]/username/newRepoName.git

After this all commands started working fine. You can check the change by using

git remote -v

In my case after successfull change it showed correct renamed repo in URL

[aniket@alok Android]$ git remote -v
origin  ssh://[email protected]/aniket91/TicTacToe.git (fetch)
origin  ssh://[email protected]/aniket91/TicTacToe.git (push)

Design Android EditText to show error message as described by google

reVerse's answer is great but it didn't point out how to remove the floating error tooltip kind of thing

You'll need edittext.setError(null) to remove that.
Also, as someone pointed out, you don't need TextInputLayout.setErrorEnabled(true)

Layout

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter something" />
</android.support.design.widget.TextInputLayout>

Code

TextInputLayout til = (TextInputLayout) editText.getParent();
til.setError("Your input is not valid...");
editText.setError(null);

Adding maven nexus repo to my pom.xml

It seems the answers here do not support an enterprise use case where a Nexus server has multiple users and has project-based isolation (protection) based on user id ALONG with using an automated build (CI) system like Jenkins. You would not be able to create a settings.xml file to satisfy the different user ids needed for different projects. I am not sure how to solve this, except by opening Nexus up to anonymous access for reading repositories, unless the projects could store a project-specific generic user id in their pom.xml.

Spring RequestMapping for controllers that produce and consume JSON

As of Spring 4.2.x, you can create custom mapping annotations, using @RequestMapping as a meta-annotation. So:

Is there a way to produce a "composite/inherited/aggregated" annotation with default values for consumes and produces, such that I could instead write something like:

@JSONRequestMapping(value = "/foo", method = RequestMethod.POST)

Yes, there is such a way. You can create a meta annotation like following:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(consumes = "application/json", produces = "application/json")
public @interface JsonRequestMapping {
    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String[] value() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "method")
    RequestMethod[] method() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "params")
    String[] params() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "headers")
    String[] headers() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "consumes")
    String[] consumes() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "produces")
    String[] produces() default {};
}

Then you can use the default settings or even override them as you want:

@JsonRequestMapping(method = POST)
public String defaultSettings() {
    return "Default settings";
}

@JsonRequestMapping(value = "/override", method = PUT, produces = "text/plain")
public String overrideSome(@RequestBody String json) {
    return json;
}

You can read more about AliasFor in spring's javadoc and github wiki.

How can I use xargs to copy files that have spaces and quotes in their names?

For those who relies on commands, other than find, eg ls:

find . | grep "FooBar" | tr \\n \\0 | xargs -0 -I{} cp "{}" ~/foo/bar

Get child Node of another Node, given node name

Check if the Node is a Dom Element, cast, and call getElementsByTagName()

Node doc = docs.item(i);
if(doc instanceof Element) {
    Element docElement = (Element)doc;
    ...
    cell = doc.getElementsByTagName("aoo").item(0);
}

sass :first-child not working

While @Andre is correct that there are issues with pseudo elements and their support, especially in older (IE) browsers, that support is improving all the time.

As for your question of, are there any issues, I'd say I've not really seen any, although the syntax for the pseudo-element can be a bit tricky, especially when first sussing it out. So:

div#top-level
  declarations: ...
  div.inside
    declarations: ...
    &:first-child
      declarations: ...

which compiles as one would expect:

div#top-level{
  declarations... }
div#top-level div.inside {
  declarations... }
div#top-level div.inside:first-child {
  declarations... }

I haven't seen any documentation on any of this, save for the statement that "sass can do everything that css can do." As always, with Haml and SASS the indentation is everything.

Git push rejected "non-fast-forward"

I had a similar problem and I resolved it with: git pull origin

Python - 'ascii' codec can't decode byte

In case you're dealing with Unicode, sometimes instead of encode('utf-8'), you can also try to ignore the special characters, e.g.

"??".encode('ascii','ignore')

or as something.decode('unicode_escape').encode('ascii','ignore') as suggested here.

Not particularly useful in this example, but can work better in other scenarios when it's not possible to convert some special characters.

Alternatively you can consider replacing particular character using replace().

Why do I get access denied to data folder when using adb?

I had a similar problem when trying to operate on a rooted Samsung Galaxy S. Issuing a command from the computer shell

> adb root

fails with a message "cannot run as root in production builds". Here is a simple method that allows to become root.

Instead of the previous, issue the following two commands one after the other

> adb shell
$ su

After the first command, if the prompt has changed from '>' to '$' as shown above, it means that you have entered the adb shell environment. If subsequently the prompt has changed to '#' after issuing the second command, that means that you are now root. Now, as root, you can do anything you want with your device.

To switch back to 'safe' shell, issue

# exit

You will see that the prompt '$' reappears which means you are in the adb shell as a user and not as root.

Find and replace string values in list

An example with for loop (I prefer List Comprehensions).

a, b = '[br]', '<br />'
for i, v in enumerate(words):
    if a in v:
        words[i] = v.replace(a, b)
print(words)
# ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

If you don't have non-ASCII characters (codepoints 128 and above) in your file, UTF-8 without BOM is the same as ASCII, byte for byte - so Notepad++ will guess wrong.

What you need to do is to specify the character encoding when serving the AJAX response - e.g. with PHP, you'd do this:

header('Content-Type: application/json; charset=utf-8');

The important part is to specify the charset with every JS response - else IE will fall back to user's system default encoding, which is wrong most of the time.

Change the column label? e.g.: change column "A" to column "Name"

What version of Excel?

In general, you cannot change the column letters. They are part of the Excel system.

You can use a row in the sheet to enter headers for a table that you are using. The table headers can be descriptive column names.

In Excel 2007 and later, you can convert a range of data into an Excel Table (Insert Ribbon > Table). An Excel Table can use structured table references instead of cell addresses, so the labels in the first row of the table now serve as a name reference for the data in the column.

If you have an Excel Table in your sheet (Excel 2007 and later) and scroll down, the column letters will be replaced with the column headers for the table column.

enter image description here

If this does not answer your question, please consider editing your question to include the detail you want to learn about.

How do I make a C++ macro behave like a function?

Macros should generally be avoided; prefer inline functions to them at all times. Any compiler worth its salt should be capable of inlining a small function as if it were a macro, and an inline function will respect namespaces and other scopes, as well as evaluating all the arguments once.

If it must be a macro, a while loop (already suggested) will work, or you can try the comma operator:

#define MACRO(X,Y) \
 ( \
  (cout << "1st arg is:" << (X) << endl), \
  (cout << "2nd arg is:" << (Y) << endl), \
  (cout << "3rd arg is:" << ((X) + (Y)) << endl), \
  (void)0 \
 )

The (void)0 causes the statement to evaluate to one of void type, and the use of commas rather than semicolons allows it to be used inside a statement, rather than only as a standalone. I would still recommend an inline function for a host of reasons, the least of which being scope and the fact that MACRO(a++, b++) will increment a and b twice.

Set textbox to readonly and background color to grey in jquery

Why don't you place the account number in a div. Style it as you please and then have a hidden input in the form that also contains the account number. Then when the form gets submitted, the value should come through and not be null.

What are alternatives to document.write?

Try to use getElementById() or getElementsByName() to access a specific element and then to use innerHTML property:

<html>
    <body>
        <div id="myDiv1"></div>
        <div id="myDiv2"></div>
    </body>

    <script type="text/javascript">
        var myDiv1 = document.getElementById("myDiv1");
        var myDiv2 = document.getElementById("myDiv2");

        myDiv1.innerHTML = "<b>Content of 1st DIV</b>";
        myDiv2.innerHTML = "<i>Content of second DIV element</i>";
    </script>
</html>

HTTP Error 500.19 and error code : 0x80070021

I solved this by doing the following:

WebServer(ISS)->WebServer->Application Development
add .NET Extensibility 3.5
add .NET Extensibility 4.5
add ASP.NET 4.5
add ISAPI Extensions
add ISAPI Filters

enter image description here

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

I get this error whenever I use np.concatenate the wrong way:

>>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index

The correct way is to input the two arrays as a tuple:

>>> np.concatenate((a, a))
array([[1., 0.],
       [0., 1.],
       [1., 0.],
       [0., 1.]])

How to setup virtual environment for Python in VS Code?

The question is how to create a new virtual environment in VSCode, that is why telling the following Anaconda solution might not the needed answer to the question. It is just relevant for Anaconda users.

Just create a venv using conda, see here. Afterwards open VSCode and left-click on the VSCode interpreter shown in VSCode at the bottom left:

vscode interpreter info

Choose a virtual environment that pops up in a dropdown of the settings window, and you are done. Mind the answer of @RamiMa.

Parsing JSON with Unix tools

Using Node.js

If the system has installed, it's possible to use the -p print and -e evaulate script flags with JSON.parse to pull out any value that is needed.

A simple example using the JSON string { "foo": "bar" } and pulling out the value of "foo":

$ node -pe 'JSON.parse(process.argv[1]).foo' '{ "foo": "bar" }'
bar

Because we have access to cat and other utilities, we can use this for files:

$ node -pe 'JSON.parse(process.argv[1]).foo' "$(cat foobar.json)"
bar

Or any other format such as an URL that contains JSON:

$ node -pe 'JSON.parse(process.argv[1]).name' "$(curl -s https://api.github.com/users/trevorsenior)"
Trevor Senior

Get CPU Usage from Windows Command Prompt

typeperf "\processor(_total)\% processor time"

does work on Win7, you just need to extract the percent value yourself from the last quoted string.

How do I change the default library path for R packages

Windows 10 on a Network

Having your packages stored on the network drive can slow down the performance of R / R Studio considerably, and you spend a lot of time waiting for the libraries to load/install, due to the bottlenecks of having to retrieve and push data over the server back to your local host. See the following for instructions on how to create an .RProfile on your local machine:

  1. Create a directory called C:\Users\xxxxxx\Documents\R\3.4 (or whatever R version you are using, and where you will store your local R packages- your directory location may be different than mine)
  2. On R Console, type Sys.getenv("HOME") to get your home directory (this is where your .RProfile will be stored and R will always check there for packages- and this is on the network if packages are stored there)
  3. Create a file called .Rprofile and place it in :\YOUR\HOME\DIRECTORY\ON_NETWORK (the directory you get after typing Sys.getenv("HOME") in R Console)
  4. File contents of .Rprofile should be like this:

#search 2 places for packages- install new packages to first directory- load built-in packages from the second (this is from your base R package- will be different for some)

.libPaths(c("C:\Users\xxxxxx\Documents\R\3.4", "C:/Program Files/Microsoft/R Client/R_SERVER/library"))

message("*** Setting libPath to local hard drive ***")

#insert a sleep command at line 12 of the unpackPkgZip function. So, just after the package is unzipped.

trace(utils:::unpackPkgZip, quote(Sys.sleep(2)), at=12L, print=TRUE)

message("*** Add 2 second delay when installing packages, to accommodate virus scanner for R 3.4 (fixed in R 3.5+)***")

# fix problem with tcltk for sqldf package: https://github.com/ggrothendieck/sqldf#problem-involvling-tcltk

options(gsubfn.engine = "R")

message("*** Successfully loaded .Rprofile ***")
  1. Restart R Studio and verify that you see that the messages above are displayed.

Now you can enjoy faster performance of your application on local host, vs. storing the packages on the network and slowing everything down.

Restful API service

Also when I hit the post(Config.getURL("login"), values) the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!)

No you have to create a thread yourself, a Local service runs in the UI thread by default.

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

How enable auto-format code for Intellij IDEA?

The formatting shortcuts in Intellij IDEA are :

  • For Windows : Ctrl + Alt + L
  • For Ubuntu : Ctrl + Alt + Windows + L
  • For Mac : ? (Option) + ? (Command) + L

Python: call a function from string name

If it's in a class, you can use getattr:

class MyClass(object):
    def install(self):
          print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
    method = getattr(my_cls, method_name)
except AttributeError:
    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method()

or if it's a function:

def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

Printing result of mysql query from variable

well you are returning an array of items from the database. so you need something like this.

   $dave= mysql_query("SELECT order_date, no_of_items, shipping_charge, 
    SUM(total_order_amount) as test FROM `orders` 
    WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)") 
    or  die(mysql_error());


while ($row = mysql_fetch_assoc($dave)) {
echo $row['order_date'];
echo $row['no_of_items'];
echo $row['shipping_charge'];
echo $row['test '];
}

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

It might also be worth mentioning that inline will try to open Office Documents (xls, doc etc) directly from the server, which might lead to a User Credentials Prompt.

see this link:

http://forums.asp.net/t/1885657.aspx/1?Access+the+SSRS+Report+in+excel+format+on+server

somebody tried to deliver an Excel Report from SSRS via ASP.Net -> the user always got prompted to enter the credentials. After clicking cancel on the prompt it would be opened anyway...

If the Content Disposition is marked as Attachment it will automatically be saved to the temp folder after clicking open and then opened in Excel from the local copy.

Creating an empty file in C#

Using just File.Create will leave the file open, which probably isn't what you want.

You could use:

using (File.Create(filename)) ;

That looks slightly odd, mind you. You could use braces instead:

using (File.Create(filename)) {}

Or just call Dispose directly:

File.Create(filename).Dispose();

Either way, if you're going to use this in more than one place you should probably consider wrapping it in a helper method, e.g.

public static void CreateEmptyFile(string filename)
{
    File.Create(filename).Dispose();
}

Note that calling Dispose directly instead of using a using statement doesn't really make much difference here as far as I can tell - the only way it could make a difference is if the thread were aborted between the call to File.Create and the call to Dispose. If that race condition exists, I suspect it would also exist in the using version, if the thread were aborted at the very end of the File.Create method, just before the value was returned...

Best way to store a key=>value array in JavaScript?

I know its late but it might be helpful for those that want other ways. Another way array key=>values can be stored is by using an array method called map(); (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) you can use arrow function too

 
    var countries = ['Canada','Us','France','Italy'];  
// Arrow Function
countries.map((value, key) => key+ ' : ' + value );
// Anonomous Function
countries.map(function(value, key){
return key + " : " + value;
});

Python Accessing Nested JSON Data

I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:

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

print j['state']
print j['places'][1]['post code']

How to build an android library with Android Studio and gradle?

Note: This answer is a pure Gradle answer, I use this in IntelliJ on a regular basis but I don't know how the integration is with Android Studio. I am a believer in knowing what is going on for me, so this is how I use Gradle and Android.

TL;DR Full Example - https://github.com/ethankhall/driving-time-tracker/

Disclaimer: This is a project I am/was working on.

Gradle has a defined structure ( that you can change, link at the bottom tells you how ) that is very similar to Maven if you have ever used it.

Project Root
+-- src
|   +-- main (your project)
|   |   +-- java (where your java code goes)
|   |   +-- res  (where your res go)
|   |   +-- assets (where your assets go)
|   |   \-- AndroidManifest.xml
|   \-- instrumentTest (test project)
|       \-- java (where your java code goes)
+-- build.gradle
\-- settings.gradle

If you only have the one project, the settings.gradle file isn't needed. However you want to add more projects, so we need it.

Now let's take a peek at that build.gradle file. You are going to need this in it (to add the android tools)

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.3'
    }
}

Now we need to tell Gradle about some of the Android parts. It's pretty simple. A basic one (that works in most of my cases) looks like the following. I have a comment in this block, it will allow me to specify the version name and code when generating the APK.

build.gradle

apply plugin: "android"
android {
        compileSdkVersion 17
        /*
        defaultConfig {
            versionCode = 1
            versionName = "0.0.0"
        }
        */
    }

Something we are going to want to add, to help out anyone that hasn't seen the light of Gradle yet, a way for them to use the project without installing it.

build.gradle

task wrapper(type: org.gradle.api.tasks.wrapper.Wrapper) {
    gradleVersion = '1.4'
}

So now we have one project to build. Now we are going to add the others. I put them in a directory, maybe call it deps, or subProjects. It doesn't really matter, but you will need to know where you put it. To tell Gradle where the projects are you are going to need to add them to the settings.gradle.

Directory Structure:

Project Root
+-- src (see above)
+-- subProjects (where projects are held)
|   +-- reallyCoolProject1 (your first included project)
|       \-- See project structure for a normal app
|   \-- reallyCoolProject2 (your second included project)
|       \-- See project structure for a normal app
+-- build.gradle
\-- settings.gradle

settings.gradle:

include ':subProjects:reallyCoolProject1'
include ':subProjects:reallyCoolProject2'

The last thing you should make sure of is the subProjects/reallyCoolProject1/build.gradle has apply plugin: "android-library" instead of apply plugin: "android".

Like every Gradle project (and Maven) we now need to tell the root project about it's dependency. This can also include any normal Java dependencies that you want.

build.gradle

dependencies{
    compile 'com.fasterxml.jackson.core:jackson-core:2.1.4'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.1.4'
    compile project(":subProjects:reallyCoolProject1")
    compile project(':subProjects:reallyCoolProject2')
}

I know this seems like a lot of steps, but they are pretty easy once you do it once or twice. This way will also allow you to build on a CI server assuming you have the Android SDK installed there.

NDK Side Note: If you are going to use the NDK you are going to need something like below. Example build.gradle file can be found here: https://gist.github.com/khernyo/4226923

build.gradle

task copyNativeLibs(type: Copy) {
    from fileTree(dir: 'libs', include: '**/*.so' )  into  'build/native-libs'
}
tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs }

clean.dependsOn 'cleanCopyNativeLibs'

tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->
  pkgTask.jniDir new File('build/native-libs')
}

Sources:

  1. http://tools.android.com/tech-docs/new-build-system/user-guide
  2. https://gist.github.com/khernyo/4226923
  3. https://github.com/ethankhall/driving-time-tracker/

Static Vs. Dynamic Binding in Java

In the case of the static binding type of object determined at the compile-time whereas in the dynamic binding type of the object is determined at the runtime.



class Dainamic{

    void run2(){
        System.out.println("dainamic_binding");
    }

}


public class StaticDainamicBinding extends Dainamic {

    void run(){
        System.out.println("static_binding");
    }

    @Override
    void run2() {
        super.run2();
    }

    public static void main(String[] args) {
        StaticDainamicBinding st_vs_dai = new StaticDainamicBinding();
        st_vs_dai.run();
        st_vs_dai.run2();
    }

}

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

I faced the same error but i solved this by selecting invalidate caches/restart option.

Click

  1. file >> invalidate caches/restart

Handling null values in Freemarker

You can use the ?? test operator:

This checks if the attribute of the object is not null:

<#if object.attribute??></#if>

This checks if object or attribute is not null:

<#if (object.attribute)??></#if>

Source: FreeMarker Manual

Angular 2 Dropdown Options Default Value

works great as seen below:

<select class="form-control" id="selectTipoDocumento" formControlName="tipoDocumento" [compareWith]="equals"
          [class.is-valid]="this.docForm.controls['tipoDocumento'].valid &&
           (this.docForm.controls['tipoDocumento'].touched ||  this.docForm.controls['tipoDocumento'].dirty)"
          [class.is-invalid]="!this.docForm.controls['tipoDocumento'].valid &&
           (this.docForm.controls['tipoDocumento'].touched ||  this.docForm.controls['tipoDocumento'].dirty)">
            <option value="">Selecione um tipo</option>
            <option *ngFor="let tipo of tiposDocumento" [ngValue]="tipo">{{tipo?.nome}}</option>
          </select>

How to get the request parameters in Symfony 2?

You can do it this:

$clientName = $request->request->get('appbundle_client')['clientName'];

Sometimes, when the attributes are protected, you can not have access to get the value for the common method of access:

(POST)

 $clientName = $request->request->get('clientName');

(GET)

$clientName = $request->query->get('clientName');

(GENERIC)

$clientName = $request->get('clientName');

How do I remove a library from the arduino environment?

The answer is only valid if you have not changed the "Sketchbook Location" field in Preferences. So, first, you need to open the Arduino IDE and go to the menu

"File -> Preferences"

In the dialog, look at the field "Sketchbook Location" and open the corresponding folder. The "libraries" folder in inside.

Passing a callback function to another class

You could change your code in this way:

public delegate void CallbackHandler(string str);

public class ServerRequest
{
    public void DoRequest(string request, CallbackHandler callback)
    {
        // do stuff....
        callback("asdf");
    }
}

Android: how to refresh ListView contents?

I'm doing the same thing using invalidateViews() and that works for me. If you want it to invalidate immediately you could try calling postInvalidate after calling invalidateViews.

Table border left and bottom

you can use these styles:

style="border-left: 1px solid #cdd0d4;"  
style="border-bottom: 1px solid #cdd0d4;"
style="border-top: 1px solid #cdd0d4;"
style="border-right: 1px solid #cdd0d4;"

with this you want u must use

<td style="border-left: 1px solid #cdd0d4;border-bottom: 1px solid #cdd0d4;">  

or

<img style="border-left: 1px solid #cdd0d4;border-bottom: 1px solid #cdd0d4;"> 

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Another item check:

Make sure you component is added to the declarations array of @NgModule in app.module.ts

@NgModule({
declarations: [
    YourComponent,
],

When running the ng generate component command, it does not automatilly add it to app.module.

How to use Boost in Visual Studio 2010

Also a little note: If you want to reduce the compilation-time, you can add the flag

-j2

to run two parallel builds at the same time. This might reduce it to viewing one movie ;)

Cannot find the '@angular/common/http' module

note: This is for @angular/http, not the asked @angular/common/http!

Just import in this way, WORKS perfectly:

// Import HttpModule from @angular/http
import {HttpModule} from '@angular/http';


@NgModule({
  declarations: [
    MyApp,
    HelloIonicPage,
    ItemDetailsPage,
    ListPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [...],
  entryComponents: [...],
  providers: [... ]
})

and then you contruct in the service.ts like this:

constructor(private http: Http) { }

getmyClass(): Promise<myClass[]> {
  return this.http.get(URL)
             .toPromise()
             .then(response => response.json().data as myClass[])
             .catch(this.handleError);
}

console.log not working in Angular2 Component (Typescript)

Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support

I fixed console.log issue after updating latest browser.

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

GroupBy pandas DataFrame and select most common value

If you don't want to include NaN values, using Counter is much much faster than pd.Series.mode or pd.Series.value_counts()[0]:

def get_most_common(srs):
    x = list(srs)
    my_counter = Counter(x)
    return my_counter.most_common(1)[0][0]

df.groupby(col).agg(get_most_common)

should work. This will fail when you have NaN values, as each NaN will be counted separately.

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

Yes, it is possible. You have to do something like this:

if(isset($_POST['submit']))
{
  $type_id = ($_POST['type_id'] == '' ? "null" : "'".$_POST['type_id']."'");
  $sql = "INSERT INTO `table` (`type_id`) VALUES (".$type_id.")";
}

It checks if the $_POST['type_id'] variable has an empty value. If yes, it assign NULL as a string to it. If not, it assign the value with ' to it for the SQL notation