Programs & Examples On #Treenode

The base element of a hierarchical data structure.

Best way to resolve file path too long exception

You can create a symbolic link with a shorter directory. First open command line for example by Shift + RightClick in your desired folder with a shorter path (you may have to run it as administrator).

Then type with relative or absolute paths:

mklink ShortPath\To\YourLinkedSolution C:\Path\To\Your\Solution /D

And then start the Solution from the shorter path. The advantage here is: You don't have to move anything.

How do implement a breadth first traversal?

It doesn't seem like you're asking for an implementation, so I'll try to explain the process.

Use a Queue. Add the root node to the Queue. Have a loop run until the queue is empty. Inside the loop dequeue the first element and print it out. Then add all its children to the back of the queue (usually going from left to right).

When the queue is empty every element should have been printed out.

Also, there is a good explanation of breadth first search on wikipedia: http://en.wikipedia.org/wiki/Breadth-first_search

How to call a MySQL stored procedure from within PHP code?

I now found solution by using mysqli instead of mysql.

<?php 

// enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//connect to database
$connection = mysqli_connect("hostname", "user", "password", "db", "port");

//run the store proc
$result = mysqli_query($connection, "CALL StoreProcName");

//loop the result set
while ($row = mysqli_fetch_array($result)){     
  echo $row[0] . " - " . + $row[1]; 
}

I found that many people seem to have a problem with using mysql_connect, mysql_query and mysql_fetch_array.

DataGridView.Clear()

Try this Code

private void button_Click(object sender, EventArgs e) {
    if (this.dgInv.DataSource != null) {
        this.dgInv.DataSource = null;
    } else {
        this.dgInv.Rows.Clear();
    }
}

How do you check if a certain index exists in a table?

Wrote the below function that allows me to quickly check to see if an index exists; works just like OBJECT_ID.

CREATE FUNCTION INDEX_OBJECT_ID (
    @tableName VARCHAR(128),
    @indexName VARCHAR(128)
    )
RETURNS INT
AS
BEGIN
    DECLARE @objectId INT

    SELECT @objectId = i.object_id
    FROM sys.indexes i
    WHERE i.object_id = OBJECT_ID(@tableName)
    AND i.name = @indexName

    RETURN @objectId
END
GO

EDIT: This just returns the OBJECT_ID of the table, but it will be NULL if the index doesn't exist. I suppose you could set this to return index_id, but that isn't super useful.

Finding height in Binary Search Tree

The height of a binary search tree is equal to number of layers - 1.

See the diagram at http://en.wikipedia.org/wiki/Binary_tree

Your recursion is good, so just subtract one at the root level.

Also note, you can clean up the function a bit by handling null nodes:

int findHeight(node) {
  if (node == null) return 0;
  return 1 + max(findHeight(node.left), findHeight(node.right));
}

How do I define a method which takes a lambda as a parameter in Java 8?

There's a public Web-accessible version of the Lambda-enabled Java 8 JavaDocs, linked from http://lambdafaq.org/lambda-resources. (This should obviously be a comment on Joachim Sauer's answer, but I can't get into my SO account with the reputation points I need to add a comment.) The lambdafaq site (I maintain it) answers this and a lot of other Java-lambda questions.

NB This answer was written before the Java 8 GA documentation became publicly available. I've left in place, though, because the Lambda FAQ might still be useful to people learning about features introduced in Java 8.

How to make Visual Studio copy a DLL file to the output directory?

The details in the comments section above did not work for me (VS 2013) when trying to copy the output dll from one C++ project to the release and debug folder of another C# project within the same solution.

I had to add the following post build-action (right click on the project that has a .dll output) then properties -> configuration properties -> build events -> post-build event -> command line

now I added these two lines to copy the output dll into the two folders:

xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Release
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Debug

Access nested dictionary items via a list of keys?

Solved this with recursion:

def get(d,l):
    if len(l)==1: return d[l[0]]
    return get(d[l[0]],l[1:])

Using your example:

dataDict = {
    "a":{
        "r": 1,
        "s": 2,
        "t": 3
        },
    "b":{
        "u": 1,
        "v": {
            "x": 1,
            "y": 2,
            "z": 3
        },
        "w": 3
        }
}
maplist1 = ["a", "r"]
maplist2 = ["b", "v", "y"]
print(get(dataDict, maplist1)) # 1
print(get(dataDict, maplist2)) # 2

Is there a JavaScript function that can pad a string to get to a determined length?

Here's my take

I'm not so sure about it's performance, but I find it much more readable than other options I saw around here...

var replicate = function(len, char) {
  return Array(len+1).join(char || ' ');
};

var padr = function(text, len, char) {
  if (text.length >= len) return text;
  return text + replicate(len-text.length, char);
};

Ruby: How to convert a string to boolean

if value.to_s == 'true'
  true
elsif value.to_s == 'false'
  false
end

React JS get current date

You can use the react-moment package

-> https://www.npmjs.com/package/react-moment

Put in your file the next line:

import moment from "moment";

date_create: moment().format("DD-MM-YYYY hh:mm:ss")

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Also register your created service in the Manifest and uses-permission as

<application ...>
   <service android:name=".MyBroadcastReceiver">
        <intent-filter>
            <action android:name="com.example.MyBroadcastReciver"/>
        </intent-filter>
   </service>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

and then in braod cast Reciever call your service

public class MyBroadcastReceiver extends BroadcastReceiver 
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Intent myIntent = new Intent(context, MyService.class);
        context.startService(myIntent);
    }
}

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

This happened to me, and once I removed this: enctype="multipart/form-data" It started working without the warning

How do I see the commit differences between branches in git?

You can easily do that with

git log master..branch-X

That will show you commits that branch-X has but master doesn't.

jQuery Combobox/select autocomplete?

This works great for me and I'm doing more, writing less with jQuery's example modified.

I defined the select object on my page, just like the jQuery ex. I took the text and pushed it to an array. Then I use the array as my source to my input autocomplete. tadaa.

$(function() {
   var mySource = [];
   $("#mySelect").children("option").map(function() {
      mySource.push($(this).text());
   });

   $("#myInput").autocomplete({
      source: mySource,
      minLength: 3
   });
}

Echoing the last command run in Bash?

history | tail -2 | head -1 | cut -c8-999

tail -2 returns the last two command lines from history head -1 returns just first line cut -c8-999 returns just command line, removing PID and spaces.

Why use def main()?

Consider the second script. If you import it in another one, the instructions, as at "global level", will be executed.

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

after reading previous examples I came up with this:

protected static $nonce_length = 32;

public static function getNonce()
{
    $chars = array();
    for ($i = 0; $i < 10; $i++)
        $chars = array_merge($chars, range(0, 9), range('A', 'Z'));
    shuffle($chars);
    $start = mt_rand(0, count($chars) - self::$nonce_length);
    return substr(join('', $chars), $start, self::$nonce_length);
}

I duplicate 10 times the array[0-9,A-Z] and shuffle the elements, after I get a random start point for substr() to be more 'creative' :) you can add [a-z] and other elements to array, duplicate more or less, be more creative than me

Using a list as a data source for DataGridView

First, I don't understand why you are adding all the keys and values count times, Index is never used.

I tried this example :

        var source = new BindingSource();
        List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"),  new MyStruct("c","d") };
        source.DataSource = list;
        grid.DataSource = source;

and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.

    class MyStruct
   {
    public string Name { get; set; }
    public string Adres { get; set; }


    public MyStruct(string name, string adress)
    {
        Name = name;
        Adres = adress;
    }
  }

Try to build a type that takes one key and value, and add it one by one. Hope this helps.

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You get this error because one of your variables is actually a factor variable . Execute

str(df) 

to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:

df$year <- as.numeric(as.character(df$year))

EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:

df <- data.frame(apply(df, 2, unclass))

and plot again?

How do I run git log to see changes only for a specific branch?

The problem I was having, which I think is similar to this, is that master was too far ahead of my branch point for the history to be useful. (Navigating to the branch point would take too long.)

After some trial and error, this gave me roughly what I wanted:

git log --graph --decorate --oneline --all ^master^!

C# static class constructor

You can use static constructor to initialization static variable. Static constructor will be entry point for your class

public class MyClass
{

    static MyClass()
    {

        //write your initialization code here
    }

}

Toggle visibility property of div

To clean this up a little bit and maintain a single line of code (like you would with a toggle()), you can use a ternary operator so your code winds up looking like this (also using jQuery):

$('#video-over').css('visibility', $('#video-over').css('visibility') == 'hidden' ? 'visible' : 'hidden');

Formula px to dp, dp to px android

// for getting in terms of Decimal/Float

public static float convertPixelsToDp(float px, Context context) {

    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / (metrics.densityDpi / 160f);
    return Math.round(dp);
}



public static float convertDpToPixel(float dp, Context context) {
    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return Math.round(px);
}


// for  getting in terms of Integer

private int convertPxToDp(int px, Context context) {
    Resources resources = context.getResources();
    return Math.round(px / (resources.getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
}


private int convertDpToPx(int dp, Context context) {
    Resources resources = context.getResources();

    return Math.round(dp * (resources.getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));

}

________________________________________________________________________________

public static float convertPixelsToDp(float px){
    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    float dp = px / (metrics.densityDpi / 160f);
    return Math.round(dp);
}

public static float convertDpToPixel(float dp){
    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return Math.round(px);
}


private int convertDpToPx(int dp){
    return Math.round(dp*(getResources().getDisplayMetrics().xdpi/DisplayMetrics.DENSITY_DEFAULT));

}

private int convertPxToDp(int px){
    return Math.round(px/(Resources.getSystem().getDisplayMetrics().xdpi/DisplayMetrics.DENSITY_DEFAULT));
}

Instagram: Share photo from webpage

Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.

POST https://instagram.com/api/v1/media/upload/

Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php

Replacing instances of a character in a string

To replace a character at a specific index, the function is as follows:

def replace_char(s , n , c):
    n-=1
    s = s[0:n] + s[n:n+1].replace(s[n] , c) + s[n+1:]
    return s

where s is a string, n is index and c is a character.

Better way to set distance between flexbox items

A flex container with -x (negative) margin and flex items with x (positive) margin or padding both lead to the desired visual result: Flex items have a fixed gap of 2x only between each other.

It appears to be simply a matter of preference, whether to use margin or padding on the flex items.

In this example, the flex items are scaled dynamically in order to preserve the fixed gap:

.flex-container { 
  margin: 0 -5px;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.flex-item {
  margin: 0 5px; // Alternatively: padding: 0 5px;
  flex: 1 0 auto;
}

javascript clear field value input

Here is one solution with jQuery for browsers that don't support the placeholder attribute.

$('[placeholder]').focus(function() {
  var input = $(this);

  if (input.val() == input.attr('placeholder')) {
    input.val('');
    input.removeClass('placeholder');
  }
}).blur(function() {
  var input = $(this);

  if (input.val() == '' || input.val() == input.attr('placeholder')) {
    input.addClass('placeholder');
    input.val(input.attr('placeholder'));
  }
}).blur();

Found here: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

android.os.NetworkOnMainThreadException with android 4.2

Use StrictMode Something like this:-

   if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 
        }

Obtain smallest value from array in Javascript?

The tersest expressive code to find the minimum value is probably rest parameters:

_x000D_
_x000D_
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]_x000D_
const min = Math.min(...arr)_x000D_
console.log(min)
_x000D_
_x000D_
_x000D_


Rest parameters are essentially a convenient shorthand for Function.prototype.apply when you don't need to change the function's context:

_x000D_
_x000D_
var arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]_x000D_
var min = Math.min.apply(Math, arr)_x000D_
console.log(min)
_x000D_
_x000D_
_x000D_


This is also a great use case for Array.prototype.reduce:

_x000D_
_x000D_
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]_x000D_
const min = arr.reduce((a, b) => Math.min(a, b))_x000D_
console.log(min)
_x000D_
_x000D_
_x000D_

It may be tempting to pass Math.min directly to reduce, however the callback receives additional parameters:

callback (accumulator, currentValue, currentIndex, array)

In this particular case it may be a bit verbose. reduce is particularly useful when you have a collection of complex data that you want to aggregate into a single value:

_x000D_
_x000D_
const arr = [{name: 'Location 1', distance: 14}, {name: 'Location 2', distance: 58}, {name: 'Location 3', distance: 20}, {name: 'Location 4', distance: 77}, {name: 'Location 5', distance: 66}, {name: 'Location 6', distance: 82}, {name: 'Location 7', distance: 42}, {name: 'Location 8', distance: 67}, {name: 'Location 9', distance: 42}, {name: 'Location 10', distance: 4}]_x000D_
const closest = arr.reduce(_x000D_
  (acc, loc) =>_x000D_
    acc.distance < loc.distance_x000D_
      ? acc_x000D_
      : loc_x000D_
)_x000D_
console.log(closest)
_x000D_
_x000D_
_x000D_


And of course you can always use classic iteration:

_x000D_
_x000D_
var arr,_x000D_
  i,_x000D_
  l,_x000D_
  min_x000D_
_x000D_
arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]_x000D_
min = Number.POSITIVE_INFINITY_x000D_
for (i = 0, l = arr.length; i < l; i++) {_x000D_
  min = Math.min(min, arr[i])_x000D_
}_x000D_
console.log(min)
_x000D_
_x000D_
_x000D_

...but even classic iteration can get a modern makeover:

_x000D_
_x000D_
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]_x000D_
let min = Number.POSITIVE_INFINITY_x000D_
for (const value of arr) {_x000D_
  min = Math.min(min, value)_x000D_
}_x000D_
console.log(min)
_x000D_
_x000D_
_x000D_

npm start error with create-react-app

I have faced the following issue.

enter image description here

Please find the solution:

  1. Add "C:\Windows\System32" to the global PATH environment variable.

  2. Check whether the environment variables has been created for nodejs,npm and composer. if not create one

enter image description here

  1. Run your app.

Running vbscript from batch file

Well i am trying to open a .vbs within a batch file without having to click open but the answer to this question is ...

SET APPDATA=%CD%

start (your file here without the brackets with a .vbs if it is a vbd file)

two divs the same line, one dynamic width, one fixed

HTML:

<div id="parent">
  <div class="right"></div>
  <div class="left"></div>
</div>

(div.right needs to be before div.left in the HTML markup)

CSS:

.right {
float:right;
width:200px;
}

CSS Input Type Selectors - Possible to have an "or" or "not" syntax?

CSS3 has a pseudo-class called :not()

_x000D_
_x000D_
input:not([type='checkbox']) {    
    visibility: hidden;
}
_x000D_
<p>If <code>:not()</code> is supported, you'll only see the checkbox.</p>
                                      
<ul>
  <li>text: (<input type="text">)</li>  
  <li>password (<input type="password">)</li>       
  <li>checkbox (<input type="checkbox">)</li> 
 </ul>
_x000D_
_x000D_
_x000D_


Multiple selectors

As Vincent mentioned, it's possible to string multiple :not()s together:

input:not([type='checkbox']):not([type='submit'])

CSS4, which is supported in many of the latest browser releases, allows multiple selectors in a :not()

input:not([type='checkbox'],[type='submit'])

Legacy support

All modern browsers support the CSS3 syntax. At the time this question was asked, we needed a fall-back for IE7 and IE8. One option was to use a polyfill like IE9.js. Another was to exploit the cascade in CSS:

input {
   // styles for most inputs
}   

input[type=checkbox] {
  // revert back to the original style
} 

input.checkbox {
  // for completeness, this would have worked even in IE3!
} 

How to get the current location latitude and longitude in android

Before couple of months, I created GPSTracker library to help me to get GPS locations. In case you need to view GPSTracker > getLocation

Demo

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Activity

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView textview;

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

        // check if GPS enabled
        GPSTracker gpsTracker = new GPSTracker(this);

        if (gpsTracker.getIsGPSTrackingEnabled())
        {
            String stringLatitude = String.valueOf(gpsTracker.latitude);
            textview = (TextView)findViewById(R.id.fieldLatitude);
            textview.setText(stringLatitude);

            String stringLongitude = String.valueOf(gpsTracker.longitude);
            textview = (TextView)findViewById(R.id.fieldLongitude);
            textview.setText(stringLongitude);

            String country = gpsTracker.getCountryName(this);
            textview = (TextView)findViewById(R.id.fieldCountry);
            textview.setText(country);

            String city = gpsTracker.getLocality(this);
            textview = (TextView)findViewById(R.id.fieldCity);
            textview.setText(city);

            String postalCode = gpsTracker.getPostalCode(this);
            textview = (TextView)findViewById(R.id.fieldPostalCode);
            textview.setText(postalCode);

            String addressLine = gpsTracker.getAddressLine(this);
            textview = (TextView)findViewById(R.id.fieldAddressLine);
            textview.setText(addressLine);
        }
        else
        {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gpsTracker.showSettingsAlert();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.varna_lab_geo_locations, menu);
        return true;
    }
}

GPS Tracker

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

/**
 * Create this Class from tutorial : 
 * http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
 * 
 * For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
 * 
 */

public class GPSTracker extends Service implements LocationListener {

    // Get Class Name
    private static String TAG = GPSTracker.class.getName();

    private final Context mContext;

    // flag for GPS Status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS Tracking is enabled 
    boolean isGPSTrackingEnabled = false;

    Location location;
    double latitude;
    double longitude;

    // How many Geocoder should return our GPSTracker
    int geocoderMaxResults = 1;

    // The minimum distance to change updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    // Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
    private String provider_info;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    /**
     * Try to get my current location by GPS or Network Provider
     */
    public void getLocation() {

        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            //getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            //getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            // Try to get location if you GPS Service is enabled
            if (isGPSEnabled) {
                this.isGPSTrackingEnabled = true;

                Log.d(TAG, "Application use GPS Service");

                /*
                 * This provider determines location using
                 * satellites. Depending on conditions, this provider may take a while to return
                 * a location fix.
                 */

                provider_info = LocationManager.GPS_PROVIDER;

            } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
                this.isGPSTrackingEnabled = true;

                Log.d(TAG, "Application use Network State to get GPS coordinates");

                /*
                 * This provider determines location based on
                 * availability of cell tower and WiFi access points. Results are retrieved
                 * by means of a network lookup.
                 */
                provider_info = LocationManager.NETWORK_PROVIDER;

            } 

            // Application can use GPS or Network Provider
            if (!provider_info.isEmpty()) {
                locationManager.requestLocationUpdates(
                    provider_info,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, 
                    this
                );

                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(provider_info);
                    updateGPSCoordinates();
                }
            }
        }
        catch (Exception e)
        {
            //e.printStackTrace();
            Log.e(TAG, "Impossible to connect to LocationManager", e);
        }
    }

    /**
     * Update GPSTracker latitude and longitude
     */
    public void updateGPSCoordinates() {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }

    /**
     * GPSTracker latitude getter and setter
     * @return latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        return latitude;
    }

    /**
     * GPSTracker longitude getter and setter
     * @return
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        return longitude;
    }

    /**
     * GPSTracker isGPSTrackingEnabled getter.
     * Check GPS/wifi is enabled
     */
    public boolean getIsGPSTrackingEnabled() {

        return this.isGPSTrackingEnabled;
    }

    /**
     * Stop using GPS listener
     * Calling this method will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to show settings alert dialog
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        //Setting Dialog Title
        alertDialog.setTitle(R.string.GPSAlertDialogTitle);

        //Setting Dialog Message
        alertDialog.setMessage(R.string.GPSAlertDialogMessage);

        //On Pressing Setting button
        alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) 
            {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        //On pressing cancel button
        alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) 
            {
                dialog.cancel();
            }
        });

        alertDialog.show();
    }

    /**
     * Get list of address by latitude and longitude
     * @return null or List<Address>
     */
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses 
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    /**
     * Try to get AddressLine
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    /**
     * Try to get Locality
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else {
            return null;
        }
    }

    /**
     * Try to get Postal Code
     * @return null or postalCode
     */
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;
        }
    }

    /**
     * Try to get CountryName
     * @return null or postalCode
     */
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;
        }
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Note

If the method / answer doesn't work. You need to use the official Google Provider: FusedLocationProviderApi.

Article: Getting the Last Known Location

How to configure WAMP (localhost) to send email using Gmail?

It's quite simple. (Adapt syntax for your convenience)

public $smtp = array(
    'transport' => 'Smtp',
    'from' => '[email protected]',
    'host' => 'ssl://smtp.gmail.com',
    'port' => 465,
    'timeout' => 30,
    'username' => '[email protected]',
    'password' => '*****'
)

Add php variable inside echo statement as href link address?

you can either use

echo '<a href="'.$link_address.'">Link</a>';

or

echo "<a href=\"$link_address\">Link</a>';

if you use double quotes you can insert the variable into the string and it will be parsed.

Why is php not running?

Check out the apache config files. For Debian/Ubuntu theyre in /etc/apache2/sites-available/ for RedHat/CentOS/etc they're in /etc/httpd/conf.d/. If you've just installed it, the file in there is probably named default.

Make sure that the config file in there is pointing to the correct folder and then make sure your scripts are located there.

The line you're looking for in those files is DocumentRoot /path/to/directory.

For a blank install, your php files most likely needs to be in /var/www/.

What you'll also need to do is find your php.ini file, probably located at /etc/php5/apache2/php.ini or /etc/php.ini and find the entry for display_errors and switch it to On.

Laravel 5 – Remove Public from URL

You can remove public keyword from url using various methods.

1) If you are using dedicated hosting and you have root access then You can remove public keyword from url using Virtual Host. You should give DocumentRoot path with public. So this will start index from public directory and remove it from url.

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/html/{yoursourcedirectory}/public

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

2) If you dont have root access of your hosting then you should genarate a new .htaccess file in your root directory and put the code as below

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1 

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
</IfModule>

You can get more reference here.

Jquery UI Datepicker not displaying

it's the css file in the new one doesn't work. Try to include the old 1.7.* css file on your header too, and try again.

Also, did you try to do a .datepicker( "show" ) right after it constructed?

__init__() got an unexpected keyword argument 'user'

You can't do

LivingRoom.objects.create(user=instance)

because you have an __init__ method that does NOT take user as argument.

You need something like

#signal function: if a user is created, add control livingroom to the user    
def create_control_livingroom(sender, instance, created, **kwargs):
    if created:
        my_room = LivingRoom()
        my_room.user = instance

Update

But, as bruno has already said it, Django's models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields.

So, following better principles, you should probably have something like

class LivingRoom(models.Model):
    '''Living Room object'''
    user = models.OneToOneField(User)

    def __init__(self, *args, temp=65, **kwargs):
        self.temp = temp
        return super().__init__(*args, **kwargs)

Note - If you weren't using temp as a keyword argument, e.g. LivingRoom(65), then you'll have to start doing that. LivingRoom(user=instance, temp=66) or if you want the default (65), simply LivingRoom(user=instance) would do.

What is a file with extension .a?

.a files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.

Java/Groovy - simple date reformatting

With Groovy, you don't need the includes, and can just do:

String oldDate = '04-DEC-2012'
Date date = Date.parse( 'dd-MMM-yyyy', oldDate )
String newDate = date.format( 'M-d-yyyy' )

println newDate

To print:

12-4-2012

ActiveXObject creation error " Automation server can't create object"

This is caused by Security settings for internet explorer. You can fix this,by changing internet explorer settings.Go To Settings->Internet Options->Security Tabs. You will see different zones:i)Internet ii)Local Intranet iii)Trusted Sites iv)Restricted Sites. Depending on your requirement select one zone. I am running my application in localhost so i selected Local intranet and then click Custom Level button. It opens security settings window. Please enable Initialize and script Activex controls not marked as safe for scripting option.It should work.

enter image description here

enter image description here

getting integer values from textfield

You need to use Integer.parseInt(String)

private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
        if(evt.getSource()==jTextField2){
            int jml = Integer.parseInt(jTextField3.getText());
            jTextField1.setText(numberToWord(jml));

        }
    }

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

What is the difference between float and double?

Huge difference.

As the name implies, a double has 2x the precision of float[1]. In general a double has 15 decimal digits of precision, while float has 7.

Here's how the number of digits are calculated:

double has 52 mantissa bits + 1 hidden bit: log(253)÷log(10) = 15.95 digits

float has 23 mantissa bits + 1 hidden bit: log(224)÷log(10) = 7.22 digits

This precision loss could lead to greater truncation errors being accumulated when repeated calculations are done, e.g.

float a = 1.f / 81;
float b = 0;
for (int i = 0; i < 729; ++ i)
    b += a;
printf("%.7g\n", b); // prints 9.000023

while

double a = 1.0 / 81;
double b = 0;
for (int i = 0; i < 729; ++ i)
    b += a;
printf("%.15g\n", b); // prints 8.99999999999996

Also, the maximum value of float is about 3e38, but double is about 1.7e308, so using float can hit "infinity" (i.e. a special floating-point number) much more easily than double for something simple, e.g. computing the factorial of 60.

During testing, maybe a few test cases contain these huge numbers, which may cause your programs to fail if you use floats.


Of course, sometimes, even double isn't accurate enough, hence we sometimes have long double[1] (the above example gives 9.000000000000000066 on Mac), but all floating point types suffer from round-off errors, so if precision is very important (e.g. money processing) you should use int or a fraction class.


Furthermore, don't use += to sum lots of floating point numbers, as the errors accumulate quickly. If you're using Python, use fsum. Otherwise, try to implement the Kahan summation algorithm.


[1]: The C and C++ standards do not specify the representation of float, double and long double. It is possible that all three are implemented as IEEE double-precision. Nevertheless, for most architectures (gcc, MSVC; x86, x64, ARM) float is indeed a IEEE single-precision floating point number (binary32), and double is a IEEE double-precision floating point number (binary64).

Changing the resolution of a VNC session in linux

I'm running TigerVNC on my Linux server, which has basic randr support. I just start vncserver without any -randr or multiple -geometry options.

When I run xrandr in a terminal, it displays all the available screen resolutions:

bash> xrandr
 SZ:    Pixels          Physical       Refresh
 0   1920 x 1200   ( 271mm x 203mm )   60
 1   1920 x 1080   ( 271mm x 203mm )   60
 2   1600 x 1200   ( 271mm x 203mm )   60
 3   1680 x 1050   ( 271mm x 203mm )   60
 4   1400 x 1050   ( 271mm x 203mm )   60
 5   1360 x 768    ( 271mm x 203mm )   60
 6   1280 x 1024   ( 271mm x 203mm )   60
 7   1280 x 960    ( 271mm x 203mm )   60
 8   1280 x 800    ( 271mm x 203mm )   60
 9   1280 x 720    ( 271mm x 203mm )   60
*10  1024 x 768    ( 271mm x 203mm )  *60
 11   800 x 600    ( 271mm x 203mm )   60
 12   640 x 480    ( 271mm x 203mm )   60
Current rotation - normal
Current reflection - none
Rotations possible - normal
Reflections possible - none

I can then easily switch to another resolution (f.e. switch to 1360x768):

bash> xrandr -s 5

I'm using TightVnc viewer as the client and it automatically adapts to the new resolution.

How does one convert a grayscale image to RGB in OpenCV (Python)?

One you convert your image to gray-scale you cannot got back. You have gone from three channel to one, when you try to go back all three numbers will be the same. So the short answer is no you cannot go back. The reason your backtorgb function this throwing that error is because it needs to be in the format:

CvtColor(input, output, CV_GRAY2BGR)

OpenCV use BGR not RGB, so if you fix the ordering it should work, though your image will still be gray.

How to go to a specific element on page?

here is a simple javascript for that

call this when you need to scroll the screen to an element which has id="yourSpecificElementId"

window.scroll(0,findPos(document.getElementById("yourSpecificElementId")));

and you need this function for the working:

//Finds y value of given object
function findPos(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    return [curtop];
    }
}

the screen will be scrolled to your specific element.

Binding a Button's visibility to a bool value in ViewModel

Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.

I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:

<ValueConversion(GetType(Boolean), GetType(Visibility))> _
Public Class BoolToVisibilityConverter
    Implements IValueConverter

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert

        If value IsNot Nothing Then
            If value = True Then 
                Return Visibility.Visible
            Else
                Return Visibility.Collapsed
            End If
        Else
            Return Visibility.Collapsed
        End If
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException
    End Function
End Class

A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.

matplotlib savefig in jpeg format

Just install pillow with pip install pillow and it will work.

Javascript search inside a JSON object

Use PaulGuo's jSQL, a SQL like database using javascript. For example:

var db = new jSQL();
db.create('dbname', testListData).use('dbname');
var data = db.select('*').where(function(o) {
    return o.name == 'Jacking';
}).listAll();

How to draw a line with matplotlib?

As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2)).

Ternary operator in PowerShell

I've recently improved (open PullRequest) the ternary conditional and null-coalescing operators in the PoweShell lib 'Pscx'
Pls have a look for my solution.


My github topic branch: UtilityModule_Invoke-Operators

Functions:

Invoke-Ternary
Invoke-TernaryAsPipe
Invoke-NullCoalescing
NullCoalescingAsPipe

Aliases

Set-Alias :?:   Pscx\Invoke-Ternary                     -Description "PSCX alias"
Set-Alias ?:    Pscx\Invoke-TernaryAsPipe               -Description "PSCX alias"
Set-Alias :??   Pscx\Invoke-NullCoalescing              -Description "PSCX alias"
Set-Alias ??    Pscx\Invoke-NullCoalescingAsPipe        -Description "PSCX alias"

Usage

<condition_expression> |?: <true_expression> <false_expression>

<variable_expression> |?? <alternate_expression>

As expression you can pass:
$null, a literal, a variable, an 'external' expression ($b -eq 4) or a scriptblock {$b -eq 4}

If a variable in the variable expression is $null or not existing, the alternate expression is evaluated as output.

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

Well actually your only need $.each to get all values, it will help you jsfiddle.net/NdQbw/5

<div class="divright">
            <select id="drp_Books_Ill_Illustrations" class="leaderMultiSelctdropdown Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
                <option value=" ">No illustrations</option>
                <option value="a" selected>Illustrations</option>
                <option value="b">Maps</option>
                <option value="c" selected>selectedPortraits</option>
            </select>
    </div>

<div class="divright">
        <select id="drp_Books_Ill_Illustrations1" class=" Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
            <option value=" ">No illustrations</option>
            <option value="a">Illustrations</option>
            <option value="b">Maps</option>
            <option value="c">selectedPortraits</option>
        </select>
</div>

<button class="getValue">Get Value</button>
<button  class="setValue"> Set  value </button>

<div class="divright">
        <select id="drp_Books_Ill_Illustrations2" class="leaderMultiSelctdropdown Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
            <option value=" ">No illustrations</option>
            <option value="a" selected>Illustrations</option>
            <option value="b">Maps</option>
            <option value="c" selected>selectedPortraits</option>
        </select>
</div>

<div class="divright">
        <select id="drp_Books_Ill_Illustrations3" class=" Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
            <option value=" ">No illustrations</option>
            <option value="a">Illustrations</option>
            <option value="b">Maps</option>
            <option value="c">selectedPortraits</option>
        </select>
</div>

<button class="getValue1">Get Value</button>
<button  class="setValue1"> Set  value </button>

The script:

 var selectedValues = new Array();
    selectedValues[0] = "a";
    selectedValues[1] = "c";

$(".getValue").click(function() {
    alert($(".leaderMultiSelctdropdown").val());
});
$(".setValue").click(function() {
   $(".Books_Illustrations").val(selectedValues);
});

$('#drp_Books_Ill_Illustrations2, #drp_Books_Ill_Illustrations3').select2();


$(".getValue1").click(function() {
    alert($(".leaderMultiSelctdropdown").val());
});

$(".setValue1").click(function() {
    //You need a id for set values
    $.each($(".Books_Illustrations"), function(){
            $(this).select2('val', selectedValues);
    });
});

How to delete a file from SD card?

Recursively delete all children of the file ...

public static void DeleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()) {
        for (File child : fileOrDirectory.listFiles()) {
            DeleteRecursive(child);
        }
    }

    fileOrDirectory.delete();
}

How to set a dropdownlist item as selected in ASP.NET?

Set dropdown property

selected="true"

How to replace innerHTML of a div using jQuery?

jQuery has few functions which work with text, if you use text() one, it will do the job for you:

$("#regTitle").text("Hello World");

Also, you can use html() instead, if you have any html tag...

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

Setting Remote Webdriver to run tests in a remote computer using Java

This is how I got rid of the error:

WebDriverException: Error forwarding the new session cannot find : {platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=11}

In your nodeconfig.json, the version must be a String, not an integer.

So instead of using "version": 11 use "version": "11" (note the double quotes).

A full example of a working nodecondig.json file for a RemoteWebDriver:

{
  "capabilities":
  [
    {
      "platform": "WIN8_1",
      "browserName": "internet explorer",
      "maxInstances": 1,
      "seleniumProtocol": "WebDriver"
      "version": "11"
    }
    ,{
      "platform": "WIN7",
      "browserName": "chrome",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "40"
    }
    ,{
      "platform": "LINUX",
      "browserName": "firefox",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "33"
    }
  ],
  "configuration":
  {
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 3,
    "port": 5555,
    "host": ip,
    "register": true,
    "registerCycle": 5000,
    "hubPort": 4444,
    "hubHost": {your-ip-address}
  }
}

Biggest differences of Thrift vs Protocol Buffers?

It's also important to note that not all supported languages compair consistently with thrift or protobuf. At this point it's a matter of the modules implementation in addition to the underlying serialization. Take care to check benchmarks for whatever language you plan to use.

PHP 7 simpleXML

Typically on Debian systems you have different PHP configuration for CLI and for PHP running as say an Apache module. Your phpinfo page may very well show simplexml as being enabled via web server, while it is not enabled via CLI.

Pod install is staying on "Setting up CocoaPods Master repo"

pod setup --verbose 

I am running the above mentioned command right now but as mentioned by @Joe Blow, it shows absolutely no information on the progress.

But if you open the Activity Monitor on Mac (Task Manager on Windows?), under the 'Network' tab you will see a process named 'git-remote-https' and it shows the size of 'Received Bytes' increasing. After downloading about 300MB it stopped and then I could see further progress in the Terminal window.

Android EditText for password with android:hint

Here is your answer. We can use both simultaniously. As i used both and they are working fine. The code is as follows:

<EditText
    android:id="@+id/edittext_password_la"
    android:layout_below="@+id/edittext_username_la"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="15dip"
    android:inputType="textPassword"
    android:hint="@string/string_password" />

This will help you.

localhost refused to connect Error in visual studio

None of these solutions worked for me. I'm not 100%, but I think my issue might have been with running the same project on the same port from multiple branches. That used to be an issue for me on Local IIS --- I'm not sure if that's also an issue on IIS Express. What worked for me was following this solution:

https://stackoverflow.com/a/27033934/2133723

Which says to go to:

File -> Open -> Web Site...

and remove the relevant projects. After this, I was able to run the project without changing the port.

Prior to doing this, I had followed the other solutions posted on this question (which didn't help me), such as deleting the .vs folder, so I'm not sure if that would be a necessary step prior to removing the website from File -> Open -> Web Site....

Extract matrix column values by matrix column name

> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")

> myMatrix
  A B C D  E
A 1 3 5 7  9
B 2 4 6 8 10

> myMatrix["A", "A"]
[1] 1

> myMatrix["A", ]
A B C D E 
1 3 5 7 9 

> myMatrix[, "A"]
A B 
1 2 

How do I iterate over the words of a string?

Here is my version

#include <vector>

inline std::vector<std::string> Split(const std::string &str, const std::string &delim = " ")
{
    std::vector<std::string> tokens;
    if (str.size() > 0)
    {
        if (delim.size() > 0)
        {
            std::string::size_type currPos = 0, prevPos = 0;
            while ((currPos = str.find(delim, prevPos)) != std::string::npos)
            {
                std::string item = str.substr(prevPos, currPos - prevPos);
                if (item.size() > 0)
                {
                    tokens.push_back(item);
                }
                prevPos = currPos + 1;
            }
            tokens.push_back(str.substr(prevPos));
        }
        else
        {
            tokens.push_back(str);
        }
    }
    return tokens;
}

It works with multi-character delimiters. It prevents empty tokens to get in your results. It uses a single header. It returns the string as one single token when you provide no delimiter. It also returns an empty result if the string is empty. It is unfortunately inefficient because of the huge std::vector copy UNLESS you are compiling using C++11, which should be using the move schematic. In C++11, this code should be fast.

Get value of c# dynamic property via string

The GetProperty/GetValue does not work for Json data, it always generate a null exception, however, you may try this approach:

Serialize your object using JsonConvert:

var z = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(request));

Then access it directly casting it back to string:

var pn = (string)z["DynamicFieldName"];

It may work straight applying the Convert.ToString(request)["DynamicFieldName"], however I haven't tested.

How to use paginator from material angular?

Another way to link Angular Paginator with the data table using Slice Pipe.Here data is fetched only once from server.

View:

 <div class="col-md-3" *ngFor="let productObj of productListData | 
     slice: lowValue : highValue">
       //actual data dispaly  
 </div>

<mat-paginator [length]="productListData.length" [pageSize]="pageSize" 
   (page)="pageEvent = getPaginatorData($event)">
</mat-paginator> 

Component

    pageIndex:number = 0;
    pageSize:number = 50;
    lowValue:number = 0;
    highValue:number = 50;       

  getPaginatorData(event){
     console.log(event);
     if(event.pageIndex === this.pageIndex + 1){
        this.lowValue = this.lowValue + this.pageSize;
        this.highValue =  this.highValue + this.pageSize;
       }
    else if(event.pageIndex === this.pageIndex - 1){
       this.lowValue = this.lowValue - this.pageSize;
       this.highValue =  this.highValue - this.pageSize;
      }   
       this.pageIndex = event.pageIndex;
 }

How to get an input text value in JavaScript

Do not use global variables in this way. Even if this could work, it's bad programming style. You can inadvertently overwrite important data in this way. Do this instead:

<script type="text/javascript">
   function kk(){
       var lol = document.getElementById('lolz').value;
       alert(lol);
   }
</script>

If you insist var lol to be set outside the function kk, then I propose this solution:

<body>
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" OnClick="kk()"/>
    <script type="text/javascript">
       var lol = document.getElementById('lolz');
       function kk() {
           alert(lol.value);
       }
    </script>
</body>

Note that the script element must follow the input element it refers to, because elements are only queryable with getElementById if they already have been parsed and created.

Both examples work, tested in jsfiddler.

Edit: I removed the language="javascript" attribute, because it's deprecated. See W3 HTML4 Specification, the SCRIPT element:

language = cdata [CI]

Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.

and

A deprecated element or attribute is one that has been outdated by newer constructs. […] Deprecated elements may become obsolete in future versions of HTML. […] This specification includes examples that illustrate how to avoid using deprecated elements. […]

htaccess redirect to https://www

If you are using CloudFlare or a similar CDN you will get an infinite loop error with the %{HTTPS} solutions provided here. If you're a CloudFlare user you'll need to use this:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

placeholder for select tag

<select>
   <option disabled selected>select your beverage</option>
   <option >Tea</option>
   <option>coffee</option>
   <option>soda</option>
</select>

Returning multiple objects in an R function

Similarly in Java, you can create a S4 class in R that encapsulates your information:

setClass(Class="Person",
         representation(
            height="numeric",
            age="numeric"
          )
)

Then your function can return an instance of this class:

myFunction = function(age=28, height=176){
  return(new("Person",
          age=age,
          height=height))
}

and you can access your information:

aPerson = myFunction()

aPerson@age
aPerson@height

CSS to stop text wrapping under image

Since this question is gaining lots of views and this was the accepted answer, I felt the need to add the following disclaimer:

This answer was specific to the OP's question (Which had the width set in the examples). While it works, it requires you to have a width on each of the elements, the image and the paragraph. Unless that is your requirement, I recommend using Joe Conlin's solution which is posted as another answer on this question.

The span element is an inline element, you can't change its width in CSS.

You can add the following CSS to your span so you will be able to change its width.

display: block;

Another way, which usually makes more sense, is to use a <p> element as a parent for your <span>.

<li id="CN2787">
  <img class="fav_star" src="images/fav.png">
  <p>
     <span>Text, text and more text</span>
  </p>
</li>

Since <p> is a block element, you can set its width using CSS, without having to change anything.

But in both cases, since you have a block element now, you will need to float the image so that your text doesn't all go below your image.

li p{width: 100px; margin-left: 20px}
.fav_star {width: 20px;float:left}

P.S. Instead of float:left on the image, you can also put float:right on li p but in that case, you will also need text-align:left to realign the text correctly.

P.S.S. If you went ahead with the first solution of not adding a <p> element, your CSS should look like so:

li span{width: 100px; margin-left: 20px;display:block}
.fav_star {width: 20px;float:left}

SyntaxError: unexpected EOF while parsing

elec_and_weather['DEMAND_t-%i'% k] = np.zeros(len(elec_and_weather['DEMAND']))'

The error comes at the end of the line where you have the (') sign; this error always means that you have a syntax error.

Plot a horizontal line using matplotlib

If you want to draw a horizontal line in the axes, you might also try ax.hlines() method. You need to specify y position and xmin and xmax in the data coordinate (i.e, your actual data range in the x-axis). A sample code snippet is:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1, 21, 200)
y = np.exp(-x)

fig, ax = plt.subplots()
ax.plot(x, y)
ax.hlines(y=0.2, xmin=4, xmax=20, linewidth=2, color='r')

plt.show()

The snippet above will plot a horizontal line in the axes at y=0.2. The horizontal line starts at x=4 and ends at x=20. The generated image is:

enter image description here

What is the string length of a GUID?

22 bytes, if you do it like this:

System.Guid guid = System.Guid.NewGuid();
byte[] guidbytes = guid.ToByteArray();
string uuid = Convert.ToBase64String(guidbytes).Trim('=');

When to use async false and async true in ajax function in jquery

It's not relative to performance...

You set async to false, when you need that ajax request to be completed before the browser passes to other codes:

<script>
    // ...
    $.ajax(... async: false ...); // Hey browser! first complete this request, 
                                  // then go for other codes

    $.ajax(...); // Executed after the completion of the previous async:false request.
</script>

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

All I had to do was run:

sudo apt-get install libfontconfig1

I was in the folder located at /usr/lib/x86_64-linux-gnu and it worked perfectly.

What is the best way to implement nested dictionaries?

This is a function that returns a nested dictionary of arbitrary depth:

from collections import defaultdict
def make_dict():
    return defaultdict(make_dict)

Use it like this:

d=defaultdict(make_dict)
d["food"]["meat"]="beef"
d["food"]["veggie"]="corn"
d["food"]["sweets"]="ice cream"
d["animal"]["pet"]["dog"]="collie"
d["animal"]["pet"]["cat"]="tabby"
d["animal"]["farm animal"]="chicken"

Iterate through everything with something like this:

def iter_all(d,depth=1):
    for k,v in d.iteritems():
        print "-"*depth,k
        if type(v) is defaultdict:
            iter_all(v,depth+1)
        else:
            print "-"*(depth+1),v

iter_all(d)

This prints out:

- food
-- sweets
--- ice cream
-- meat
--- beef
-- veggie
--- corn
- animal
-- pet
--- dog
---- labrador
--- cat
---- tabby
-- farm animal
--- chicken

You might eventually want to make it so that new items can not be added to the dict. It's easy to recursively convert all these defaultdicts to normal dicts.

def dictify(d):
    for k,v in d.iteritems():
        if isinstance(v,defaultdict):
            d[k] = dictify(v)
    return dict(d)

Getting a directory name from a filename

 auto p = boost::filesystem::path("test/folder/file.txt");
 std::cout << p.parent_path() << '\n';             // test/folder
 std::cout << p.parent_path().filename() << '\n';  // folder
 std::cout << p.filename() << '\n';                // file.txt

You may need p.parent_path().filename() to get name of parent folder.

Using node.js as a simple web server

The fast way:

var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/../public')); // ? adjust
app.listen(3000, function() { console.log('listening'); });

Your way:

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
    console.dir(req.url);

    // will get you  '/' or 'index.html' or 'css/styles.css' ...
    // • you need to isolate extension
    // • have a small mimetype lookup array/object
    // • only there and then reading the file
    // •  delivering it after setting the right content type

    res.writeHead(200, {'Content-Type': 'text/html'});

    res.end('ok');
}).listen(3001);

Echo tab characters in bash script

Put your string between double quotes:

echo "[$res]"

Connecting PostgreSQL 9.2.1 with Hibernate

If the project is maven placed it in src/main/resources, in the package phase it will copy it in ../WEB-INF/classes/hibernate.cfg.xml

Anaconda vs. miniconda

Per the original docs:

Choose Anaconda if you:

  • Are new to conda or Python
  • Like the convenience of having Python and over 1500 scientific packages automatically installed at once
  • Have the time and disk space (a few minutes and 3 GB), and/or
  • Don’t want to install each of the packages you want to use individually.

Choose Miniconda if you:

  • Do not mind installing each of the packages you want to use individually.
  • Do not have time or disk space to install over 1500 packages at once, and/or
  • Just want fast access to Python and the conda commands, and wish to sort out the other programs later.

I use Miniconda myself. Anaconda is bloated. Many of the packages are never used and could still be easily installed if and when needed.

Note that Conda is the package manager (e.g. conda list displays all installed packages in the environment), whereas Anaconda and Miniconda are distributions. A software distribution is a collection of packages, pre-built and pre-configured, that can be installed and used on a system. A package manager is a tool that automates the process of installing, updating, and removing packages.

Anaconda is a full distribution of the central software in the PyData ecosystem, and includes Python itself along with the binaries for several hundred third-party open-source projects. Miniconda is essentially an installer for an empty conda environment, containing only Conda, its dependencies, and Python. Source.

Once Conda is installed, you can then install whatever package you need from scratch along with any desired version of Python.

2-4.4.0.1 is the version number for your Anaconda installation package. Strangely, it is not listed in their Old Package Lists.

In April 2016, the Anaconda versioning jumped from 2.5 to 4.0 in order to avoid confusion with Python versions 2 & 3. Version 4.0 included the Anaconda Navigator.

Release notes for subsequent versions can be found here.

How to create a readonly textbox in ASP.NET MVC3 Razor

The solution with TextBoxFor is OK, but if you don't want to see the field like EditBox stylish (it might be a little confusing for the user) involve changes as follows:

  1. Razor code before changes

    <div class="editor-field">
         @Html.EditorFor(model => model.Text)
         @Html.ValidationMessageFor(model => model.Text)
    </div>
    
  2. After changes

    <!-- New div display-field (after div editor-label) -->
    <div class="display-field">
        @Html.DisplayFor(model => model.Text)
    </div>
    
    <div class="editor-field">
        <!-- change to HiddenFor in existing div editor-field -->
        @Html.HiddenFor(model => model.Text)
        @Html.ValidationMessageFor(model => model.Text)
    </div>
    

Generally, this solution prevents field from editing, but shows value of it. There is no need for code-behind modifications.

Programmatically set the initial view controller using Storyboards

If you prefer not to change applicationDidFinish, you can do the following trick:

Set Navigation controller as an initial view controller and assign to it a custom class 'MyNavigationController'. Then you can tweak its root view controller during viewDidLoad - it will override the root view controller that you set in your storyboard.

class MyNavigationController: UINavigationController {
    override func viewDidLoad() {
        super.viewDidLoad()
        if !isLoggedIn() {
            viewControllers = [R.storyboard.authentication.loginView()!]
        }
    }

    private func isLoggedIn() -> Bool {
        return false
    }

}

How to find SQL Server running port?

very simple. make a note of the sqlsrvr.exe PID from taskmanager then run this command:

netstat -ano | findstr *PID*

it will show TCP and UDP connections of your SQL server (including ports) standard is 1433 for TCP and 1434 for UDP

example : enter image description here

CSV in Python adding an extra carriage return, on Windows

You can introduce the lineterminator='\n' parameter in the csv writer command.

import csv
delimiter='\t'
with open('tmp.csv', '+w', encoding='utf-8') as stream:
    writer = csv.writer(stream, delimiter=delimiter, quoting=csv.QUOTE_NONE, quotechar='',  lineterminator='\n')
    writer.writerow(['A1' , 'B1', 'C1'])
    writer.writerow(['A2' , 'B2', 'C2'])
    writer.writerow(['A3' , 'B3', 'C3'])

Fatal error: Call to a member function prepare() on null

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e ); line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

How can I remove a specific item from an array?

You can do it easily with the filter method:

_x000D_
_x000D_
function remove(arrOriginal, elementToRemove){
    return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));
_x000D_
_x000D_
_x000D_

This removes all elements from the array and also works faster than a combination of slice and indexOf.

How to handle login pop up window using Selenium WebDriver?

I was getting windows security alert whenever my application was opening. to resolve this issue i used following procedure

import org.openqa.selenium.security.UserAndPassword;
UserAndPassword UP = new UserAndPassword("userName","Password");
driver.switchTo().alert().authenticateUsing(UP);

this resolved my issue of logging into application. I hope this might help who are all looking for authenticating windows security alert.

How to examine processes in OS X's Terminal?

Try the top command. It's an interactive command that will display the running processes.

You may also use the Apple's "Activity Monitor" application (located in /Applications/Utilities/).

It provides an actually quite nice GUI. You can see all the running processes, filter them by users, get extended informations about them (CPU, memory, network, etc), monitor them, etc...

Probably your best choice, unless you want to stick with the terminal (in such a case, read the top or ps manual, as those commands have a bunch of options).

Syntax for creating a two-dimensional array in Java

Actually Java doesn't have multi-dimensional array in mathematical sense. What Java has is just array of arrays, an array where each element is also an array. That is why the absolute requirement to initialize it is the size of the first dimension. If the rest are specified then it will create an array populated with default value.

int[][]   ar  = new int[2][];
int[][][] ar  = new int[2][][];
int[][]   ar  = new int[2][2]; // 2x2 array with zeros

It also gives us a quirk. The size of the sub-array cannot be changed by adding more elements, but we can do so by assigning a new array of arbitrary size.

int[][]   ar  = new int[2][2];
ar[1][3] = 10; // index out of bound
ar[1]    = new int[] {1,2,3,4,5,6}; // works

What is the difference between function and procedure in PL/SQL?

The following are the major differences between procedure and function,

  1. Procedure is named PL/SQL block which performs one or more tasks. where function is named PL/SQL block which performs a specific action.
  2. Procedure may or may not return value where as function should return one value.
  3. we can call functions in select statement where as procedure we cant.

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

UILabel with text of two different colors

In my case I'm using Xcode 10.1. There is a option of switching between plain text and Attributed text in Label text in Interface Builder

enter image description here

Hope this may help someone else..!

What is the difference between Python's list methods append and extend?

This is the equivalent of append and extend using the + operator:

>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> x = x + [4,5,6] # Extend
>>> x
[1, 2, 3, 4, 5, 6]
>>> x = x + [[7,8]] # Append
>>> x
[1, 2, 3, 4, 5, 6, [7, 8]]

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

If you are to use the Codeigniter framework then just make this into config file:

$config['compress_output'] = FALSE;

And in php.ini configuration file, use:

zlib.output_compression=On

How to do paging in AngularJS?

I recently implemented paging for the Built with Angular site. You chan checkout the source: https://github.com/angular/builtwith.angularjs.org

I'd avoid using a filter to separate the pages. You should break up the items into pages within the controller.

How to make a button redirect to another page using jQuery or just Javascript

this is the FASTEST (most readable, least complicated) way to do it, Owens works but it's not legal HTML, technically this answer is not jQuery (but since jQuery is a pre-prepared pseudocode - reinterpreted on the client platform as native JavaScript - there really is no such thing as jQuery anyway)

 <button onclick="window.location.href='http://www.google.com';">Google</button>

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

In addition to the locations listed above, the OS X version of Perl also has two more ways:

  1. The /Library/Perl/x.xx/AppendToPath file. Paths listed in this file are appended to @INC at runtime.

  2. The /Library/Perl/x.xx/PrependToPath file. Paths listed in this file are prepended to @INC at runtime.

Replace transparency in PNG images with white background

This works for me:

convert -flatten img1.png img1-white.png

Documentation references:

What are the benefits to marking a field as `readonly` in C#?

Be careful with private readonly arrays. If these are exposed a client as an object (you might do this for COM interop as I did) the client can manipulate array values. Use the Clone() method when returning an array as an object.

How does Google reCAPTCHA v2 work behind the scenes?

A new paper has been released with several tests against reCAPTCHA:

https://www.blackhat.com/docs/asia-16/materials/asia-16-Sivakorn-Im-Not-a-Human-Breaking-the-Google-reCAPTCHA-wp.pdf

Some highlights:

  • By keeping a cookie active for +9 days (by browsing sites with Google resources), you can then pass reCAPTCHA by only clicking the checkbox;
  • There are no restrictions based on requests per IP;
  • The browser's user agent must be real, and Google run tests against your environment to ensure it matches the user agent;
  • Google tests if the browser can render a Canvas;
  • Screen resolution and mouse events don't affect the results;

Google has already fixed the cookie vulnerability and is probably restricting some behaviors based on IPs.

Another interesting finding is that Google runs a VM in JavaScript that obfuscates much of reCAPTCHA code and behavior. This VM is known as botguard and is used to protect other services besides reCAPTCHA:

https://github.com/neuroradiology/InsideReCaptcha

UPDATE 2017

A recent paper (from August) was published on WOOT 2017 achieving 85% accuracy in solving noCAPTCHA reCAPTCHA audio challenges:

http://uncaptcha.cs.umd.edu/papers/uncaptcha_woot17.pdf

UPDATE 2018

Google is introducing reCAPTCHA v3, which looks like a "human score prediction engine" that is calibrated per website. It can be installed into different pages of a website (working like a Google Analytics script) to help reCAPTCHA and the website owner to understand the behaviour of humans vs. bots before filling a reCAPTCHA.

https://www.google.com/recaptcha/intro/v3beta.html

How to set header and options in axios?

There are several ways to do this:

  • For a single request:

    let config = {
      headers: {
        header1: value,
      }
    }
    
    let data = {
      'HTTP_CONTENT_LANGUAGE': self.language
    }
    
    axios.post(URL, data, config).then(...)
    
  • For setting default global config:

    axios.defaults.headers.post['header1'] = 'value' // for POST requests
    axios.defaults.headers.common['header1'] = 'value' // for all requests
    
  • For setting as default on axios instance:

    let instance = axios.create({
      headers: {
        post: {        // can be common or any other method
          header1: 'value1'
        }
      }
    })
    
    //- or after instance has been created
    instance.defaults.headers.post['header1'] = 'value'
    
    //- or before a request is made
    // using Interceptors
    instance.interceptors.request.use(config => {
      config.headers.post['header1'] = 'value';
      return config;
    });
    

How to write a confusion matrix in Python?

Only with numpy, we can do as follow considering efficiency:

def confusion_matrix(pred, label, nc=None):
    assert pred.size == label.size
    if nc is None:
        nc = len(unique(label))
        logging.debug("Number of classes assumed to be {}".format(nc))

    confusion = np.zeros([nc, nc])
    # avoid the confusion with `0`
    tran_pred = pred + 1
    for i in xrange(nc):    # current class
        mask = (label == i)
        masked_pred = mask * tran_pred
        cls, counts = unique(masked_pred, return_counts=True)
        # discard the first item
        cls = [cl - 1 for cl in cls][1:]
        counts = counts[1:]
        for cl, count in zip(cls, counts):
            confusion[i, cl] = count
    return confusion

For other features such as plot, mean-IoU, see my repositories.

Git: "please tell me who you are" error

i use heroku cli 1. must use all user name and user email

$git config --global user.email .login email.

$git config --global user.name .heroku name.

  1. git pull [git url]
  2. git init
  3. git add *

    5 git commit -m "after config user.name ,user email"

  4. git push heroku master

How to view query error in PDO PHP

a quick way to see your errors whilst testing:

$error= $st->errorInfo();
echo $error[2];

How to cancel a Task in await?

One case which hasn't been covered is how to handle cancellation inside of an async method. Take for example a simple case where you need to upload some data to a service get it to calculate something and then return some results.

public async Task<Results> ProcessDataAsync(MyData data)
{
    var client = await GetClientAsync();
    await client.UploadDataAsync(data);
    await client.CalculateAsync();
    return await client.GetResultsAsync();
}

If you want to support cancellation then the easiest way would be to pass in a token and check if it has been cancelled between each async method call (or using ContinueWith). If they are very long running calls though you could be waiting a while to cancel. I created a little helper method to instead fail as soon as canceled.

public static class TaskExtensions
{
    public static async Task<T> WaitOrCancel<T>(this Task<T> task, CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        await Task.WhenAny(task, token.WhenCanceled());
        token.ThrowIfCancellationRequested();

        return await task;
    }

    public static Task WhenCanceled(this CancellationToken cancellationToken)
    {
        var tcs = new TaskCompletionSource<bool>();
        cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
        return tcs.Task;
    }
}

So to use it then just add .WaitOrCancel(token) to any async call:

public async Task<Results> ProcessDataAsync(MyData data, CancellationToken token)
{
    Client client;
    try
    {
        client = await GetClientAsync().WaitOrCancel(token);
        await client.UploadDataAsync(data).WaitOrCancel(token);
        await client.CalculateAsync().WaitOrCancel(token);
        return await client.GetResultsAsync().WaitOrCancel(token);
    }
    catch (OperationCanceledException)
    {
        if (client != null)
            await client.CancelAsync();
        throw;
    }
}

Note that this will not stop the Task you were waiting for and it will continue running. You'll need to use a different mechanism to stop it, such as the CancelAsync call in the example, or better yet pass in the same CancellationToken to the Task so that it can handle the cancellation eventually. Trying to abort the thread isn't recommended.

How do I call an Angular 2 pipe with multiple arguments?

I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.

Here is the Pipe being called in an *ngFor directive,

<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
  Hello {{item.first}} !
</div>

Here is the Pipe,

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
  transform(myobjects: Array<object>, args?: Array<object>): any {
    if (args && Array.isArray(myobjects)) {
      // copy all objects of original array into new array of objects
      var returnobjects = myobjects;
      // args are the compare oprators provided in the *ngFor directive
      args.forEach(function (filterobj) {
        let filterkey = Object.keys(filterobj)[0];
        let filtervalue = filterobj[filterkey];
        myobjects.forEach(function (objectToFilter) {
          if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
            // object didn't match a filter value so remove it from array via filter
            returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
          }
        })
      });
      // return new array of objects to *ngFor directive
      return returnobjects;
    }
  }
}

And here is the Component containing the object to filter,

import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  items = [{ title: "mr", first: "john", last: "jones" }
   ,{ title: "mr", first: "adrian", last: "jacobs" }
   ,{ title: "mr", first: "lou", last: "jones" }
   ,{ title: "ms", first: "linda", last: "hamilton" }
  ];
}

StackBlitz Example

GitHub Example: Fork a working copy of this example here

*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.

Happy Coding :-)

Google Maps setCenter()

 function resize() {
        var map_obj = document.getElementById("map_canvas");

      /*  map_obj.style.width = "500px";
        map_obj.style.height = "225px";*/
        if (map) {
            map.checkResize();
            map.panTo(new GLatLng(lat,lon));
        }
    }

<body onload="initialize()" onunload="GUnload()" onresize="resize()">
<div id="map_canvas" style="width: 100%; height: 100%">
</div>

Fast way of finding lines in one file that are not in another?

The way I usually do this is using the --suppress-common-lines flag, though note that this only works if your do it in side-by-side format.

diff -y --suppress-common-lines file1.txt file2.txt

How do you perform address validation?

As seen on reddit:

$address = urlencode('1600 Pennsylvania Avenue, Washington, DC');
$json = json_decode(file_get_contents("http://where.yahooapis.com/geocode?q=$address&flags=J"));
print_r($json);

LINQ Join with Multiple Conditions in On Clause

Here you go with:

from b in _dbContext.Burden 
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }

Can I fade in a background image (CSS: background-image) with jQuery?

jquery:

 $("div").fadeTo(1000 , 1);

css

    div {
     background: url("../images/example.jpg") no-repeat center; 
    opacity:0;
    Height:100%;
    }

html

<div></div>

ASP.NET - How to write some html in the page? With Response.Write?

You can go with the literal control of ASP.net or you can use panels or the purpose.

Using OR operator in a jquery if statement

Update: using .indexOf() to detect if stat value is one of arr elements

Pure JavaScript

_x000D_
_x000D_
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
    var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
_x000D_
_x000D_

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

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

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

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

If using win7 64 bit OS:

After installing the latest JDK make sure you copy the jre folder from the install location {C:\Program Files\Java\jdk1.7.0_40} directly to your eclipse folder as even pathing it apparently does nothing on win7.

Mad

edit:

Actual jdk version number on folder name will vary as newer versions are released

How can I do a BEFORE UPDATED trigger with sql server?

T-SQL supports only AFTER and INSTEAD OF triggers, it does not feature a BEFORE trigger, as found in some other RDBMSs.

I believe you will want to use an INSTEAD OF trigger.

Installing tkinter on ubuntu 14.04

Install the package python-tk like

sudo apt-get install python-tk

That is described (with apt-cache search python-tk as)

Tkinter - Writing Tk applications with Python

How to remove extension from string (only real extension!)

From the manual, pathinfo:

<?php
    $path_parts = pathinfo('/www/htdocs/index.html');

    echo $path_parts['dirname'], "\n";
    echo $path_parts['basename'], "\n";
    echo $path_parts['extension'], "\n";
    echo $path_parts['filename'], "\n"; // Since PHP 5.2.0
?>

It doesn't have to be a complete path to operate properly. It will just as happily parse file.jpg as /path/to/my/file.jpg.

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Also, to note - the Active Record Class also has a $this->db->where_in() method.

socket.emit() vs. socket.send()

TL;DR:

socket.send(data, callback) is essentially equivalent to calling socket.emit('message', JSON.stringify(data), callback)

Without looking at the source code, I would assume that the send function is more efficient edit: for sending string messages, at least?

So yeah basically emit allows you to send objects, which is very handy.

Take this example with socket.emit:

sendMessage: function(type, message) {
    socket.emit('message', {
        type: type,
        message: message
    });
}

and for those keeping score at home, here is what it looks like using socket.send:

sendMessage: function(type, message) {
    socket.send(JSON.stringify({
        type: type,
        message: message
    }));
}

Print a div content using Jquery

If you want to do this without an extra plugin (like printThis), I think this should work. The idea is to have a special div that will be printed, while everything else is hidden using CSS. This is easier to do if the div is a direct child of the body tag, so you will have to move whatever you want to print to a div like that. S So begin with creating a div with id print-me as a direct child to your body tag. Then use this code to print the div:

$("#btn").click(function () {
    //Copy the element you want to print to the print-me div.
    $("#printarea").clone().appendTo("#print-me");
    //Apply some styles to hide everything else while printing.
    $("body").addClass("printing");
    //Print the window.
    window.print();
    //Restore the styles.
    $("body").removeClass("printing");
    //Clear up the div.
    $("#print-me").empty();
});

The styles you need are these:

@media print {
    /* Hide everything in the body when printing... */
    body.printing * { display: none; }
    /* ...except our special div. */
    body.printing #print-me { display: block; }
}

@media screen {
    /* Hide the special layer from the screen. */
    #print-me { display: none; }
}

The reason why we should only apply the @print styles when the printing class is present is that the page should be printed as normally if the user prints the page by selecting File -> Print.

How to increase Bootstrap Modal Width?

Actually, you are applying CSS on modal div.

you have to apply CSS on .modal-dialog

For example, see the following code.

<div class="modal" id="myModal">
 <div class="modal-dialog" style="width:xxxpx;"> <!-- Set width of div which you want -->
      <div class="modal-content">
           Lorem Ipsum some text...content 

        </div>
     </div>
 </div>

Bootstrap also provides classes for setting div width.

For small modal use modal-sm

And for large modal modal-lg

What happens to C# Dictionary<int, int> lookup if the key does not exist?

int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;

If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.

Hope, this code helps you.

How could I convert data from string to long in c#

You won't be able to convert it directly to long because of the decimal point i think you should convert it into decimal and then convert it into long something like this:

String strValue[i] = "1100.25";
long l1 = Convert.ToInt64(Convert.ToDecimal(strValue));

hope this helps!

How to get just the responsive grid from Bootstrap 3?

Made a Grunt build with the Bootstrap 3.3.5 grid only:

https://github.com/horgen/grunt-builds/tree/master/bootstrap-grid

~10KB minimized.

If you need some other parts from Bootstrap just include them in /src/less/bootstrap.less.

How do I execute a program using Maven?

With the global configuration that you have defined for the exec-maven-plugin:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4.0</version>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

invoking mvn exec:java on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse.

So, to trigger the plugin from the command line, just run:

mvn exec:java

Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>my-execution</id>
      <phase>package</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

With this example, your class would be executed during the package phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.

What is the difference between 127.0.0.1 and localhost

There is nothing different. One is easier to remember than the other. Generally, you define a name to associate with an IP address. You don't have to specify localhost for 127.0.0.1, you could specify any name you want.

Nested JSON: How to add (push) new items to an object?

You can achieve this using Lodash _.assign function.

library[title] = _.assign({}, {'foregrounds': foregrounds }, {'backgrounds': backgrounds });

_x000D_
_x000D_
// This is my JSON object generated from a database_x000D_
var library = {_x000D_
  "Gold Rush": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["1.jpg", "", "2.jpg"]_x000D_
  },_x000D_
  "California": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["3.jpg", "4.jpg", "5.jpg"]_x000D_
  }_x000D_
}_x000D_
_x000D_
// These will be dynamically generated vars from editor_x000D_
var title = "Gold Rush";_x000D_
var foregrounds = ["Howdy", "Slide 2"];_x000D_
var backgrounds = ["1.jpg", ""];_x000D_
_x000D_
function save() {_x000D_
_x000D_
  // If title already exists, modify item_x000D_
  if (library[title]) {_x000D_
_x000D_
    // override one Object with the values of another (lodash)_x000D_
    library[title] = _.assign({}, {_x000D_
      'foregrounds': foregrounds_x000D_
    }, {_x000D_
      'backgrounds': backgrounds_x000D_
    });_x000D_
    console.log(library[title]);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    // console.log('Changes Saved to <b>' + title + '</b>');_x000D_
  }_x000D_
_x000D_
  // If title does not exist, add new item_x000D_
  else {_x000D_
    // Format it for the JSON object_x000D_
    var item = ('"' + title + '" : {"foregrounds" : ' + foregrounds + ',"backgrounds" : ' + backgrounds + '}');_x000D_
_x000D_
    // THE PROBLEM SEEMS TO BE HERE??_x000D_
    // Error: "Result of expression 'library.push' [undefined] is not a function"_x000D_
    library.push(item);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    console.log('Added: <b>' + title + '</b>');_x000D_
  }_x000D_
}_x000D_
_x000D_
save();
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

PHP cURL not working - WAMP on Windows 7 64 bit

This work for me: http://www.mediafire.com/?3ay381k3cq59cm2 download a paste the file in ext folder PHP 5.4.3

Gaussian fit for Python

You get a horizontal straight line because it did not converge.

Better convergence is attained if the first parameter of the fitting (p0) is put as max(y), 5 in the example, instead of 1.

How do I check in SQLite whether a table exists?

Use

SELECT 1 FROM table LIMIT 1;

to prevent all records from being read.

Can I grep only the first n lines of a file?

You have a few options using programs along with grep. The simplest in my opinion is to use head:

head -n10 filename | grep ...

head will output the first 10 lines (using the -n option), and then you can pipe that output to grep.

Getting value of HTML text input

Yes, you can use jQuery to make this done, the idea is

Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.

<form name="input" action="handle_email.php" method="post">
  <input type="hidden" name="email" id="email" />
  <input type="submit" value="Submit" />
</form> 

<script>
   $("form").submit(function() {
     var emailFromOtherTextBox = $("#email_textbox").val();
     $("#email").val(emailFromOtherTextBox ); 
     return true;
  });
</script>

also see http://api.jquery.com/submit/

How can I use a custom font in Java?

From the Java tutorial, you need to create a new font and register it in the graphics environment:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));

After this step is done, the font is available in calls to getAvailableFontFamilyNames() and can be used in font constructors.

ORA-01652 Unable to extend temp segment by in tablespace

I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)

How does Google calculate my location on a desktop?

They use a combination of IP geolocation, as well as comparing the results of a scan for nearby wireless networks with a database on their side (which is built by collecting GPS coordinates alongside wifi scan data when Android phone users use their GPS)

How To: Execute command line in C#, get STD OUT results

Julian's solution is tested working with some minor corrections. The following is an example that also used https://sourceforge.net/projects/bat-to-exe/ GenericConsole.cs and https://www.codeproject.com/Articles/19225/Bat-file-compiler program.txt for args part:

using System;
using System.Text;  //StringBuilder
using System.Diagnostics;
using System.IO;


class Program
{
    private static bool redirectStandardOutput = true;

    private static string buildargument(string[] args)
    {
        StringBuilder arg = new StringBuilder();
        for (int i = 0; i < args.Length; i++)
        {
            arg.Append("\"" + args[i] + "\" ");
        }

        return arg.ToString();
    }

    static void Main(string[] args)
    {
        Process prc = new Process();
        prc.StartInfo = //new ProcessStartInfo("cmd.exe", String.Format("/c \"\"{0}\" {1}", Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args)));
        //new ProcessStartInfo(Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args));
        new ProcessStartInfo("mapTargetIDToTargetNameA3.bat");
        prc.StartInfo.Arguments = buildargument(args);

        prc.EnableRaisingEvents = true;

        if (redirectStandardOutput == true)
        {
            prc.StartInfo.UseShellExecute = false;
        }
        else
        {
            prc.StartInfo.UseShellExecute = true;
        }

        prc.StartInfo.CreateNoWindow = true;

        prc.OutputDataReceived += OnOutputDataRecived;
        prc.ErrorDataReceived += OnErrorDataReceived;
        //prc.Exited += OnExited;

        prc.StartInfo.RedirectStandardOutput = redirectStandardOutput;
        prc.StartInfo.RedirectStandardError = redirectStandardOutput;

        try
        {
            prc.Start();
            prc.BeginOutputReadLine();
            prc.BeginErrorReadLine();
            prc.WaitForExit();
        }
        catch (Exception e)
        {
            Console.WriteLine("OS error: " + e.Message);
        }

        prc.Close();
    }

    // Handle the dataevent
    private static void OnOutputDataRecived(object sender, DataReceivedEventArgs e)
    {
        //do something with your data
        Console.WriteLine(e.Data);
    }

    //Handle the error
    private static void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine(e.Data);
    }

    // Handle Exited event and display process information.
    //private static void OnExited(object sender, System.EventArgs e)
    //{
    //    var process = sender as Process;
    //    if (process != null)
    //    {
    //        Console.WriteLine("ExitCode: " + process.ExitCode);
    //    }
    //    else
    //    {
    //        Console.WriteLine("Process exited");
    //    }
    //}
}

The code need to compile inside VS2007, using commandline csc.exe generated executable will not show console output correctly, or even crash with CLR20r3 error. Comment out the OnExited event process, the console output of the bat to exe will be more like the original bat console output.

Developing for Android in Eclipse: R.java not regenerating

I encountered this problem for the first time this afternoon. Even when I create a new project, R.java isn't generated. I changed the workplace, and everything works again.

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

You can also try this one,

==> Get target/source position in viewport
==> Check whether space from bottom is less that your tooltip height
==> If space from bottom is less that your tooltip height, then just scroll page up

placement: function(context, source){
  //get target/source position in viewport
  var bounds = $(source)[0].getBoundingClientRect();
      winHeight = $(window).height();

  //check wheather space from bottom is less that your tooltip height
  var rBottom = winHeight - bounds.bottom;

  //Consider 180 == your Tooltip height
  //if space from bottom is less that your tooltip height, this will scrolls page up
  //We are keeping tooltip position is fixed(at bottom)

  if (rBottom < 180){
    $('html, body').animate({ scrollTop: $(document).scrollTop()+180 }, 'slow');
  }

  return "bottom";
}

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

JAR File Manifest Attributes for Security

The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.

Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.

Permissions Attribute

The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.

Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:

  • sandbox - runs in the security sandbox and does not require additional permissions.

  • all-permissions - requires access to the user's system resources.

Changes to Security Slider:

The following changes to Security Slider were included in this release(7u51):

  • Block Self-Signed and Unsigned applets on High Security Setting
  • Require Permissions Attribute for High Security Setting
  • Warn users of missing Permissions Attributes for Medium Security Setting

For more information, see Java Control Panel documentation.

enter image description here

sample MANIFEST.MF

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet

How to change menu item text dynamically in Android

you can do this create a global "Menu" object then assign it in onCreateOptionMenu

public class ExampleActivity extends AppCompatActivity
    Menu menu;

then assign here

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    this.menu = menu;
    return true;
}

Then later use assigned Menu object to get required items

menu.findItem(R.id.bedSwitch).setTitle("Your Text");

How to underline a UILabel in swift?

The answer above is causing an error in my build environment.

This doesn't work in Swift 4.0:

attributedText.addAttribute(NSUnderlineStyleAttributeName, 
                            value: NSUnderlineStyle.styleSingle.rawValue, 
                            range: textRange)

Try this instead:

attributedText.addAttribute(NSAttributedStringKey.underlineStyle,
                            value: NSUnderlineStyle.styleSingle.rawValue,
                            range: textRange)

hope this helps someone.

How to add white spaces in HTML paragraph

You can try it by adding &nbsp;

Masking password input from the console : Java

If you're dealing with a Java character array (such as password characters that you read from the console), you can convert it to a JRuby string with the following Ruby code:

# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"

jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}

# .. do something with 'password' variable ..    
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"

See also "https://stackoverflow.com/a/27628738/4390019" and "https://stackoverflow.com/a/27628756/4390019"

How to get a file or blob from an object URL?

If you show the file in a canvas anyway you can also convert the canvas content to a blob object.

canvas.toBlob(function(my_file){
  //.toBlob is only implemented in > FF18 but there is a polyfill 
  //for other browsers https://github.com/blueimp/JavaScript-Canvas-to-Blob
  var myBlob = (my_file);
})

Display a float with two decimal places in Python

If you actually want to change the number itself instead of only displaying it differently use format()

Format it to 2 decimal places:

format(value, '.2f')

example:

>>> format(5.00000, '.2f')
'5.00'

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

How to exit an if clause

The only thing that would apply this without additional methods is elif as the following example

a = ['yearly', 'monthly', 'quartly', 'semiannual', 'monthly', 'quartly', 'semiannual', 'yearly']
# start the condition
if 'monthly' in b: 
    print('monthly') 
elif 'quartly' in b: 
    print('quartly') 
elif 'semiannual' in b: 
    print('semiannual') 
elif 'yearly' in b: 
    print('yearly') 
else: 
    print('final') 

how to get the selected index of a drop down

If you are actually looking for the index number (and not the value) of the selected option then it would be

document.forms[0].elements["CCards"].selectedIndex 
/* You may need to change document.forms[0] to reference the correct form */

or using jQuery

$('select[name="CCards"]')[0].selectedIndex 

CodeIgniter: How to get Controller, Action, URL information

The methods are deprecated.

$this->router->fetch_class();
$this->router->fetch_method();

You can access the properties instead.

$this->router->class;
$this->router->method;

See codeigniter user guide

URI Routing methods fetch_directory(), fetch_class(), fetch_method()

With properties CI_Router::$directory, CI_Router::$class and CI_Router::$method being public and their respective fetch_*() no longer doing anything else to just return the properties - it doesn’t make sense to keep them.

Those are all internal, undocumented methods, but we’ve opted to deprecate them for now in order to maintain backwards-compatibility just in case. If some of you have utilized them, then you can now just access the properties instead:

$this->router->directory;
$this->router->class;
$this->router->method;

How to combine multiple conditions to subset a data-frame using "OR"?

Just for the sake of completeness, we can use the operators [ and [[:

set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])

Several options

df[df[1] < 0.5 | df[2] == "g", ] 
df[df[[1]] < 0.5 | df[[2]] == "g", ] 
df[df["v1"] < 0.5 | df["v2"] == "g", ]

df$name is equivalent to df[["name", exact = FALSE]]

Using dplyr:

library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")

Using sqldf:

library(sqldf)
sqldf('SELECT *
      FROM df 
      WHERE v1 < 0.5 OR v2 = "g"')

Output for the above options:

          v1 v2
1 0.26550866  a
2 0.37212390  b
3 0.20168193  e
4 0.94467527  g
5 0.06178627  j

How can I update my ADT in Eclipse?

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help

  2. Install New Software ---> Add

  3. inside Add Repository write the Name: ADT (or whatever you want)

  4. Location: https://dl-ssl.google.com/android/eclipse/

  5. after loading you should get Developer Tools and NDK Plugins

  6. check both if you want to use the Native Developer Kit (NDK) in the future or check

  7. Developer Tool only

  8. click Next

  9. Finish

Way to get all alphabetic chars in an array in PHP?

Another way:

$c = 'A';
$chars = array($c);
while ($c < 'Z') $chars[] = ++$c;

Sharing a variable between multiple different threads

  1. Making it static could fix this issue.
  2. Reference to the main thread in other thread and making that variable visible

sql: check if entry in table A exists in table B

SELECT *
FROM   B
WHERE  NOT EXISTS (SELECT 1 
                   FROM   A 
                   WHERE  A.ID = B.ID)

Array initialization in Perl

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

MVC 4 Data Annotations "Display" Attribute

One of the benefits is you can use it in multiple views and have a consistent label text. It is also used by asp.net MVC scaffolding to generate the labels text and makes it easier to generate meaningful text

[Display(Name = "Wild and Crazy")]
public string WildAndCrazyProperty { get; set; }

"Wild and Crazy" shows up consistently wherever you use the property in your application.

Sometimes this is not flexible as you might want to change the text in some view. In that case, you will have to use custom markup like in your second example

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

Well, you can detect when your input boxes have the focus, and you know the height of the keyboard. There is also CSS available to get the orientation of the screen, so I think you can hack it.

You would want to handle the case of a physical keyboard somehow, though.

Replacing all non-alphanumeric characters with empty strings

I made this method for creating filenames:

public static String safeChar(String input)
{
    char[] allowed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_".toCharArray();
    char[] charArray = input.toString().toCharArray();
    StringBuilder result = new StringBuilder();
    for (char c : charArray)
    {
        for (char a : allowed)
        {
            if(c==a) result.append(a);
        }
    }
    return result.toString();
}

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Html table tr inside td

Try this code

_x000D_
_x000D_
<table border="1" width="100%">
  <tr>
    <td>Name 1</td>
    <td>Name 2</td>
    <td colspan="2">Name 3</td>
    <td>Name 4</td>
  </tr>

  <tr>
    <td rowspan="3">ITEM 1</td>
    <td rowspan="3">ITEM 2</td>
    <td>name</td>
    <td>price</td>
    <td rowspan="3">ITEM 4</td>
  </tr>
  <tr>
    <td>name</td>
    <td>price</td>
  </tr>
  <tr>
    <td>name</td>
    <td>price</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

list.clear() vs list = new ArrayList<Integer>();

I would suggest using list.clear() rather than allocating a new object. When you call the "new" keyword, you are creating more space in memory. In reality, it doesn't matter much. I suppose that if you know how large the list will be, it might be a good idea to create a new space but then specify how large the array will be.

The truth is, it's not going to matter unless you're doing scientific programming. In that case, you need to go learn C++.

How can I select an element by name with jQuery?

You can use the jQuery attribute selector:

$('td[name ="tcol1"]')   // matches exactly 'tcol1'
$('td[name^="tcol"]' )   // matches those that begin with 'tcol'
$('td[name$="tcol"]' )   // matches those that end with 'tcol'
$('td[name*="tcol"]' )   // matches those that contain 'tcol'

How to change column datatype from character to numeric in PostgreSQL 8.4

If your VARCHAR column contains empty strings (which are not the same as NULL for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:

ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
            USING COALESCE(NULLIF(code, '')::NUMERIC, 0);

(found with the help of this answer)

How to compare strings in C conditional preprocessor-directives

If your strings are compile time constants (as in your case) you can use the following trick:

#define USER_JACK strcmp(USER, "jack")
#define USER_QUEEN strcmp(USER, "queen")
#if $USER_JACK == 0
#define USER_VS USER_QUEEN
#elif USER_QUEEN == 0
#define USER_VS USER_JACK
#endif

The compiler can tell the result of the strcmp in advance and will replace the strcmp with its result, thus giving you a #define that can be compared with preprocessor directives. I don't know if there's any variance between compilers/dependance on compiler options, but it worked for me on GCC 4.7.2.

EDIT: upon further investigation, it look like this is a toolchain extension, not GCC extension, so take that into consideration...

Getting the last element of a list

some_list[-1] is the shortest and most Pythonic.

In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.

You can also set list elements in this way. For instance:

>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

Note that getting a list item by index will raise an IndexError if the expected item doesn't exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can't have a last element.

How can I return two values from a function in Python?

you can try this

class select_choice():
    return x, y

a, b = test()

How do I compare strings in Java?

In Java, when the == operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.

The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

The == operator checks if the two strings are exactly the same object.

The .equals() method check if the two strings have the same value.

Regex doesn't work in String.matches()

[a-z] matches a single char between a and z. So, if your string was just "d", for example, then it would have matched and been printed out.

You need to change your regex to [a-z]+ to match one or more chars.

LINQ: Distinct values

I'm a bit late to the answer, but you may want to do this if you want the whole element, not only the values you want to group by:

var query = doc.Elements("whatever")
               .GroupBy(element => new {
                             id = (int) element.Attribute("id"),
                             category = (int) element.Attribute("cat") })
               .Select(e => e.First());

This will give you the first whole element matching your group by selection, much like Jon Skeets second example using DistinctBy, but without implementing IEqualityComparer comparer. DistinctBy will most likely be faster, but the solution above will involve less code if performance is not an issue.

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

the output is from NonFinalPluginExpiry.java

example 2.4.0-alpha7

https://github.com/c3ph3us/android-gradle-plugin-source-codes/blob/master/gradle-2.4.0-alpha7-sources/com/android/build/gradle/internal/NonFinalPluginExpiry.java

if someone want to use plugin and dont want to do a daily google shi..

either need to:

  1. recompile plugin
  2. replace "Plugin-Version" in manifest
  3. make a automation script to generate env var and set it daily

         MessageDigest crypt = MessageDigest.getInstance("SHA-1");
         crypt.reset();
         crypt.update(String.format(
                         "%1$s:%2$s:%3$s",
                            now.getYear(),
                            now.getMonthValue() -1,
                            now.getDayOfMonth())
                            .getBytes("utf8"));
        String overrideValue = new BigInteger(1, crypt.digest()).toString(16);
    

EXAMPLE APP IN JAVA (sources + JAR):

  1. FOR GENERATE ADO - for ALL OS'es WITH JVM
  2. SET ENV for LINUX

https://github.com/c3ph3us/ado

https://github.com/c3ph3us/ado/releases

example bash function to export env and start idea / or studio:

// eval export & start idea :) 
function sti() {
    export `java -jar AndroidDailyOverride.jar p`
    idea.sh
}

How do I check if a string contains another string in Swift?

Extension way

Swift 4

extension String {
    func contains(find: String) -> Bool{
        return self.range(of: find) != nil
    }
    func containsIgnoringCase(find: String) -> Bool{
        return self.range(of: find, options: .caseInsensitive) != nil
    }
}

var value = "Hello world"

print(value.contains("Hello")) // true
print(value.contains("bo"))    // false

print(value.containsIgnoringCase(find: "hello"))    // true
print(value.containsIgnoringCase(find: "Hello"))    // true
print(value.containsIgnoringCase(find: "bo"))       // false

Generally Swift 4 has contains method however it available from iOS 8.0+


Swift 3.1

You can write extension contains: and containsIgnoringCase for String

extension String { 

   func contains(_ find: String) -> Bool{
     return self.range(of: find) != nil
   }

   func containsIgnoringCase(_ find: String) -> Bool{
     return self.range(of: find, options: .caseInsensitive) != nil 
   }
 }

Older Swift version

extension String {

    func contains(find: String) -> Bool{
       return self.rangeOfString(find) != nil
     }

    func containsIgnoringCase(find: String) -> Bool{
       return self.rangeOfString(find, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil
     }
}

Example:

var value = "Hello world"

print(value.contains("Hello")) // true
print(value.contains("bo"))    // false

print(value.containsIgnoringCase("hello"))    // true
print(value.containsIgnoringCase("Hello"))    // true
print(value.containsIgnoringCase("bo"))       // false

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

How to auto generate migrations with Sequelize CLI from Sequelize models?

If you don't want to recreate your model from scratch, you can manually generate a migration file using the following CLI command:

sequelize migration:generate --name [name_of_your_migration]

This will generate a blank skeleton migration file. While it doesn't copy your model structure over to the file, I do find it easier and cleaner than regenerating everything. Note: make sure to run the command from the containing directory of your migrations directory; otherwise the CLI will generate a new migration dir for you

How to use Fiddler to monitor WCF service

I just tried the first answer from Brad Rem and came to this setting in the web.config under BasicHttpBinding:

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding bypassProxyOnLocal="False" useDefaultWebProxy="false" proxyAddress="http://127.0.0.1:8888" ...
        ...
      </basicHttpBinding>
    </bindings>
    ...
<system.serviceModel>

Hope this helps someone.

How to install requests module in Python 3.4, instead of 2.7

On Windows with Python v3.6.5

py -m pip install requests

Fake "click" to activate an onclick method

I could be misinterpreting your question, but, yes, this is possible. The way that I would go about doing it is this:

var oElement = document.getElementById('elementId');   // get a reference to your element
oElement.onclick = clickHandler; // assign its click function a function reference

function clickHandler() {
    // this function will be called whenever the element is clicked
    // and can also be called from the context of other functions
}

Now, whenever this element is clicked, the code in clickHandler will execute. Similarly, you can execute the same code by calling the function from within the context of other functions (or even assign clickHandler to handle events triggered by other elements)>

Javascript wait() function

You shouldn't edit it, you should completely scrap it.

Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout correctly.

How to print from Flask @app.route to python console

It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:

from __future__ import print_function # In python 2.7
import sys

@app.route('/button/')
def button_clicked():
    print('Hello world!', file=sys.stderr)
    return redirect('/')

Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post

Div Scrollbar - Any way to style it?

Using javascript you can style the scroll bars. Which works fine in IE as well as FF.

Check the below links

From Twinhelix , Example 2 , Example 3 [or] you can find some 30 type of scroll style types by click the below link 30 scrolling techniques

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

For me I put my dependencies in the wrong spot.

buildscript {
  dependencies {
    //Don't put dependencies here.
  }
}

dependencies {
 //Put them here
}

How do I remove blue "selected" outline on buttons?

That is a default behaviour of each browser; your browser seems to be Safari, in Google Chrome it is orange in color!

Use this to remove this effect:

button {
  outline: none; // this one
}

Visual Studio Code includePath

The best way to configure the standard headers for your project is by setting the compilerPath property to the configurations in your c_cpp_properties.json file. It is not recommended to add system include paths to the includePath property.

Another option if you prefer not to use c_cpp_properties.json is to set the C_Cpp.default.compilerPath setting.

Read a text file line by line in Qt

Use this code:

QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
   QTextStream in(&inputFile);
   while (!in.atEnd())
   {
      QString line = in.readLine();
      ...
   }
   inputFile.close();
}

Group query results by month and year in postgresql

select to_char(date,'Mon') as mon,
       extract(year from date) as yyyy,
       sum("Sales") as "Sales"
from yourtable
group by 1,2

At the request of Radu, I will explain that query:

to_char(date,'Mon') as mon, : converts the "date" attribute into the defined format of the short form of month.

extract(year from date) as yyyy : Postgresql's "extract" function is used to extract the YYYY year from the "date" attribute.

sum("Sales") as "Sales" : The SUM() function adds up all the "Sales" values, and supplies a case-sensitive alias, with the case sensitivity maintained by using double-quotes.

group by 1,2 : The GROUP BY function must contain all columns from the SELECT list that are not part of the aggregate (aka, all columns not inside SUM/AVG/MIN/MAX etc functions). This tells the query that the SUM() should be applied for each unique combination of columns, which in this case are the month and year columns. The "1,2" part is a shorthand instead of using the column aliases, though it is probably best to use the full "to_char(...)" and "extract(...)" expressions for readability.

How to get a index value from foreach loop in jstl

You can use the varStatus attribute like this:-

<c:forEach var="categoryName" items="${categoriesList}" varStatus="myIndex">

myIndex.index will give you the index. Here myIndex is a LoopTagStatus object.

Hence, you can send that to your javascript method like this:-

<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>

HTML/Javascript: how to access JSON data loaded in a script tag with src set

Check this answer: https://stackoverflow.com/a/7346598/1764509

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});

NULL values inside NOT IN clause

Query A is the same as:

select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null

Since 3 = 3 is true, you get a result.

Query B is the same as:

select 'true' where 3 <> 1 and 3 <> 2 and 3 <> null

When ansi_nulls is on, 3 <> null is UNKNOWN, so the predicate evaluates to UNKNOWN, and you don't get any rows.

When ansi_nulls is off, 3 <> null is true, so the predicate evaluates to true, and you get a row.

Is key-value pair available in Typescript?

If you are trying to use below example

Example: { value1: "value1" }

And add conditionalData dynamically based on some condition, Try

let dataToWrite: any = {value1: "value1"};

if(conditionalData)
   dataToWrite["conditionalData"] = conditionalData

Youtube - downloading a playlist - youtube-dl

Download YouTube playlist videos in separate directory indexed by video order in a playlist

$ youtube-dl -o '%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s'  https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re

Download all playlists of YouTube channel/user keeping each playlist in separate directory:

$ youtube-dl -o '%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' https://www.youtube.com/user/TheLinuxFoundation/playlists

Video Selection:

youtube-dl is a command-line program to download videos from YouTube.com and a few more sites. It requires the Python interpreter, version 2.6, 2.7, or 3.2+, and it is not platform specific. It should work on your Unix box, on Windows or on macOS. It is released to the public domain, which means you can modify it, redistribute it or use it however you like.

$ youtube-dl [OPTIONS] URL [URL...]
--playlist-start NUMBER          Playlist video to start at (default is 1)

--playlist-end NUMBER            Playlist video to end at (default is last)

--playlist-items ITEM_SPEC       Playlist video items to download. Specify
                                 indices of the videos in the playlist
                                 separated by commas like: "--playlist-items
                                 1,2,5,8" if you want to download videos
                                 indexed 1, 2, 5, 8 in the playlist. You can
                                 specify range: "--playlist-items
                                 1-3,7,10-13", it will download the videos
                                 at index 1, 2, 3, 7, 10, 11, 12 and 13.

Check an integer value is Null in c#

Simply you can do this:

    public void CheckNull(int? item)
    {
        if (item != null)
        {
            //Do Something
        }

    }

OS X Framework Library not loaded: 'Image not found'

I think there is no fixed way to solve this problem since it might be caused by different reason. I also had this problem last week, I don't know when and exactly what cause this problem, only when I run it on simulator with Xcode or try to install it onto the phone, then it reports such kind of error, But when I run it with react-native run-ios with terminal, there is no problem.

I checked all the ways posted on the internet, like renew certificate, change settings in Xcode (all of ways mentions above), actually all of settings in Xcode were already set as it requested before, none of ways works for me. Until this morning when I delete the pods and reinstall, the error finally gonna after a week. If you are also using cocoapod and then error was just show up without any specific reason, maybe you can try my way.

  1. Check my cocoapods version.
  2. Update it if there is new version available.
  3. Go to your project folder, delete your Podfile.lock , Pods file, project xcworkspace.
  4. Run pod install

How do I time a method's execution in Java?

System.currentTimeMillis(); IS NOT a good approach for measuring the performance of your algorithms. It measures the total time you experience as a user watching the computer screen. It includes also time consumed by everything else running on your computer in the background. This could make a huge difference in case you have a lot of programs running on your workstation.

Proper approach is using java.lang.management package.

From http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking website (archive link):

  • "User time" is the time spent running your application's own code.
  • "System time" is the time spent running OS code on behalf of your application (such as for I/O).

getCpuTime() method gives you sum of those:

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class CPUUtils {

    /** Get CPU time in nanoseconds. */
    public static long getCpuTime( ) {
        ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
        return bean.isCurrentThreadCpuTimeSupported( ) ?
            bean.getCurrentThreadCpuTime( ) : 0L;
    }

    /** Get user time in nanoseconds. */
    public static long getUserTime( ) {
        ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
        return bean.isCurrentThreadCpuTimeSupported( ) ?
            bean.getCurrentThreadUserTime( ) : 0L;
    }

    /** Get system time in nanoseconds. */
    public static long getSystemTime( ) {
        ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
        return bean.isCurrentThreadCpuTimeSupported( ) ?
            (bean.getCurrentThreadCpuTime( ) - bean.getCurrentThreadUserTime( )) : 0L;
    }

}

How to generate graphs and charts from mysql database in php

I use Google Chart Tools https://developers.google.com/chart/ It's well documented and the charts look great. Being javascript, you can feed it json data via ajax.

How to install node.js as windows service?

I'm not addressing the question directly, but providing an alternative that might also meet your requirement in a more node.js fashion way.

Functionally the requirements are:

  1. Have the logic (app) running in the background
  2. Be able to start/stop the logic
  3. Automatically start the logic when system boots up

These requirements can be satisfied by using a process manager (PM) and making the process manager start on system startup. Two good PMs that are Windows-friendly are:

To make the PM start automatically, the most simple way is to create a scheduled task with a "At Startup" trigger:

enter image description here

phpMyAdmin + CentOS 6.0 - Forbidden

Edit your httpd.conf file as follows:

# nano /etc/httpd/conf/httpd.conf

Add the following lines here:

<Directory "/usr/share/phpmyadmin">
    Order allow,deny
    Allow from all
</Directory>

Issue the following command:

# service httpd restart

If your problem is not solved then disable your SELinux.

Android Studio - Auto complete and other features not working

  1. Close Android Studio.
  2. Go to C:/User/[SystemName] and delete .gradle file.
  3. Open Android Studio and sync gradle file again.

Replace multiple characters in one replace call

You can just try this :

str.replace(/[.#]/g, 'replacechar');

this will replace .,- and # with your replacechar !