Programs & Examples On #Channelfactory

WCF ChannelFactory class - used to create and manage Channel-s which are used to send and receive Message-s to WCF service endpoints

WCF error - There was no endpoint listening at

You can solve the issue by clearing value of address in endpoint tag in web.config:

<endpoint address="" name="wsHttpEndpoint"  .......           />

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

Try browse the WCF in IIS see if it's alive and works normally,

In my case it's because the physical path of the WCF is misdirected.

Task<> does not contain a definition for 'GetAwaiter'

I had this problem because I was calling a method

await myClass.myStaticMethod(myString);

but I was setting myString with

var myString = String.Format({some dynamic-type values})

which resulted in a dynamic type, not a string, thus when I tried to await on myClass.myStaticMethod(myString), the compiler thought I meant to call myClass.myStaticMethod(dynamic myString). This compiled fine because, again, in a dynamic context, it's all good until it blows up at run-time, which is what happened because there is no implementation of the dynamic version of myStaticMethod, and this error message didn't help whatsoever, and the fact that Intellisense would take me to the correct definition didn't help either.
Tricky!

However, by forcing the result type to string, like:

var myString = String.Format({some dynamic-type values})

to

string myString = String.Format({some dynamic-type values})

my call to myStaticMethod routed properly

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I didn't have control over the security configuration for the service I was calling into, but got the same error. I was able to fix my client as follows.

  1. In the config, set up the security mode:

    <security mode="TransportCredentialOnly">
      <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
      <message clientCredentialType="UserName" algorithmSuite="Default" />
    </security>
    
  2. In the code, set the proxy class to allow impersonation (I added a reference to a service called customer):

    Customer_PortClient proxy = new Customer_PortClient();
    proxy.ClientCredentials.Windows.AllowedImpersonationLevel =    
             System.Security.Principal.TokenImpersonationLevel.Impersonation;
    

WCF timeout exception detailed investigation

Did you check the WCF traces? WCF has a tendency to swallow exceptions and only return the last exception, which is the timeout that you're getting, since the end point didn't return anything meaningful.

What is the best workaround for the WCF client `using` block issue?

I'd like to add implementation of Service from Marc Gravell's answer for case of using ServiceClient instead of ChannelFactory.

public interface IServiceConnector<out TServiceInterface>
{
    void Connect(Action<TServiceInterface> clientUsage);
    TResult Connect<TResult>(Func<TServiceInterface, TResult> channelUsage);
}

internal class ServiceConnector<TService, TServiceInterface> : IServiceConnector<TServiceInterface>
    where TServiceInterface : class where TService : ClientBase<TServiceInterface>, TServiceInterface, new()
{
    public TResult Connect<TResult>(Func<TServiceInterface, TResult> channelUsage)
    {
        var result = default(TResult);
        Connect(channel =>
        {
            result = channelUsage(channel);
        });
        return result;
    }

    public void Connect(Action<TServiceInterface> clientUsage)
    {
        if (clientUsage == null)
        {
            throw new ArgumentNullException("clientUsage");
        }
        var isChanneldClosed = false;
        var client = new TService();
        try
        {
            clientUsage(client);
            client.Close();
            isChanneldClosed = true;
        }
        finally
        {
            if (!isChanneldClosed)
            {
                client.Abort();
            }
        }
    }
}

Android replace the current fragment with another fragment

Use android.support.v4.app for FragmentManager & FragmentTransaction in your code, it has worked for me.

DetailsFragment detailsFragment = new DetailsFragment();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.details,detailsFragment);
fragmentTransaction.commit();

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

composer dump-autoload

PATH vendor/composer/autoload_classmap.php
  • Composer dump-autoload won’t download a thing.
  • It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php).
  • Ideal for when you have a new class inside your project.
  • autoload_classmap.php also includes the providers in config/app.php

php artisan dump-autoload

  • It will call Composer with the optimize flag
  • It will 'recompile' loads of files creating the huge bootstrap/compiled.php

How do I get a plist as a Dictionary in Swift?

in my case I create a NSDictionary called appSettings and add all needed keys. For this case, the solution is:

if let dict = NSBundle.mainBundle().objectForInfoDictionaryKey("appSettings") {
  if let configAppToken = dict["myKeyInsideAppSettings"] as? String {

  }
}

How do I find files with a path length greater than 260 characters in Windows?

As a refinement of simplest solution, and if you can’t or don’t want to install Powershell, just run:

dir /s /b | sort /r /+261 > out.txt

or (faster):

dir /s /b | sort /r /+261 /o out.txt

And lines longer than 260 will get to the top of listing. Note that you must add 1 to SORT column parameter (/+n).

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

How to do a SUM() inside a case statement in SQL server

You could use a Common Table Expression to create the SUM first, join it to the table, and then use the WHEN to to get the value from the CTE or the original table as necessary.

WITH PercentageOfTotal (Id, Percentage) 
AS 
(
    SELECT Id, (cnt / SUM(AreaId)) FROM dbo.MyTable GROUP BY Id
)
SELECT 
    CASE
        WHEN o.TotalType = 'Average' THEN r.avgscore
        WHEN o.TotalType = 'PercentOfTot' THEN pt.Percentage
        ELSE o.cnt
    END AS [displayscore]
FROM PercentageOfTotal pt
    JOIN dbo.MyTable t ON pt.Id = t.Id

What data type to use in MySQL to store images?

This can be done from the command line. This will create a column for your image with a NOT NULL property.

CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB; 

From here

How do you align left / right a div without using float?

You could just use a margin-left with a percentage.

HTML

<div class="goleft">Left Div</div>
<div class="goright">Right Div</div>

CSS

.goright{
    margin-left:20%;
}
.goleft{
    margin-right:20%;
}

(goleft would be the same as default, but can reverse if needed)

text-align doesn't always work as intended for layout options, it's mainly just for text. (But is often used for form elements too).

The end result of doing this will have a similar effect to a div with float:right; and width:80% set. Except, it won't clump together like a float will. (Saving the default display properties for the elements that come after).

How to check if there exists a process with a given pid in Python?

The answers involving sending 'signal 0' to the process will work only if the process in question is owned by the user running the test. Otherwise you will get an OSError due to permissions, even if the pid exists in the system.

In order to bypass this limitation you can check if /proc/<pid> exists:

import os

def is_running(pid):
    if os.path.isdir('/proc/{}'.format(pid)):
        return True
    return False

This applies to linux based systems only, obviously.

Check if string is neither empty nor space in shell script

Another quick test for a string to have something in it but space.

if [[ -n "${str// /}" ]]; then
    echo "It is not empty!"
fi

"-n" means non-zero length string.

Then the first two slashes mean match all of the following, in our case space(s). Then the third slash is followed with the replacement (empty) string and closed with "}". Note the difference from the usual regular expression syntax.

You can read more about string manipulation in bash shell scripting here.

Laravel Controller Subfolder routing

In my case I had a prefix that had to be added for each route in the group, otherwise response would be that the UserController class was not found.

Route::prefix('/user')->group(function() {
    Route::post('/login', [UserController::class, 'login'])->prefix('/user');
    Route::post('/register', [UserController::class, 'register'])->prefix('/user');
});

Where does pip install its packages?

By default, on Linux, Pip installs packages to /usr/local/lib/python2.7/dist-packages.

Using virtualenv or --user during install will change this default location. If you use pip show make sure you are using the right user or else pip may not see the packages you are referencing.

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Easiest way to read/write a file's content in Python

If you're open to using libraries, try installing forked-path (with either easy_install or pip).

Then you can do:

from path import path
s = path(filename).bytes()

This library is fairly new, but it's a fork of a library that's been floating around Python for years and has been used quite a bit. Since I found this library years ago, I very seldom use os.path or open() any more.

Where to get "UTF-8" string literal in Java?

Now I use org.apache.commons.lang3.CharEncoding.UTF_8 constant from commons-lang.

PHP remove all characters before specific string

Considering

$string="We have www/audio path where the audio files are stored";  //Considering the string like this

Either you can use

strstr($string, 'www/audio');

Or

$expStr=explode("www/audio",$string);
$resultString="www/audio".$expStr[1];

Regex pattern for numeric values

"[1-9][0-9]*|0"

I'd just use "[0-9]+" to represent positive whole numbers.

3-dimensional array in numpy

You are right, you are creating a matrix with 2 rows, 3 columns and 4 depth. Numpy prints matrixes different to Matlab:

Numpy:

>>> import numpy as np
>>> np.zeros((2,3,2))
 array([[[ 0.,  0.],
    [ 0.,  0.],
    [ 0.,  0.]],

   [[ 0.,  0.],
    [ 0.,  0.],
    [ 0.,  0.]]])

Matlab

>> zeros(2, 3, 2)
 ans(:,:,1) =
     0     0     0
     0     0     0
 ans(:,:,2) =
     0     0     0
     0     0     0

However you are calculating the same matrix. Take a look to Numpy for Matlab users, it will guide you converting Matlab code to Numpy.


For example if you are using OpenCV, you can build an image using numpy taking into account that OpenCV uses BGR representation:

import cv2
import numpy as np

a = np.zeros((100, 100,3))
a[:,:,0] = 255

b = np.zeros((100, 100,3))
b[:,:,1] = 255

c = np.zeros((100, 200,3)) 
c[:,:,2] = 255

img = np.vstack((c, np.hstack((a, b))))

cv2.imshow('image', img)
cv2.waitKey(0)

enter image description here

If you take a look to matrix c you will see it is a 100x200x3 matrix which is exactly what it is shown in the image (in red as we have set the R coordinate to 255 and the other two remain at 0).

Select all columns except one in MySQL?

I would like to add another point of view in order to solve this problem, specially if you have a small number of columns to remove.

You could use a DB tool like MySQL Workbench in order to generate the select statement for you, so you just have to manually remove those columns for the generated statement and copy it to your SQL script.

In MySQL Workbench the way to generate it is:

Right click on the table -> send to Sql Editor -> Select All Statement.

AngularJS - Multiple ng-view in single template

It is possible to have multiple or nested views. But not by ng-view.

The primary routing module in angular does not support multiple views. But you can use ui-router. This is a third party module which you can get via Github, angular-ui/ui-router, https://github.com/angular-ui/ui-router . Also a new version of ngRouter (ngNewRouter) currently, is being developed. It is not stable at the moment. So I provide you a simple start up example with ui-router. Using it you can name views and specify which templates and controllers should be used for rendering them. Using $stateProvider you should specify how view placeholders should be rendered for specific state.

<body ng-app="main">
    <script type="text/javascript">
    angular.module('main', ['ui.router'])
    .config(['$locationProvider', '$stateProvider', function ($locationProvider, $stateProvider) {
        $stateProvider
        .state('home', {
            url: '/',
            views: {
                'header': {
                    templateUrl: '/app/header.html'
                },
                'content': {
                    templateUrl: '/app/content.html'
                }
            }
        });
    }]);
    </script>
    <a ui-sref="home">home</a>
    <div ui-view="header">header</div>
    <div ui-view="content">content</div>
    <div ui-view="bottom">footer</div>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-ui-router/release/angular-ui-router.js">
</body>

You need referencing angularjs, and angular-ui.router for this sample.

$ bower install angular-ui-router

Invert colors of an image in CSS or JavaScript

You can apply the style via javascript. This is the Js code below that applies the filter to the image with the ID theImage.

function invert(){
document.getElementById("theImage").style.filter="invert(100%)";
}

And this is the

<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png"></img>

Now all you need to do is call invert() We do this when the image is clicked.

_x000D_
_x000D_
function invert(){_x000D_
document.getElementById("theImage").style.filter="invert(100%)";_x000D_
}
_x000D_
<h4> Click image to invert </h4>_x000D_
_x000D_
<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png" onClick="invert()" ></img>
_x000D_
_x000D_
_x000D_

We use this on our website

How to substitute shell variables in complex text files

If you really only want to use bash (and sed), then I would go through each of your environment variables (as returned by set in posix mode) and build a bunch of -e 'regex' for sed from that, terminated by a -e 's/\$[a-zA-Z_][a-zA-Z0-9_]*//g', then pass all that to sed.

Perl would do a nicer job though, you have access to the environment vars as an array and you can do executable replacements so you only match any environment variable once.

How can I backup a Docker-container with its data-volumes?

UPDATE 2

Raw single volume backup bash script:

#!/bin/bash
# This script allows you to backup a single volume from a container
# Data in given volume is saved in the current directory in a tar archive.
CONTAINER_NAME=$1
VOLUME_NAME=$2

usage() {
  echo "Usage: $0 [container name] [volume name]"
  exit 1
}

if [ -z $CONTAINER_NAME ]
then
  echo "Error: missing container name parameter."
  usage
fi

if [ -z $VOLUME_NAME ]
then
  echo "Error: missing volume name parameter."
  usage
fi

sudo docker run --rm --volumes-from $CONTAINER_NAME -v $(pwd):/backup busybox tar cvf /backup/backup.tar $VOLUME_NAME

Raw single volume restore bash script:

#!/bin/bash
# This script allows you to restore a single volume from a container
# Data in restored in volume with same backupped path
NEW_CONTAINER_NAME=$1

usage() {
  echo "Usage: $0 [container name]"
  exit 1
}

if [ -z $NEW_CONTAINER_NAME ]
then
  echo "Error: missing container name parameter."
  usage
fi

sudo docker run --rm --volumes-from $NEW_CONTAINER_NAME -v $(pwd):/backup busybox tar xvf /backup/backup.tar

Usage can be like this:

$ volume_backup.sh old_container /srv/www
$ sudo docker stop old_container && sudo docker rm old_container
$ sudo docker run -d --name new_container myrepo/new_container
$ volume_restore.sh new_container

Assumptions are: backup file is named backup.tar, it resides in the same directory as backup and restore script, volume name is the same between containers.

UPDATE

It seems to me that backupping volumes from containers is not different from backupping volumes from data containers.

Volumes are nothing else than paths linked to a container so the process is the same.

I don't know if docker-backup works also for same container volumes but you can use:

sudo docker run --rm --volumes-from yourcontainer -v $(pwd):/backup busybox tar cvf /backup/backup.tar /data

and:

sudo docker run --rm --volumes-from yournewcontainer -v $(pwd):/backup busybox tar xvf /backup/backup.tar

END UPDATE

There is this nice tool available which lets you backup and restore docker volumes containers:

https://github.com/discordianfish/docker-backup

if you have a container linked to some container volumes like this:

$ docker run --volumes-from=my-data-container --name my-server ...

you can backup all the volumes like this:

$ docker-backup store my-server-backup.tar my-server

and restore like this:

$ docker-backup restore my-server-backup.tar

Or you can follow the official way:

How to port data-only volumes from one host to another?

Position DIV relative to another DIV?

You want to use position: absolute while inside the other div.

DEMO

Trying to start a service on boot on Android

As an additional info: BOOT_COMPLETE is sent to applications before external storage is mounted. So if application is installed to external storage it won't receive BOOT_COMPLETE broadcast message.

More details here in section Broadcast Receivers listening for "boot completed"

How to get request URI without context path?

May be you can just use the split method to eliminate the '/myapp' for example:

string[] uris=request.getRequestURI().split("/");
string uri="/"+uri[1]+"/"+uris[2];

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Can you get the column names from a SqlDataReader?

If you want the column names only, you can do:

List<string> columns = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
{
    DataTable dt = reader.GetSchemaTable();
    foreach (DataRow row in dt.Rows)
    {
        columns.Add(row.Field<String>("ColumnName"));
    }
}

But if you only need one row, I like my AdoHelper addition. This addition is great if you have a single line query and you don't want to deal with data table in you code. It's returning a case insensitive dictionary of column names and values.

public static Dictionary<string, string> ExecuteCaseInsensitiveDictionary(string query, string connectionString, Dictionary<string, string> queryParams = null)
{
    Dictionary<string, string> CaseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    try
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;

                // Add the parameters for the SelectCommand.
                if (queryParams != null)
                    foreach (var param in queryParams)
                        cmd.Parameters.AddWithValue(param.Key, param.Value);

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    DataTable dt = new DataTable();
                    dt.Load(reader);
                    foreach (DataRow row in dt.Rows)
                    {
                        foreach (DataColumn column in dt.Columns)
                        {
                            CaseInsensitiveDictionary.Add(column.ColumnName, row[column].ToString());
                        }
                    }
                }
            }
            conn.Close();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return CaseInsensitiveDictionary;
}

SSRS expression to format two decimal places does not show zeros

Actually, I needed the following...get rid of the decimals without rounding so "12.23" needs to show as "12". In SSRS, do not format the number as a percent. Leave the formatting as default (no formatting applied) then in the expression do the following: =Fix(Fields!PctAmt.Value*100))

Multiply the number by 100 then apply the FIX function in SSRS which returns only the integer portion of a number.

Sort objects in ArrayList by date?

list.sort(Comparator.comparing(o -> o.getDateTime()));

The best answer IMHO from Tunaki using Java 8 lambda

How to stash my previous commit?

I solving doing this:

Remove the target commit

git revert --strategy resolve 222

Save commit 222 to patch file

git diff HEAD~2 HEAD~1 > 222.patch

Apply this patch to unstage

patch -p1 < 222.patch

Push to stash

git stash

Remove temp file

rm -f 222.patch

Very simple strategy in my opinion

How to convert an xml string to a dictionary?

I have modified one of the answers to my taste and to work with multiple values with the same tag for example consider the following xml code saved in XML.xml file

     <A>
        <B>
            <BB>inAB</BB>
            <C>
                <D>
                    <E>
                        inABCDE
                    </E>
                    <E>value2</E>
                    <E>value3</E>
                </D>
                <inCout-ofD>123</inCout-ofD>
            </C>
        </B>
        <B>abc</B>
        <F>F</F>
    </A>

and in python

import xml.etree.ElementTree as ET




class XMLToDictionary(dict):
    def __init__(self, parentElement):
        self.parentElement = parentElement
        for child in list(parentElement):
            child.text = child.text if (child.text != None) else  ' '
            if len(child) == 0:
                self.update(self._addToDict(key= child.tag, value = child.text.strip(), dict = self))
            else:
                innerChild = XMLToDictionary(parentElement=child)
                self.update(self._addToDict(key=innerChild.parentElement.tag, value=innerChild, dict=self))

    def getDict(self):
        return {self.parentElement.tag: self}

    class _addToDict(dict):
        def __init__(self, key, value, dict):
            if not key in dict:
                self.update({key: value})
            else:
                identical = dict[key] if type(dict[key]) == list else [dict[key]]
                self.update({key: identical + [value]})


tree = ET.parse('./XML.xml')
root = tree.getroot()
parseredDict = XMLToDictionary(root).getDict()
print(parseredDict)

the output is

{'A': {'B': [{'BB': 'inAB', 'C': {'D': {'E': ['inABCDE', 'value2', 'value3']}, 'inCout-ofD': '123'}}, 'abc'], 'F': 'F'}}

Detect if the device is iPhone X

After looking at all the answers this is what I ended up doing:

Solution (Swift 4.1 compatible)

extension UIDevice {
    static var isIphoneX: Bool {
        var modelIdentifier = ""
        if isSimulator {
            modelIdentifier = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] ?? ""
        } else {
            var size = 0
            sysctlbyname("hw.machine", nil, &size, nil, 0)
            var machine = [CChar](repeating: 0, count: size)
            sysctlbyname("hw.machine", &machine, &size, nil, 0)
            modelIdentifier = String(cString: machine)
        }

        return modelIdentifier == "iPhone10,3" || modelIdentifier == "iPhone10,6"
    }

    static var isSimulator: Bool {
        return TARGET_OS_SIMULATOR != 0
    }
}

Use

if UIDevice.isIphoneX {
    // is iPhoneX
} else {
    // is not iPhoneX
}

Note

Pre Swift 4.1 you can check if the app is running on a simulator like so:

TARGET_OS_SIMULATOR != 0

From Swift 4.1 and onwards you can check if the app is running on a simulator using the Target environment platform condition:

#if targetEnvironment(simulator)
    return true
#else
    return false
#endif

(the older method will still work, but this new method is more future proof)

Send FormData and String Data Together Through JQuery AJAX?

var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
    fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
    fd.append(input.name,input.value);
});
$.ajax({
    url: 'test.php',
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        console.log(data);
    }
});

Added a for loop and changed .serialize() to .serializeArray() for object reference in a .each() to append to the FormData.

Checking if an input field is required using jQuery

The required property is boolean:

$('form#register').find('input').each(function(){
    if(!$(this).prop('required')){
        console.log("NR");
    } else {
        console.log("IR");
    }
});

Reference: HTMLInputElement

Can't find AVD or SDK manager in Eclipse

Chances are that you may be running your eclipse using Java 1.5.

Latest Plugin requires that the JRE be 1.6 or higher. 

You will have to use Eclipse that runs on JRE 1.6

Edit: I had run into same problems. If it is not JRE problem then you can debug this. Follow below procedure:

  1. Window -> show View -> other -> Plugin Development -> Plugin Registry
  2. In the plugin registry search for com.android.ide.eclipse.adt or any other plugin related to android (depending on your installation there maybe 7-8)
  3. Select , Right Click -> Diagnose. This will show the problem why the plugin was not loaded

Extract text from a string

The following regex extract anything between the parenthesis:

PS> $prog = [regex]::match($s,'\(([^\)]+)\)').Groups[1].Value
PS> $prog
SUB RAD MSD 50R III


Explanation (created with RegexBuddy)

Match the character '(' literally «\(»
Match the regular expression below and capture its match into backreference number 1 «([^\)]+)»
   Match any character that is NOT a ) character «[^\)]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character ')' literally «\)»

Check these links:

http://www.regular-expressions.info

http://powershell.com/cs/blogs/tobias/archive/2011/10/27/regular-expressions-are-your-friend-part-1.aspx

http://powershell.com/cs/blogs/tobias/archive/2011/12/02/regular-expressions-are-your-friend-part-2.aspx

http://powershell.com/cs/blogs/tobias/archive/2011/12/02/regular-expressions-are-your-friend-part-3.aspx

jQuery AJAX form data serialize using PHP

Change your code as follows -

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm");
$("#smt").click(function(){
$.ajax({
        type:"POST",
        url:form.attr("action"),
        data:form.serialize(),

        success: function(response){
        if(response == 1){
              $("#err").html("Hi Tony");//updated
        }  else {
            $("#err").html("I dont know you.");//updated
        }
        }
    });
});
});
</script>

PHP -

<?php
$user=$_POST['user'];
$pass=$_POST['pass'];

if($user=="tony")
{
    echo 1;   
}
else
{
    echo 0;    
}
?>

How to get last month/year in java?

private static String getPreviousMonthDate(Date date){
    final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Calendar cal = Calendar.getInstance();  
    cal.setTime(date);  
    cal.set(Calendar.DAY_OF_MONTH, 1);  
    cal.add(Calendar.DATE, -1);

    Date preMonthDate = cal.getTime();  
    return format.format(preMonthDate);
}


private static String getPreToPreMonthDate(Date date){
    final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Calendar cal = Calendar.getInstance();  
    cal.setTime(date);  
    cal.add(Calendar.MONTH, -1);  
    cal.set(Calendar.DAY_OF_MONTH,1);  
    cal.add(Calendar.DATE, -1);  

    Date preToPreMonthDate = cal.getTime();  
    return format.format(preToPreMonthDate);
}

make: *** [ ] Error 1 error

Sometimes you will get lots of compiler outputs with many warnings and no line of output that says "error: you did something wrong here" but there was still an error. An example of this is a missing header file - the compiler says something like "no such file" but not "error: no such file", then it exits with non-zero exit code some time later (perhaps after many more warnings). Make will bomb out with an error message in these cases!

String.strip() in Python

strip does nothing but, removes the the whitespace in your string. If you want to remove the extra whitepace from front and back of your string, you can use strip.

The example string which can illustrate that is this:

In [2]: x = "something \t like     \t this"
In [4]: x.split('\t')
Out[4]: ['something ', ' like     ', ' this']

See, even after splitting with \t there is extra whitespace in first and second items which can be removed using strip in your code.

Insert and set value with max()+1 problems

This is select come insert sequel.

I am trying to get serial_no maximum +1 value and its giving correct value.

SELECT MAX(serial_no)+1 into @var FROM sample.kettle;
Insert into kettle(serial_no,name,age,salary) values (@var,'aaa',23,2000);

Check if an element has event listener on it. No jQuery

You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener method.

Saving binary data as file using JavaScript from a browser

Use FileSaver.js. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it:
     https://github.com/eligrey/FileSaver.js

Minified version is really small at < 2.5KB, gzipped < 1.2KB.

Usage:

/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);

You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
     https://github.com/eligrey/Blob.js

Consider StreamSaver.js if you have files larger than blob's size limitations.

Complete example:

_x000D_
_x000D_
/* Two options_x000D_
 * 1. Get FileSaver.js from here_x000D_
 *     https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
 *     <script src="FileSaver.min.js" />_x000D_
 *_x000D_
 * Or_x000D_
 *_x000D_
 * 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
 *    then a simple implementation of saveAs function can be:_x000D_
 */_x000D_
function saveAs(blob, fileName) {_x000D_
    var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
    var anchorElem = document.createElement("a");_x000D_
    anchorElem.style = "display: none";_x000D_
    anchorElem.href = url;_x000D_
    anchorElem.download = fileName;_x000D_
_x000D_
    document.body.appendChild(anchorElem);_x000D_
    anchorElem.click();_x000D_
_x000D_
    document.body.removeChild(anchorElem);_x000D_
_x000D_
    // On Edge, revokeObjectURL should be called only after_x000D_
    // a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
    setTimeout(function() {_x000D_
        window.URL.revokeObjectURL(url);_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
    // convert base64 string to byte array_x000D_
    var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
    var byteNumbers = new Array(byteCharacters.length);_x000D_
    for (var i = 0; i < byteCharacters.length; i++) {_x000D_
        byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
    }_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
    _x000D_
    // now that we have the byte array, construct the blob from it_x000D_
    var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
    var fileName1 = "cool.gif";_x000D_
    saveAs(blob1, fileName1);_x000D_
_x000D_
    // saving text file_x000D_
    var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
    var fileName2 = "cool.txt";_x000D_
    saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_


Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js for supporting IE 11).
You can also save from a canvas element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.

Demos: https://eligrey.com/demos/FileSaver.js/

Blog post by author of FileSaver.js: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers

Note 2: Failed to execute 'atob' on 'Window'

Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
                See http://caniuse.com/#search=blob

Note 4: IE < 10 support (I've not tested this part):
                https://github.com/eligrey/FileSaver.js#ie--10
                https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476

Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html

Note 5: Creating a BLOB from a Base64 string in JavaScript

Note 6: FileSaver.js examples: https://github.com/eligrey/FileSaver.js#examples

Split a large dataframe into a list of data frames based on common value in column

From version 0.8.0, dplyr offers a handy function called group_split():

# On sample data from @Aus_10

df %>%
  group_split(g)

[[1]]
# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     2.04      0.627 A    
 2     0.530    -0.703 A    
 3    -0.475     0.541 A    
 4     1.20     -0.565 A    
 5    -0.380    -0.126 A    
 6     1.25     -1.69  A    
 7    -0.153    -1.02  A    
 8     1.52     -0.520 A    
 9     0.905    -0.976 A    
10     0.517    -0.535 A    
# … with 15 more rows

[[2]]
# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     1.61      0.858 B    
 2     1.05     -1.25  B    
 3    -0.440    -0.506 B    
 4    -1.17      1.81  B    
 5     1.47     -1.60  B    
 6    -0.682    -0.726 B    
 7    -2.21      0.282 B    
 8    -0.499     0.591 B    
 9     0.711    -1.21  B    
10     0.705     0.960 B    
# … with 15 more rows

To not include the grouping column:

df %>%
 group_split(g, keep = FALSE)

Case insensitive string as HashMap key

You can use CollationKey objects instead of strings:

Locale locale = ...;
Collator collator = Collator.getInstance(locale);
collator.setStrength(Collator.SECONDARY); // Case-insensitive.
collator.setDecomposition(Collator.FULL_DECOMPOSITION);

CollationKey collationKey = collator.getCollationKey(stringKey);
hashMap.put(collationKey, value);
hashMap.get(collationKey);

Use Collator.PRIMARY to ignore accent differences.

The CollationKey API does not guarantee that hashCode() and equals() are implemented, but in practice you'll be using RuleBasedCollationKey, which does implement these. If you're paranoid, you can use a TreeMap instead, which is guaranteed to work at the cost of O(log n) time instead of O(1).

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

How does EL empty operator work in JSF?

Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable using not empty operator on my dataModel that extends javax.faces.model.ListDataModel

Code sample:

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;

public class EntityDataModel extends ListDataModel<Entity> implements
        Collection<Entity>, SelectableDataModel<Entity>, Serializable {

    public EntityDataModel(List<Entity> data) { super(data); }

    @Override
    public Entity getRowData(String rowKey) {
        // In a real app, a more efficient way like a query by rowKey should be
        // implemented to deal with huge data
        List<Entity> entitys = (List<Entity>) getWrappedData();
        for (Entity entity : entitys) {
            if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
        }
        return null;
    }

    @Override
    public Object getRowKey(Entity entity) {
        return entity.getId();
    }

    @Override
    public boolean isEmpty() {
        List<Entity> entity = (List<Entity>) getWrappedData();
        return (entity == null) || entity.isEmpty();
    }
    // ... other not implemented methods of Collection...
}

Is there functionality to generate a random character in Java?

I use this:

char uppercaseChar = (char) ((int)(Math.random()*100)%26+65);

char lowercaseChar = (char) ((int)(Math.random()*1000)%26+97);

How do I minimize the command prompt from my bat file

If you want to start the batch for Win-Run / autostart, I found I nice solution here https://www.computerhope.com/issues/ch000932.htm & https://superuser.com/questions/364799/how-to-run-the-command-prompt-minimized

cmd.exe /c start /min myfile.bat ^& exit
  • the cmd.exe is needed as start is no windows command that can be executed outside a batch
  • /c = exit after the start is finished
  • the ^& exit part ensures that the window closes even if the batch does not end with exit

However, the initial cmd is still not minimized.

Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

With Swift 3, according to your needs, you may choose one of the two following ways to solve your problem.


1. Display the difference between two dates to the user

You can use a DateComponentsFormatter to create strings for your app’s interface. DateComponentsFormatter has a maximumUnitCount property with the following declaration:

var maximumUnitCount: Int { get set }

Use this property to limit the number of units displayed in the resulting string. For example, with this property set to 2, instead of “1h 10m, 30s”, the resulting string would be “1h 10m”. Use this property when you are constrained for space or want to round up values to the nearest large unit.

By setting maximumUnitCount's value to 1, you are guaranteed to display the difference in only one DateComponentsFormatter's unit (years, months, days, hours or minutes).

The Playground code below shows how to display the difference between two dates:

import Foundation

let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)

let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [NSCalendar.Unit.year, .month, .day, .hour, .minute]
dateComponentsFormatter.maximumUnitCount = 1
dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full
let timeDifference = dateComponentsFormatter.string(from: oldDate, to: newDate)

print(String(reflecting: timeDifference)) // prints Optional("5 hours")

Note that DateComponentsFormatter rounds up the result. Therefore, a difference of 4 hours and 30 minutes will be displayed as 5 hours.

If you need to repeat this operation, you can refactor your code:

import Foundation

struct Formatters {

    static let dateComponentsFormatter: DateComponentsFormatter = {
        let dateComponentsFormatter = DateComponentsFormatter()
        dateComponentsFormatter.allowedUnits = [NSCalendar.Unit.year, .month, .day, .hour, .minute]
        dateComponentsFormatter.maximumUnitCount = 1
        dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full
        return dateComponentsFormatter
    }()

}

extension Date {
    
    func offset(from: Date) -> String? {
        return Formatters.dateComponentsFormatter.string(from: oldDate, to: self)
    }
    
}

let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)

let timeDifference = newDate.offset(from: oldDate)
print(String(reflecting: timeDifference)) // prints Optional("5 hours")

2. Get the difference between two dates without formatting

If you don't need to display with formatting the difference between two dates to the user, you can use Calendar. Calendar has a method dateComponents(_:from:to:) that has the following declaration:

func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents

Returns the difference between two dates.

The Playground code below that uses dateComponents(_:from:to:) shows how to retrieve the difference between two dates by returning the difference in only one type of Calendar.Component (years, months, days, hours or minutes).

import Foundation

let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)

let descendingOrderedComponents = [Calendar.Component.year, .month, .day, .hour, .minute]
let dateComponents = Calendar.current.dateComponents(Set(descendingOrderedComponents), from: oldDate, to: newDate)
let arrayOfTuples = descendingOrderedComponents.map { ($0, dateComponents.value(for: $0)) }

for (component, value) in arrayOfTuples {
    if let value = value, value > 0 {
        print(component, value) // prints hour 4
        break
    }
}

If you need to repeat this operation, you can refactor your code:

import Foundation

extension Date {
    
    func offset(from: Date) -> (Calendar.Component, Int)? {
        let descendingOrderedComponents = [Calendar.Component.year, .month, .day, .hour, .minute]
        let dateComponents = Calendar.current.dateComponents(Set(descendingOrderedComponents), from: from, to: self)
        let arrayOfTuples = descendingOrderedComponents.map { ($0, dateComponents.value(for: $0)) }
        
        for (component, value) in arrayOfTuples {
            if let value = value, value > 0 {
                return (component, value)
            }
        }
        
        return nil
    }

}

let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)

if let (component, value) = newDate.offset(from: oldDate) {
    print(component, value) // prints hour 4
}

How to find the cumulative sum of numbers in a list?

I did a bench-mark of the top two answers with Python 3.4 and I found itertools.accumulate is faster than numpy.cumsum under many circumstances, often much faster. However, as you can see from the comments, this may not always be the case, and it's difficult to exhaustively explore all options. (Feel free to add a comment or edit this post if you have further benchmark results of interest.)

Some timings...

For short lists accumulate is about 4 times faster:

from timeit import timeit

def sum1(l):
    from itertools import accumulate
    return list(accumulate(l))

def sum2(l):
    from numpy import cumsum
    return list(cumsum(l))

l = [1, 2, 3, 4, 5]

timeit(lambda: sum1(l), number=100000)
# 0.4243644131347537
timeit(lambda: sum2(l), number=100000)
# 1.7077815784141421

For longer lists accumulate is about 3 times faster:

l = [1, 2, 3, 4, 5]*1000
timeit(lambda: sum1(l), number=100000)
# 19.174508565105498
timeit(lambda: sum2(l), number=100000)
# 61.871223849244416

If the numpy array is not cast to list, accumulate is still about 2 times faster:

from timeit import timeit

def sum1(l):
    from itertools import accumulate
    return list(accumulate(l))

def sum2(l):
    from numpy import cumsum
    return cumsum(l)

l = [1, 2, 3, 4, 5]*1000

print(timeit(lambda: sum1(l), number=100000))
# 19.18597290944308
print(timeit(lambda: sum2(l), number=100000))
# 37.759664884768426

If you put the imports outside of the two functions and still return a numpy array, accumulate is still nearly 2 times faster:

from timeit import timeit
from itertools import accumulate
from numpy import cumsum

def sum1(l):
    return list(accumulate(l))

def sum2(l):
    return cumsum(l)

l = [1, 2, 3, 4, 5]*1000

timeit(lambda: sum1(l), number=100000)
# 19.042188624851406
timeit(lambda: sum2(l), number=100000)
# 35.17324400227517

Handling MySQL datetimes and timestamps in Java

BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.

Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.

When writing datetime value to sql db

    //Convert the time into UTC and build Timestamp object.
    Timestamp ts = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")));
    //use setTimestamp on preparedstatement
    preparedStatement.setTimestamp(1, ts);

When reading the value back from DB into java,

  1. Read it as it is in java.sql.Timestamp type.
  2. Decorate the DateTime value as time in UTC timezone using atZone method in LocalDateTime class.
  3. Then, change it to your desired timezone. Here I am changing it to Toronto timezone.

    ResultSet resultSet = preparedStatement.executeQuery();
    resultSet.next();
    Timestamp timestamp = resultSet.getTimestamp(1);
    ZonedDateTime timeInUTC = timestamp.toLocalDateTime().atZone(ZoneId.of("UTC"));
    LocalDateTime timeInToronto = LocalDateTime.ofInstant(timeInUTC.toInstant(), ZoneId.of("America/Toronto"));
    

Hibernate vs JPA vs JDO - pros and cons of each?

Some notes:

  • JDO and JPA are both specifications, not implementations.
  • The idea is you can swap JPA implementations, if you restrict your code to use standard JPA only. (Ditto for JDO.)
  • Hibernate can be used as one such implementation of JPA.
  • However, Hibernate provides a native API, with features above and beyond that of JPA.

IMO, I would recommend Hibernate.


There have been some comments / questions about what you should do if you need to use Hibernate-specific features. There are many ways to look at this, but my advice would be:

  • If you are not worried by the prospect of vendor tie-in, then make your choice between Hibernate, and other JPA and JDO implementations including the various vendor specific extensions in your decision making.

  • If you are worried by the prospect of vendor tie-in, and you can't use JPA without resorting to vendor specific extensions, then don't use JPA. (Ditto for JDO).

In reality, you will probably need to trade-off how much you are worried by vendor tie-in versus how much you need those vendor specific extensions.

And there are other factors too, like how well you / your staff know the respective technologies, how much the products will cost in licensing, and whose story you believe about what is going to happen in the future for JDO and JPA.

Serialize Property as Xml Attribute in Element

You will need wrapper classes:

public class SomeIntInfo
{
    [XmlAttribute]
    public int Value { get; set; }
}

public class SomeStringInfo
{
    [XmlAttribute]
    public string Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeStringInfo SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeIntInfo SomeInfo { get; set; }
}

or a more generic approach if you prefer:

public class SomeInfo<T>
{
    [XmlAttribute]
    public T Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeInfo<string> SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeInfo<int> SomeInfo { get; set; }
}

And then:

class Program
{
    static void Main()
    {
        var model = new SomeModel
        {
            SomeString = new SomeInfo<string> { Value = "testData" },
            SomeInfo = new SomeInfo<int> { Value = 5 }
        };
        var serializer = new XmlSerializer(model.GetType());
        serializer.Serialize(Console.Out, model);
    }
}

will produce:

<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomeStringElementName Value="testData" />
  <SomeInfoElementName Value="5" />
</SomeModel>

How to make div go behind another div?

To answer the question in a general manner:

Using z-index will allow you to control this. see z-index at csstricks.

The element of higher z-index will be displayed on top of elements of lower z-index.

For instance, take the following HTML:

<div id="first">first</div>
<div id="second">second</div>

If I have the following CSS:

#first {
    position: fixed;
    z-index: 2;
}

#second {
    position: fixed;
    z-index: 1;
}

#first wil be on top of #second.

But specifically in your case:

The div element is a child of the div that you wish to put in front. This is not logically possible.

Git: How to remove remote origin from Git repo

you can try this out,if you want to remove origin and then add it:

git remote remove origin

then:

git remote add origin http://your_url_here

How do you create optional arguments in php?

The default value of the argument must be a constant expression. It can't be a variable or a function call.

If you need this functionality however:

function foo($foo, $bar = false)
{
    if(!$bar)
    {
        $bar = $foo;
    }
}

Assuming $bar isn't expected to be a boolean of course.

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I was facing the same issue while i was using "jdk-10.0.1_windows-x64_bin" and eclipse-jee-oxygen-3a-win32-x86_64 on Windows 64 bit Operating System.

But Finally i resolved this issue by changing my jdk to "jdk-8u172-windows-x64", Now its working fine. @Thanks

What is the "Upgrade-Insecure-Requests" HTTP header?

Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests response header, indicating that the browser supports it (and in fact prefers it).

It took me 30mins of Googling, but I finally found it buried in the W3 spec.

The confusion comes because the header in the spec was HTTPS: 1, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:

"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842

Their fix was to rename it to Upgrade-Insecure-Requests: 1, and the spec has since been updated to match.

Anyway, here is the explanation from the W3 spec (as it appeared at the time)...

The HTTPS HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide.

...

When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.

When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a Strict-Transport-Security header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].

Calculate the display width of a string in Java

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For example, if you have a Graphics variable called g, you'd use:

int width = g.getFontMetrics().stringWidth(text);

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

Select rows where column is null

select Column from Table where Column is null;

Android Lint contentDescription warning

Disabling Lint warnings will easily get you into trouble later on. You're better off just specifying contentDescription for all of your ImageViews. If you don't need a description, then just use:

android:contentDescription="@null"

How to run python script in webpage

With your current requirement this would work :

    def start_html():
        return '<html>'

    def end_html():
        return '</html>'

    def print_html(text):
        text = str(text)
        text = text.replace('\n', '<br>')
        return '<p>' + str(text) + '</p>'
if __name__ == '__main__':
        webpage_data =  start_html()
        webpage_data += print_html("Hi Welcome to Python test page\n")
        webpage_data += fd.write(print_html("Now it will show a calculation"))
        webpage_data += print_html("30+2=")
        webpage_data += print_html(30+2)
        webpage_data += end_html()
        with open('index.html', 'w') as fd: fd.write(webpage_data)

open the index.html and you will see what you want

Start HTML5 video at a particular position when loading?

You have to wait until the browser knows the duration of the video before you can seek to a particular time. So, I think you want to wait for the 'loadedmetadata' event something like this:

document.getElementById('vid1').addEventListener('loadedmetadata', function() {
  this.currentTime = 50;
}, false);

How to fill Matrix with zeros in OpenCV?

You can choose filling zero data or create zero Mat.

  1. Filling zero data with setTo():

    img.setTo(Scalar::all(0));
    
  2. Create zero data with zeros():

    img = zeros(img.size(), img.type());
    

The img changes address of memory.

Split string in Lua?

I used the above examples to craft my own function. But the missing piece for me was automatically escaping magic characters.

Here is my contribution:

function split(text, delim)
    -- returns an array of fields based on text and delimiter (one character only)
    local result = {}
    local magic = "().%+-*?[]^$"

    if delim == nil then
        delim = "%s"
    elseif string.find(delim, magic, 1, true) then
        -- escape magic
        delim = "%"..delim
    end

    local pattern = "[^"..delim.."]+"
    for w in string.gmatch(text, pattern) do
        table.insert(result, w)
    end
    return result
end

How to Set AllowOverride all

If you are using Linux you may edit the code in the directory of

/etc/httpd/conf/httpd.conf

now, here find the code line kinda like

# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
    AllowOverride None
#
# Controls who can get stuff from this server.
#
    Order allow,deny
    Allow from all

</Directory>

Change the AllowOveride None to AllowOveride All

Now now you can set any kind of rule in your .httacess file inside your directories if any other operating system just try to find the file of httpd.conf and edit it.

Elegant way to create empty pandas DataFrame with NaN of type float

Hope this can help!

 pd.DataFrame(np.nan, index = np.arange(<num_rows>), columns = ['A'])

Append an int to a std::string

The std::string::append() method expects its argument to be a NULL terminated string (char*).

There are several approaches for producing a string containg an int:

  • std::ostringstream

    #include <sstream>
    
    std::ostringstream s;
    s << "select logged from login where id = " << ClientID;
    std::string query(s.str());
    
  • std::to_string (C++11)

    std::string query("select logged from login where id = " +
                      std::to_string(ClientID));
    
  • boost::lexical_cast

    #include <boost/lexical_cast.hpp>
    
    std::string query("select logged from login where id = " +
                      boost::lexical_cast<std::string>(ClientID));
    

JavaScript Nested function

_x000D_
_x000D_
function foo() {_x000D_
  function bar() {_x000D_
    return 1;_x000D_
  }_x000D_
}_x000D_
bar();
_x000D_
_x000D_
_x000D_
Will throw an error. Since bar is defined inside foo, bar will only be accessible inside foo.
To use bar you need to run it inside foo.

_x000D_
_x000D_
function foo() {_x000D_
  function bar() {_x000D_
    return 1;_x000D_
  }_x000D_
  bar();_x000D_
}
_x000D_
_x000D_
_x000D_

How to change text color and console color in code::blocks?

You should define the function textcolor before. Because textcolor is not a standard function in C.

void textcolor(unsigned short color) {
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hcon,color);
}

How to append one file to another in Linux from the shell?

Another solution:

cat file1 | tee -a file2

tee has the benefit that you can append to as many files as you like, for example:

cat file1 | tee -a file2 file3 file3

will append the contents of file1 to file2, file3 and file4.

From the man page:

-a, --append
       append to the given FILEs, do not overwrite

How to delete an SVN project from SVN repository

Disposing of a Working Copy

Subversion doesn't track either the state or the existence of working copies on the server, so there's no server overhead to keeping working copies around. Likewise, there's no need to let the server know that you're going to delete a working copy.

If you're likely to use a working copy again, there's nothing wrong with just leaving it on disk until you're ready to use it again, at which point all it takes is an svn update to bring it up to date and ready for use.

However, if you're definitely not going to use a working copy again, you can safely delete the entire thing using whatever directory removal capabilities your operating system offers. We recommend that before you do so you run svn status and review any files listed in its output that are prefixed with a ? to make certain that they're not of importance.

from: http://svnbook.red-bean.com/en/1.7/svn.tour.cleanup.html

Pandas split column of lists into multiple columns

Much simpler solution:

pd.DataFrame(df2["teams"].to_list(), columns=['team1', 'team2'])

Yields,

  team1 team2
-------------
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG
7    SF   NYG

If you wanted to split a column of delimited strings rather than lists, you could similarly do:

pd.DataFrame(df["teams"].str.split('<delim>', expand=True).values,
             columns=['team1', 'team2'])

What is the iBeacon Bluetooth Profile

iBeacon Profile contains 31 Bytes which includes the followings

  1. Prefix - 9 Bytes - which include s the adv data and Manufacturer data
  2. UUID - 16 Bytes
  3. Major - 2 Bytes
  4. Minor - 2 Bytes
  5. TxPower - 1 Byte

enter image description here

How to check if input date is equal to today's date?

Date.js is a handy library for manipulating and formatting dates. It can help in this situation.

How to remove package using Angular CLI?

You can use npm uninstall <package-name> will remove it from your package.json file and from node_modules.

If you do ng help command, you will see that there is no ng remove/delete supported command. So, basically you cannot revert the ng add behavior yet.

Removing MySQL 5.7 Completely

Run these commands in the terminal:

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo apt-get autoremove

sudo apt-get autoclean

Run these commands separately as each command requires confirmation & if run as a block, the command below the one currently running will cancel the confirmation (leading to the command not being run).

Please refer to How do I uninstall Mysql?

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

In my case, this was caused by custom manifest entries added by the maven-jar-plugin.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <archive>
            <index>true</index>
            <manifest>
                <addClasspath>true</addClasspath>
            </manifest>
            <manifestEntries>
                <git>${buildNumber}</git>
                <build-time>${timestamp}</build-time>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

Removing the following entries fixed the problem

<index>true</index>
<manifest>
    <addClasspath>true</addClasspath>
</manifest>

What is the meaning of {...this.props} in Reactjs

You will use props in your child component

for example

if your now component props is

{
   booking: 4,
   isDisable: false
}

you can use this props in your child compoenet

 <div {...this.props}> ... </div>

in you child component, you will receive all your parent props.

How to properly upgrade node using nvm

Here are the steps that worked for me for Ubuntu OS and using nvm

Go to nodejs website and get the last LTS version (for example in your current dater the version will be: x.y.z)

nvm install x.y.z
# In my case current version is: 14.15.4 (and had 14.15.3)

After that, execute nvm list and you will get list of node versions installed by nvm.

Now you need to switch to the default last installed one by executing:

nvm alias default x.y.z

List again or run nvm --version to check: enter image description here

Update: sometimes even if i go over the steps above it doesn't work, so what i did was removing the symbolic links in /usr/local/bin

cd /usr/local/bin
sudo rm node npm npx

And relink:

sudo ln -s $(which node) /usr/local/bin/node
sudo ln -s $(which npm) /usr/local/bin/npm
sudo ln -s $(which npx) /usr/local/bin/npx

how to use javascript Object.defineProperty

Basically, defineProperty is a method that takes in 3 parameters - an object, a property, and a descriptor. What is happening in this particular call is the "health" property of the player object is getting assigned to 10 plus 15 times that player object's level.

Calculate difference in keys contained in two Python dictionaries

The top answer by hughdbrown suggests using set difference, which is definitely the best approach:

diff = set(dictb.keys()) - set(dicta.keys())

The problem with this code is that it builds two lists just to create two sets, so it's wasting 4N time and 2N space. It's also a bit more complicated than it needs to be.

Usually, this is not a big deal, but if it is:

diff = dictb.keys() - dicta

Python 2

In Python 2, keys() returns a list of the keys, not a KeysView. So you have to ask for viewkeys() directly.

diff = dictb.viewkeys() - dicta

For dual-version 2.7/3.x code, you're hopefully using six or something similar, so you can use six.viewkeys(dictb):

diff = six.viewkeys(dictb) - dicta

In 2.4-2.6, there is no KeysView. But you can at least cut the cost from 4N to N by building your left set directly out of an iterator, instead of building a list first:

diff = set(dictb) - dicta

Items

I have a dictA which can be the same as dictB or may have some keys missing as compared to dictB or else the value of some keys might be different

So you really don't need to compare the keys, but the items. An ItemsView is only a Set if the values are hashable, like strings. If they are, it's easy:

diff = dictb.items() - dicta.items()

Recursive diff

Although the question isn't directly asking for a recursive diff, some of the example values are dicts, and it appears the expected output does recursively diff them. There are already multiple answers here showing how to do that.

How to initialize a vector of vectors on a struct?

Like this:

#include <vector>

// ...

std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));

(Pre-C++11 you need to leave whitespace between the angled brackets.)

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

I also faced the same issue today in my running code. Well, I found a lot of answers here. But the important thing I want to mention is that this error message is quite ambiguous and doesn't explicitly point out the exact error.

Some faced it due to browser extensions, some due to incorrect URL patterns and I faced this due to an error in my formGroup instance used in a pop-up in that screen. So, I would suggest everyone that before making any new changes in your code, please debug your code and verify that you don't have any such errors. You will certainly find the actual reason by debugging.

If nothing else works then check your URL as that is the most common reason for this issue.

How do you set the Content-Type header for an HttpClient request?

You can use this it will be work!

HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get,"URL");
msg.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

HttpResponseMessage response = await _httpClient.SendAsync(msg);
response.EnsureSuccessStatusCode();

string json = await response.Content.ReadAsStringAsync();

How do I count unique visitors to my site?

$user_ip=$_SERVER['REMOTE_ADDR'];

$check_ip = mysql_query("select userip from pageview where page='yourpage'  and userip='$user_ip'");
if(mysql_num_rows($check_ip)>=1)
{

}
else
{
  $insertview = mysql_query("insert into pageview values('','yourpage','$user_ip')");

  $updateview = mysql_query("update totalview set totalvisit = totalvisit+1 where page='yourpage' ");
}

code from talkerscode official tutorial if you have any problem http://talkerscode.com/webtricks/create-a-simple-pageviews-counter-using-php-and-mysql.php

How to find the first and second maximum number?

OK I found it.

=LARGE($E$4:$E$9;A12)

=large(array, k)

Array Required. The array or range of data for which you want to determine the k-th largest value.

K Required. The position (from the largest) in the array or cell range of data to return.

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

'uint32_t' does not name a type

just navigate to /usr/include/x86_64-linux-gnu/bits open stdint-uintn.h and add these lines

typedef __uint8_t uint8_t;
typedef __uint16_t uint16_t;
typedef __uint32_t uint32_t;
typedef __uint64_t uint64_t;

again open stdint-intn.h and add

typedef __int8_t int8_t;
typedef __int16_t int16_t;
typedef __int32_t int32_t;
typedef __int64_t int64_t;

note these lines are already present just copy and add the missing lines cheerss..

Convert alphabet letters to number in Python

>>> [str(ord(string.lower(c)) - ord('a') + 1) for c in string.letters]
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17',
'18', '19', '20', '21', '22', '23', '24', '25', '26', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24',
 '25', '26']

Reading values from DataTable

For VB.Net is

        Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "database path")
        Dim cmd As New OleDb.OleDbCommand
        Dim dt As New DataTable
        Dim da As New OleDb.OleDbDataAdapter
        con.Open()
        cmd.Connection = con
        cmd.CommandText = sql
        da.SelectCommand = cmd

        da.Fill(dt)

        For i As Integer = 0 To dt.Rows.Count
            someVar = dt.Rows(i)("fieldName")
        Next

How do I set the icon for my application in visual studio 2008?

The important thing is that the icon you want to be displayed as the application icon ( in the title bar and in the task bar ) must be the FIRST icon in the resource script file

The file is in the res folder and is named (applicationName).rc

/////////////////////////////////////////////////////////////////////////////
//
// Icon
//

// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
(icon ID )          ICON                    "res\\filename.ico"

SSIS Convert Between Unicode and Non-Unicode Error

Add Data Conversion transformations to convert string columns from non-Unicode (DT_STR) to Unicode (DT_WSTR) strings.

You need to do this for all the string columns...

CSS checkbox input styling

As IE6 doesn't understand attribute selectors, you can combine a script only seen by IE6 (with conditional comments) and jQuery or IE7.js by Dean Edwards.

IE7(.js) is a JavaScript library to make Microsoft Internet Explorer behave like a standards-compliant browser. It fixes many HTML and CSS issues and makes transparent PNG work correctly under IE5 and IE6.

The choice of using classes or jQuery or IE7.js depends on your likes and dislikes and your other needs (maybe PNG-24 transparency throughout your site without having to rely on PNG-8 with complete transparency that fallbacks to 1-bit transparency on IE6 - only created by Fireworks and pngnq, etc)

How do you calculate log base 2 in Java for integers?

To add to x4u answer, which gives you the floor of the binary log of a number, this function return the ceil of the binary log of a number :

public static int ceilbinlog(int number) // returns 0 for bits=0
{
    int log = 0;
    int bits = number;
    if ((bits & 0xffff0000) != 0) {
        bits >>>= 16;
        log = 16;
    }
    if (bits >= 256) {
        bits >>>= 8;
        log += 8;
    }
    if (bits >= 16) {
        bits >>>= 4;
        log += 4;
    }
    if (bits >= 4) {
        bits >>>= 2;
        log += 2;
    }
    if (1 << log < number)
        log++;
    return log + (bits >>> 1);
}

PHP foreach change original array values

Try this

function checkForm($fields){
        foreach($fields as $field){
            if($field['required'] && strlen($_POST[$field['name']]) <= 0){
                $field['value'] = "Some error";
            }
        }
        return $field;
    }

Parallel.ForEach vs Task.Factory.StartNew

Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.

Java 8 Stream API to find Unique Object matching a property value

Guava API provides MoreCollectors.onlyElement() which is a collector that takes a stream containing exactly one element and returns that element.

The returned collector throws an IllegalArgumentException if the stream consists of two or more elements, and a NoSuchElementException if the stream is empty.

Refer the below code for usage:

import static com.google.common.collect.MoreCollectors.onlyElement;

Person matchingPerson = objects.stream
                        .filter(p -> p.email().equals("testemail"))
                        .collect(onlyElement());

Facebook Callback appends '#_=_' to Return URL

You can also specify your own hash on the redirect_uri parameter for the Facebook callback, which might be helpful in certain circumstances e.g. /api/account/callback#home. When you are redirected back, it'll at least be a hash that corresponds to a known route if you are using backbone.js or similar (not sure about jquery mobile).

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

display HTML page after loading complete

try using javascript for this! Seems like its the best and easiest way to do this. You'll get inbuilt funcn to execute a html code only after HTML page loads completely.

or else you may use state based programming where an event occurs at a particular state of the browser..

Write to Windows Application Event Log

As stated in MSDN (eg. https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog(v=vs.110).aspx ), checking an non existing source and creating a source requires admin privilege.

It is however possible to use the source "Application" without. In my test under Windows 2012 Server r2, I however get the following log entry using "Application" source:

The description for Event ID xxxx from source Application cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer. If the event originated on another computer, the display information had to be saved with the event. The following information was included with the event: {my event entry message} the message resource is present but the message is not found in the string/message table

I defined the following method to create the source:

    private string CreateEventSource(string currentAppName)
    {
        string eventSource = currentAppName;
        bool sourceExists;
        try
        {
            // searching the source throws a security exception ONLY if not exists!
            sourceExists = EventLog.SourceExists(eventSource);
            if (!sourceExists)
            {   // no exception until yet means the user as admin privilege
                EventLog.CreateEventSource(eventSource, "Application");
            }
        }
        catch (SecurityException)
        {
            eventSource = "Application";
        }

        return eventSource;
    }

I am calling it with currentAppName = AppDomain.CurrentDomain.FriendlyName

It might be possible to use the EventLogPermission class instead of this try/catch but not sure we can avoid the catch.

It is also possible to create the source externally, e.g in elevated Powershell:

New-EventLog -LogName Application -Source MyApp

Then, using 'MyApp' in the method above will NOT generate exception and the EventLog can be created with that source.

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

How to make a HTTP request using Ruby on Rails?

Here is the code that works if you are making a REST api call behind a proxy:

require "uri"
require 'net/http'

proxy_host = '<proxy addr>'
proxy_port = '<proxy_port>'
proxy_user = '<username>'
proxy_pass = '<password>'

uri = URI.parse("https://saucelabs.com:80/rest/v1/users/<username>")
proxy = Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass)

req = Net::HTTP::Get.new(uri.path)
req.basic_auth(<sauce_username>,<sauce_password>)

result = proxy.start(uri.host,uri.port) do |http|
http.request(req)
end

puts result.body

How to refresh an IFrame using Javascript?

2017:

If it in on same domain just :

iframe.contentWindow.location.reload();

will work.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Easy pretty printing of floats in python?

print "[%s]"%", ".join(map(str,yourlist))

This will avoid the rounding errors in the binary representation when printed, without introducing a fixed precision constraint (like formating with "%.2f"):

[9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.0793303]

Hide/encrypt password in bash file to stop accidentally seeing it

There's a more convenient way to store passwords in a script but you will have to encrypt and obfuscate the script so that it cannot be read. In order to successfully encrypt and obfuscate a shell script and actually have that script be executable, try copying and pasting it here:

http://www.kinglazy.com/shell-script-encryption-kinglazy-shieldx.htm

On the above page, all you have to do is submit your script and give the script a proper name, then hit the download button. A zip file will be generated for you. Right click on the download link and copy the URL you're provided. Then, go to your UNIX box and perform the following steps.

Installation:

1. wget link-to-the-zip-file
2. unzip the-newly-downloaded-zip-file
3. cd /tmp/KingLazySHIELD
4. ./install.sh /var/tmp/KINGLAZY/SHIELDX-(your-script-name) /home/(your-username) -force

What the above install command will do for you is:

  1. Install the encrypted version of your script in the directory /var/tmp/KINGLAZY/SHIELDX-(your-script-name).
  2. It'll place a link to this encrypted script in whichever directory you specify in replacement of /home/(your-username) - that way, it allows you to easily access the script without having to type the absolute path.
  3. Ensures NO ONE can modify the script - Any attempts to modify the encrypted script will render it inoperable...until those attempts are stopped or removed. It can even be configured to notify you whenever someone tries to do anything with the script other than run it...i.e. hacking or modification attempts.
  4. Ensures absolutely NO ONE can make copies of it. No one can copy your script to a secluded location and try to screw around with it to see how it works. All copies of the script must be links to the original location which you specified during install (step 4).

NOTE:

This does not work for interactive scripts that prompts and waits on the user for a response. The values that are expected from the user should be hard-coded into the script. The encryption ensures no one can actually see those values so you need not worry about that.

RELATION:

The solution provided in this post answers your problem in the sense that it encrypts the actual script containing the password that you wanted to have encrypted. You get to leave the password as is (unencrypted) but the script that the password is in is so deeply obfuscated and encrypted that you can rest assured no one will be able to see it. And if attempts are made to try to pry into the script, you will receive email notifications about them.

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try figsize param in df.plot(figsize=(width,height)):

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(3,3));

enter image description here

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(5,3));

enter image description here

The size in figsize=(5,3) is given in inches per (width, height)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html

App.settings - the Angular way?

I find this Angular How-to: Editable Config Files from Microsoft Dev blogs being the best solution. You can configure dev build settings or prod build settings.

git still shows files as modified after adding to .gitignore

Simply add git rm -r --cached <folder_name/file_name>

Sometimes, you update the .gitignore file after the commit command of files. So, the files get cached in the memory. To remove the cached files, use the above command.

Open window in JavaScript with HTML inserted

Here's how to do it with an HTML Blob, so that you have control over the entire HTML document:

https://codepen.io/trusktr/pen/mdeQbKG?editors=0010

This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):

_x000D_
_x000D_
const winHtml = `<!DOCTYPE html>_x000D_
    <html>_x000D_
        <head>_x000D_
            <title>Window with Blob</title>_x000D_
        </head>_x000D_
        <body>_x000D_
            <h1>Hello from the new window!</h1>_x000D_
        </body>_x000D_
    </html>`;_x000D_
_x000D_
const winUrl = URL.createObjectURL(_x000D_
    new Blob([winHtml], { type: "text/html" })_x000D_
);_x000D_
_x000D_
const win = window.open(_x000D_
    winUrl,_x000D_
    "win",_x000D_
    `width=800,height=400,screenX=200,screenY=200`_x000D_
);
_x000D_
_x000D_
_x000D_

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

I don't like all the solutions that use magic numbers like 97 or 36.

const A = 'A'.charCodeAt(0);

let numberToCharacter = number => String.fromCharCode(A + number);

let characterToNumber = character => character.charCodeAt(0) - A;

this assumes uppercase letters and starts 'A' at 0.

Read/write files within a Linux kernel module

Since version 4.14 of Linux kernel, vfs_read and vfs_write functions are no longer exported for use in modules. Instead, functions exclusively for kernel's file access are provided:

# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);

# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
            loff_t *pos);

Also, filp_open no longer accepts user-space string, so it can be used for kernel access directly (without dance with set_fs).

Rotation of 3D vector?

Here is an elegant method using quaternions that are blazingly fast; I can calculate 10 million rotations per second with appropriately vectorised numpy arrays. It relies on the quaternion extension to numpy found here.

Quaternion Theory: A quaternion is a number with one real and 3 imaginary dimensions usually written as q = w + xi + yj + zk where 'i', 'j', 'k' are imaginary dimensions. Just as a unit complex number 'c' can represent all 2d rotations by c=exp(i * theta), a unit quaternion 'q' can represent all 3d rotations by q=exp(p), where 'p' is a pure imaginary quaternion set by your axis and angle.

We start by converting your axis and angle to a quaternion whose imaginary dimensions are given by your axis of rotation, and whose magnitude is given by half the angle of rotation in radians. The 4 element vectors (w, x, y, z) are constructed as follows:

import numpy as np
import quaternion as quat

v = [3,5,0]
axis = [4,4,1]
theta = 1.2 #radian

vector = np.array([0.] + v)
rot_axis = np.array([0.] + axis)
axis_angle = (theta*0.5) * rot_axis/np.linalg.norm(rot_axis)

First, a numpy array of 4 elements is constructed with the real component w=0 for both the vector to be rotated vector and the rotation axis rot_axis. The axis angle representation is then constructed by normalizing then multiplying by half the desired angle theta. See here for why half the angle is required.

Now create the quaternions v and qlog using the library, and get the unit rotation quaternion q by taking the exponential.

vec = quat.quaternion(*v)
qlog = quat.quaternion(*axis_angle)
q = np.exp(qlog)

Finally, the rotation of the vector is calculated by the following operation.

v_prime = q * vec * np.conjugate(q)

print(v_prime) # quaternion(0.0, 2.7491163, 4.7718093, 1.9162971)

Now just discard the real element and you have your rotated vector!

v_prime_vec = v_prime.imag # [2.74911638 4.77180932 1.91629719] as a numpy array

Note that this method is particularly efficient if you have to rotate a vector through many sequential rotations, as the quaternion product can just be calculated as q = q1 * q2 * q3 * q4 * ... * qn and then the vector is only rotated by 'q' at the very end using v' = q * v * conj(q).

This method gives you a seamless transformation between axis angle <---> 3d rotation operator simply by exp and log functions (yes log(q) just returns the axis-angle representation!). For further clarification of how quaternion multiplication etc. work, see here

Pretty print in MongoDB shell as default

Oh so i guess .pretty() is equal to:

db.collection.find().forEach(printjson);

How to predict input image using trained model in Keras?

You can use model.predict() to predict the class of a single image as follows [doc]:

# load_model_sample.py
from keras.models import load_model
from keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os


def load_image(img_path, show=False):

    img = image.load_img(img_path, target_size=(150, 150))
    img_tensor = image.img_to_array(img)                    # (height, width, channels)
    img_tensor = np.expand_dims(img_tensor, axis=0)         # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
    img_tensor /= 255.                                      # imshow expects values in the range [0, 1]

    if show:
        plt.imshow(img_tensor[0])                           
        plt.axis('off')
        plt.show()

    return img_tensor


if __name__ == "__main__":

    # load model
    model = load_model("model_aug.h5")

    # image path
    img_path = '/media/data/dogscats/test1/3867.jpg'    # dog
    #img_path = '/media/data/dogscats/test1/19.jpg'      # cat

    # load a single image
    new_image = load_image(img_path)

    # check prediction
    pred = model.predict(new_image)

In this example, a image is loaded as a numpy array with shape (1, height, width, channels). Then, we load it into the model and predict its class, returned as a real value in the range [0, 1] (binary classification in this example).

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

This problem, in my case, wasn't related to the Insert key. It was related to Vrapper being enabled and editing like Vim, without my knowledge.

I just toggled the Vrapper Icon in Eclipse top bar of menus and then pressed the Insert Key and the problem was solved.

Hopefully this answer will help someone in the future.

Remove part of a string

Here the strsplit solution for a dataframe using dplyr package

col1 = c("TGAS_1121", "MGAS_1432", "ATGAS_1121") 
col2 = c("T", "M", "A") 
df = data.frame(col1, col2)
df
        col1 col2
1  TGAS_1121    T
2  MGAS_1432    M
3 ATGAS_1121    A

df<-mutate(df,col1=as.character(col1))
df2<-mutate(df,col1=sapply(strsplit(df$col1, split='_', fixed=TRUE),function(x) (x[2])))
df2

  col1 col2
1 1121    T
2 1432    M
3 1121    A

How to remove padding around buttons in Android?

A standard button is not supposed to be used at full width which is why you experience this.

Background

If you have a look at the Material Design - Button Style you will see that a button has a 48dp height click area, but will be displayed as 36dp of height for...some reason.

This is the background outline you see, which will not cover the whole area of the button itself.
It has rounded corners and some padding and is supposed to be clickable by itself, wrap its content, and not span the whole width at the bottom of your screen.

Solution

As mentioned above, what you want is a different background. Not a standard button, but a background for a selectable item with this nice ripple effect.

For this use case there is the ?selectableItemBackground theme attribute which you can use for your backgrounds (especially in lists).
It will add a platform standard ripple (or some color state list on < 21) and will use your current theme colors.

For your usecase you might just use the following:

<Button
    android:id="@+id/sign_in_button"
    style="?android:attr/buttonBarButtonStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Login"
    android:background="?attr/selectableItemBackground" />
                   <!--  /\ that's all -->

There is also no need to add layout weights if your view is the only one and spans the whole screen

If you have some different idea on what your background should look like you have to create a custom drawable yourself, and manage color and state there.

This answer copied from Question: How to properly remove padding (or margin?) around buttons in Android?

Why does Eclipse Java Package Explorer show question mark on some classes?

this is because your project has been linked to a git-hub repository, and the file having question mark on it, is not been added yet. if you want to remove this sign you will have to add this file to git-hub repository.

Getting Java version at runtime

The simplest way (java.specification.version):

double version = Double.parseDouble(System.getProperty("java.specification.version"));

if (version == 1.5) {
    // 1.5 specific code
} else {
    // ...
}

or something like (java.version):

String[] javaVersionElements = System.getProperty("java.version").split("\\.");

int major = Integer.parseInt(javaVersionElements[1]);

if (major == 5) {
    // 1.5 specific code
} else {
    // ...
}

or if you want to break it all up (java.runtime.version):

String discard, major, minor, update, build;

String[] javaVersionElements = System.getProperty("java.runtime.version").split("\\.|_|-b");

discard = javaVersionElements[0];
major   = javaVersionElements[1];
minor   = javaVersionElements[2];
update  = javaVersionElements[3];
build   = javaVersionElements[4];

How to do multiline shell script in Ansible

Ansible uses YAML syntax in its playbooks. YAML has a number of block operators:

  • The > is a folding block operator. That is, it joins multiple lines together by spaces. The following syntax:

    key: >
      This text
      has multiple
      lines
    

    Would assign the value This text has multiple lines\n to key.

  • The | character is a literal block operator. This is probably what you want for multi-line shell scripts. The following syntax:

    key: |
      This text
      has multiple
      lines
    

    Would assign the value This text\nhas multiple\nlines\n to key.

You can use this for multiline shell scripts like this:

- name: iterate user groups
  shell: |
    groupmod -o -g {{ item['guid'] }} {{ item['username'] }} 
    do_some_stuff_here
    and_some_other_stuff
  with_items: "{{ users }}"

There is one caveat: Ansible does some janky manipulation of arguments to the shell command, so while the above will generally work as expected, the following won't:

- shell: |
    cat <<EOF
    This is a test.
    EOF

Ansible will actually render that text with leading spaces, which means the shell will never find the string EOF at the beginning of a line. You can avoid Ansible's unhelpful heuristics by using the cmd parameter like this:

- shell:
    cmd: |
      cat <<EOF
      This is a test.
      EOF

Youtube - downloading a playlist - youtube-dl

Your link is not a playlist.

A proper playlist URL looks like this:

https://www.youtube.com/playlist?list=PLHSdFJ8BDqEyvUUzm6R0HxawSWniP2c9K

Your URL is just the first video OF a certain playlist. It contains https://www.youtube.com/watch? instead of https://www.youtube.com/playlist?.

Pick the playlist by clicking on the title of the playlist on the right side in the list of videos and use this URL.

Check if bash variable equals 0

Specifically: ((depth)). By example, the following prints 1.

declare -i x=0
((x)) && echo $x

x=1
((x)) && echo $x

How to use SearchView in Toolbar Android

Integrating SearchView with RecyclerView

1) Add SearchView Item in Menu

SearchView can be added as actionView in menu using

app:useActionClass = "android.support.v7.widget.SearchView" .

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
    android:id="@+id/searchBar"
    app:showAsAction="always"
    app:actionViewClass="android.support.v7.widget.SearchView"
    />
</menu>

2) Implement SearchView.OnQueryTextListener in your Activity

SearchView.OnQueryTextListener has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.

YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{

   public boolean onQueryTextSubmit(String query)

   public boolean onQueryTextChange(String newText) 

}

3) Set up SerchView Hint text, listener etc

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

    MenuItem searchItem = menu.findItem(R.id.searchBar);

    SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setQueryHint("Search People");
    searchView.setOnQueryTextListener(this);
    searchView.setIconified(false);

    return true;
}

4) Implement SearchView.OnQueryTextListener

This is how you can implement abstract methods of the listener.

@Override
public boolean onQueryTextSubmit(String query) {

    // This method can be used when a query is submitted eg. creating search history using SQLite DB

    Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {

    adapter.filter(newText);
    return true;
}

5) Write a filter method in your RecyclerView Adapter.

You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView.

public void filter(String queryText)
{
    list.clear();

    if(queryText.isEmpty())
    {
        list.addAll(copyList);
    }
    else
    {

        for(String name: copyList)
        {
            if(name.toLowerCase().contains(queryText.toLowerCase()))
            {
                list.add(name);
            }
        }

    }

    notifyDataSetChanged();
}

Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App

Removing whitespace from strings in Java

You should use

s.replaceAll("\\s+", "");

instead of:

s.replaceAll("\\s", "");

This way, it will work with more than one spaces between each string. The + sign in the above regex means "one or more \s"

--\s = Anything that is a space character (including space, tab characters etc). Why do we need s+ here?

Cannot perform runtime binding on a null reference, But it is NOT a null reference

Found solution: I had typo in my view, ViewBag.Typo <-- this caused the error, but the debugger placed the exception at a irrelevant place.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

#!/usr/bin/python

# encoding=utf8

Try This to starting of python file

How do I lowercase a string in Python?

Also, you can overwrite some variables:

s = input('UPPER CASE')
lower = s.lower()

If you use like this:

s = "Kilometer"
print(s.lower())     - kilometer
print(s)             - Kilometer

It will work just when called.

How to install the Raspberry Pi cross compiler on my Linux host machine?

You may use clang as well. It used to be faster than GCC, and now it is quite a stable thing. It is much easier to build clang from sources (you can really drink cup of coffee during build process).

In short:

  1. Get clang binaries (sudo apt-get install clang).. or download and build (read instructions here)
  2. Mount your raspberry rootfs (it may be the real rootfs mounted via sshfs, or an image).
  3. Compile your code:

    path/to/clang --target=arm-linux-gnueabihf --sysroot=/some/path/arm-linux-gnueabihf/sysroot my-happy-program.c -fuse-ld=lld
    

Optionally you may use legacy arm-linux-gnueabihf binutils. Then you may remove "-fuse-ld=lld" flag at the end.

Below is my cmake toolchain file.

toolchain.cmake

set(CMAKE_SYSTEM_VERSION 1)
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)

# Custom toolchain-specific definitions for your project
set(PLATFORM_ARM "1")
set(PLATFORM_COMPILE_DEFS "COMPILE_GLES")

# There we go!
# Below, we specify toolchain itself!

set(TARGET_TRIPLE arm-linux-gnueabihf)

# Specify your target rootfs mount point on your compiler host machine
set(TARGET_ROOTFS /Volumes/rootfs-${TARGET_TRIPLE})

# Specify clang paths
set(LLVM_DIR /Users/stepan/projects/shared/toolchains/llvm-7.0.darwin-release-x86_64/install)
set(CLANG ${LLVM_DIR}/bin/clang)
set(CLANGXX ${LLVM_DIR}/bin/clang++)

# Specify compiler (which is clang)
set(CMAKE_C_COMPILER   ${CLANG})
set(CMAKE_CXX_COMPILER ${CLANGXX})

# Specify binutils

set (CMAKE_AR      "${LLVM_DIR}/bin/llvm-ar" CACHE FILEPATH "Archiver")
set (CMAKE_LINKER  "${LLVM_DIR}/bin/llvm-ld" CACHE FILEPATH "Linker")
set (CMAKE_NM      "${LLVM_DIR}/bin/llvm-nm" CACHE FILEPATH "NM")
set (CMAKE_OBJDUMP "${LLVM_DIR}/bin/llvm-objdump" CACHE FILEPATH "Objdump")
set (CMAKE_RANLIB  "${LLVM_DIR}/bin/llvm-ranlib" CACHE FILEPATH "ranlib")

# You may use legacy binutils though.
#set(BINUTILS /usr/local/Cellar/arm-linux-gnueabihf-binutils/2.31.1)
#set (CMAKE_AR      "${BINUTILS}/bin/${TARGET_TRIPLE}-ar" CACHE FILEPATH "Archiver")
#set (CMAKE_LINKER  "${BINUTILS}/bin/${TARGET_TRIPLE}-ld" CACHE FILEPATH "Linker")
#set (CMAKE_NM      "${BINUTILS}/bin/${TARGET_TRIPLE}-nm" CACHE FILEPATH "NM")
#set (CMAKE_OBJDUMP "${BINUTILS}/bin/${TARGET_TRIPLE}-objdump" CACHE FILEPATH "Objdump")
#set (CMAKE_RANLIB  "${BINUTILS}/bin/${TARGET_TRIPLE}-ranlib" CACHE FILEPATH "ranlib")

# Specify sysroot (almost same as rootfs)
set(CMAKE_SYSROOT ${TARGET_ROOTFS})
set(CMAKE_FIND_ROOT_PATH ${TARGET_ROOTFS})

# Specify lookup methods for cmake
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

# Sometimes you also need this:
# set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)

# Specify raspberry triple
set(CROSS_FLAGS "--target=${TARGET_TRIPLE}")

# Specify other raspberry related flags
set(RASP_FLAGS "-D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS")

# Gather and distribute flags specified at prev steps.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CROSS_FLAGS} ${RASP_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CROSS_FLAGS} ${RASP_FLAGS}")

# Use clang linker. Why?
# Well, you may install custom arm-linux-gnueabihf binutils,
# but then, you also need to recompile clang, with customized triple;
# otherwise clang will try to use host 'ld' for linking,
# so... use clang linker.
set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld)

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

CCS only

@media (max-width: 1024px) and (orientation: portrait){ /* tablet and smaller */
  body:after{
    position: absolute;
    z-index: 9999;
    width: 100%;
    top: 0;
    bottom: 0;
    content: "";
    background: #212121 url(http://i.stack.imgur.com/sValK.png) 0 0 no-repeat; /* replace with an image that tells the visitor to rotate the device to landscape mode */
    background-size: 100% auto;
    opacity: 0.95;
  }
}

In some cases you may want to add a small piece of code to reload to page after the visitor rotated the device, so that the CSS is rendered properly:

window.onorientationchange = function() { 
    var orientation = window.orientation; 
        switch(orientation) { 
            case 0:
            case 90:
            case -90: window.location.reload(); 
            break; } 
};

How to use java.net.URLConnection to fire and handle HTTP requests?

There are 2 options you can go with HTTP URL Hits : GET / POST

GET Request :-

HttpURLConnection.setFollowRedirects(true); // defaults to true

String url = "https://name_of_the_url";
URL request_url = new URL(url);
HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();
http_conn.setConnectTimeout(100000);
http_conn.setReadTimeout(100000);
http_conn.setInstanceFollowRedirects(true);
System.out.println(String.valueOf(http_conn.getResponseCode()));

POST request :-

HttpURLConnection.setFollowRedirects(true); // defaults to true

String url = "https://name_of_the_url"
URL request_url = new URL(url);
HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();
http_conn.setConnectTimeout(100000);
http_conn.setReadTimeout(100000);
http_conn.setInstanceFollowRedirects(true);
http_conn.setDoOutput(true);
PrintWriter out = new PrintWriter(http_conn.getOutputStream());
if (urlparameter != null) {
   out.println(urlparameter);
}
out.close();
out = null;
System.out.println(String.valueOf(http_conn.getResponseCode()));

Iterate through DataSet

Just loop...

foreach(var table in DataSet1.Tables) {
    foreach(var col in table.Columns) {
       ...
    }
    foreach(var row in table.Rows) {
        object[] values = row.ItemArray;
        ...
    }
}

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:

[HttpPut("{pathId}/{subPathId}"),
public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)
{

    var body = new StreamReader(Request.Body);
    //The modelbinder has already read the stream and need to reset the stream index
    body.BaseStream.Seek(0, SeekOrigin.Begin); 
    var requestBody = body.ReadToEnd();
    //etc, we use this for an audit trail
}

Ruby optional parameters

It isn't possible to do it the way you've defined ldap_get. However, if you define ldap_get like this:

def ldap_get ( base_dn, filter, attrs=nil, scope=LDAP::LDAP_SCOPE_SUBTREE )

Now you can:

ldap_get( base_dn, filter, X )

But now you have problem that you can't call it with the first two args and the last arg (the same problem as before but now the last arg is different).

The rationale for this is simple: Every argument in Ruby isn't required to have a default value, so you can't call it the way you've specified. In your case, for example, the first two arguments don't have default values.

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

What are the advantages of NumPy over regular Python lists?

NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.

Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware!

The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!

Adding attribute in jQuery

best solution: from jQuery v1.6 you can use prop() to add a property

$('#someid').prop('disabled', true);

to remove it, use removeProp()

$('#someid').removeProp('disabled');

Reference

Also note that the .removeProp() method should not be used to set these properties to false. Once a native property is removed, it cannot be added again. See .removeProp() for more information.

Read Excel sheet in Powershell

This assumes that the content is in column B on each sheet (since it's not clear how you determine the column on each sheet.) and the last row of that column is also the last row of the sheet.

$xlCellTypeLastCell = 11 
$startRow = 5 
$col = 2 

$excel = New-Object -Com Excel.Application
$wb = $excel.Workbooks.Open("C:\Users\Administrator\my_test.xls")

for ($i = 1; $i -le $wb.Sheets.Count; $i++)
{
    $sh = $wb.Sheets.Item($i)
    $endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
    $city = $sh.Cells.Item($startRow, $col).Value2
    $rangeAddress = $sh.Cells.Item($startRow + 1, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
    $sh.Range($rangeAddress).Value2 | foreach 
    {
        New-Object PSObject -Property @{ City = $city; Area = $_ }
    }
}

$excel.Workbooks.Close()

How do I create a URL shortener?

I keep incrementing an integer sequence per domain in the database and use Hashids to encode the integer into a URL path.

static hashids = Hashids(salt = "my app rocks", minSize = 6)

I ran a script to see how long it takes until it exhausts the character length. For six characters it can do 164,916,224 links and then goes up to seven characters. Bitly uses seven characters. Under five characters looks weird to me.

Hashids can decode the URL path back to a integer but a simpler solution is to use the entire short link sho.rt/ka8ds3 as a primary key.

Here is the full concept:

function addDomain(domain) {
    table("domains").insert("domain", domain, "seq", 0)
}

function addURL(domain, longURL) {
    seq = table("domains").where("domain = ?", domain).increment("seq")
    shortURL = domain + "/" + hashids.encode(seq)
    table("links").insert("short", shortURL, "long", longURL)
    return shortURL
}

// GET /:hashcode
function handleRequest(req, res) {
    shortURL = req.host + "/" + req.param("hashcode")
    longURL = table("links").where("short = ?", shortURL).get("long")
    res.redirect(301, longURL)
}

How to create correct JSONArray in Java using JSONObject

Here is some code using java 6 to get you started:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();

OpenCV - Apply mask to a color image

Here, you could use cv2.bitwise_and function if you already have the mask image.

For check the below code:

img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

The output will be as follows for a lena image, and for rectangular mask.

enter image description here

MySql difference between two timestamps in days?

I know is quite old, but I'll say just for the sake of it - I was looking for the same problem and got here, but I needed the difference in days.

I used SELECT (UNIX_TIMESTAMP(DATE1) - UNIX_TIMESTAMP(DATE2))/60/60/24 Unix_timestamp returns the difference in seconds, and then I just divide into minutes(seconds/60), hours(minutes/60), days(hours/24).

Return from lambda forEach() in java

This what helped me:

List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);

Taken from Java 8 Finding Specific Element in List with Lambda

JavaScript TypeError: Cannot read property 'style' of null

In your script, this part:

document.getElementById('Noite')

must be returning null and you are also attempting to set the display property to an invalid value. There are a couple of possible reasons for this first part to be null.

  1. You are running the script too early before the document has been loaded and thus the Noite item can't be found.

  2. There is no Noite item in your HTML.

I should point out that your use of document.write() in this case code probably signifies a problem. If the document has already loaded, then a new document.write() will clear the old content and start a new fresh document so no Noite item would be found.

If your document has not yet been loaded and thus you're doing document.write() inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noite item.

The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:

document.getElementById('Noite').style.display='block';

And, make sure that there are no document.write() statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).


In addition, setting the display property to "display" doesn't make sense to me. The valid options for that are "block", "inline", "none", "table", etc... I'm not aware of any option named "display" for that style property. See here for valid options for teh display property.

You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/. That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.


P.S. I should point out that your lack of braces for your if statements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.


I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/. Here's a list of the changes I made:

  1. The script is located in the body, but after the content that it is referencing.
  2. I've added var declarations to your variables (a good habit to always use).
  3. The if statement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.
  4. I've added braces for every if statement so it absolutely clear which statements are part of the if/else and which are not.
  5. I've properly closed the </dd> tag you were inserting.
  6. I've changed style.display = ''; to style.display = 'block';.
  7. I've added semicolons at the end of every statement (another good habit to follow).

The code:

<div id="Night" style="display: none;">
    <img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
    <img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>    
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
    document.write("Meia-noite!<br>Já é amanhã!");
} else if (hr <=5 ) {
    document.write("&nbsp;&nbsp;Você não<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;devia<br>&nbsp;&nbsp;&nbsp;&nbsp;estar<br>dormindo?");
} else if (hr <= 11) {         
    document.write("Bom dia!");
} else if (hr == 12) {
    document.write("&nbsp;&nbsp;&nbsp;&nbsp;Vamos<br>&nbsp;almoçar?");
} else if (hr <= 17) {
    document.write("Boa Tarde");
} else if (hr <= 19) {
    document.write("&nbsp;Bom final<br>&nbsp;de tarde!");
} else if (hr == 20) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
    document.write("&nbsp;Boa Noite");
} else if (hr == 23) {
    document.write("Ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>

Why is Dictionary preferred over Hashtable in C#?

HashTable:

Key/value will be converted into an object (boxing) type while storing into the heap.

Key/value needs to be converted into the desired type while reading from the heap.

These operations are very costly. We need to avoid boxing/unboxing as much as possible.

Dictionary : Generic variant of HashTable.

No boxing/unboxing. No conversions required.

How can I manually set an Angular form field as invalid?

For unit test:

spyOn(component.form, 'valid').and.returnValue(true);

Resize Google Maps marker icon image

A complete beginner like myself to the topic may find it harder to implement one of these answers than, if within your control, to resize the image yourself with an online editor or a photo editor like Photoshop.

A 500x500 image will appear larger on the map than a 50x50 image.

No programming required.

How to print an unsigned char in C?

Because char is by default signed declared that means the range of the variable is

-127 to +127>

your value is overflowed. To get the desired value you have to declared the unsigned modifier. the modifier's (unsigned) range is:

 0 to 255

to get the the range of any data type follow the process 2^bit example charis 8 bit length to get its range just 2 ^(power) 8.

How to convert string into float in JavaScript?

Try

_x000D_
_x000D_
let str ="554,20";_x000D_
let float = +str.replace(',','.');_x000D_
let int = str.split(',').map(x=>+x);_x000D_
_x000D_
console.log({float,int});
_x000D_
_x000D_
_x000D_

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

Laravel - htmlspecialchars() expects parameter 1 to be string, object given.

thank me latter.........................

when you send or get array from contrller or function but try to print as single value or single variable in laravel blade file so it throws an error

->use any think who convert array into string it work.

solution: 1)run the foreach loop and get single single value and print. 2)The implode() function returns a string from the elements of an array. {{ implode($your_variable,',') }}

implode is best way to do it and its 100% work.

HTML Submit-button: Different value / button-text?

There are plenty of answers here explaining what you could do (I use the different field name one) but the simple (and as-yet unstated) answer to your question is 'no' - you can't have a different text and value using just HTML.

MVC controller : get JSON object from HTTP body?

Once you define a class (MyDTOClass) indicating what you expect to receive it should be as simple as...

public ActionResult Post([FromBody]MyDTOClass inputData){
 ... do something with input data ...
}

Thx to Julias:

Parsing Json .Net Web Api

Make sure your request is sent with the http header:

Content-Type: application/json

What does T&& (double ampersand) mean in C++11?

An rvalue reference is a type that behaves much like the ordinary reference X&, with several exceptions. The most important one is that when it comes to function overload resolution, lvalues prefer old-style lvalue references, whereas rvalues prefer the new rvalue references:

void foo(X& x);  // lvalue reference overload
void foo(X&& x); // rvalue reference overload

X x;
X foobar();

foo(x);        // argument is lvalue: calls foo(X&)
foo(foobar()); // argument is rvalue: calls foo(X&&)

So what is an rvalue? Anything that is not an lvalue. An lvalue being an expression that refers to a memory location and allows us to take the address of that memory location via the & operator.

It is almost easier to understand first what rvalues accomplish with an example:

 #include <cstring>
 class Sample {
  int *ptr; // large block of memory
  int size;
 public:
  Sample(int sz=0) : ptr{sz != 0 ? new int[sz] : nullptr}, size{sz} 
  {
     if (ptr != nullptr) memset(ptr, 0, sz);
  }
  // copy constructor that takes lvalue 
  Sample(const Sample& s) : ptr{s.size != 0 ? new int[s.size] :\
      nullptr}, size{s.size}
  {
     if (ptr != nullptr) memcpy(ptr, s.ptr, s.size);
     std::cout << "copy constructor called on lvalue\n";
  }

  // move constructor that take rvalue
  Sample(Sample&& s) 
  {  // steal s's resources
     ptr = s.ptr;
     size = s.size;        
     s.ptr = nullptr; // destructive write
     s.size = 0;
     cout << "Move constructor called on rvalue." << std::endl;
  }    
  // normal copy assignment operator taking lvalue
  Sample& operator=(const Sample& s)
  {
   if(this != &s) {
      delete [] ptr; // free current pointer
      size = s.size;

      if (size != 0) {
        ptr = new int[s.size];
        memcpy(ptr, s.ptr, s.size);
      } else 
         ptr = nullptr;
     }
     cout << "Copy Assignment called on lvalue." << std::endl;
     return *this;
  }    
 // overloaded move assignment operator taking rvalue
 Sample& operator=(Sample&& lhs)
 {
   if(this != &s) {
      delete [] ptr; //don't let ptr be orphaned 
      ptr = lhs.ptr;   //but now "steal" lhs, don't clone it.
      size = lhs.size; 
      lhs.ptr = nullptr; // lhs's new "stolen" state
      lhs.size = 0;
   }
   cout << "Move Assignment called on rvalue" << std::endl;
   return *this;
 }
//...snip
};     

The constructor and assignment operators have been overloaded with versions that take rvalue references. Rvalue references allow a function to branch at compile time (via overload resolution) on the condition "Am I being called on an lvalue or an rvalue?". This allowed us to create more efficient constructor and assignment operators above that move resources rather copy them.

The compiler automatically branches at compile time (depending on the whether it is being invoked for an lvalue or an rvalue) choosing whether the move constructor or move assignment operator should be called.

Summing up: rvalue references allow move semantics (and perfect forwarding, discussed in the article link below).

One practical easy-to-understand example is the class template std::unique_ptr. Since a unique_ptr maintains exclusive ownership of its underlying raw pointer, unique_ptr's can't be copied. That would violate their invariant of exclusive ownership. So they do not have copy constructors. But they do have move constructors:

template<class T> class unique_ptr {
  //...snip
 unique_ptr(unique_ptr&& __u) noexcept; // move constructor
};

 std::unique_ptr<int[] pt1{new int[10]};  
 std::unique_ptr<int[]> ptr2{ptr1};// compile error: no copy ctor.  

 // So we must first cast ptr1 to an rvalue 
 std::unique_ptr<int[]> ptr2{std::move(ptr1)};  

std::unique_ptr<int[]> TakeOwnershipAndAlter(std::unique_ptr<int[]> param,\
 int size)      
{
  for (auto i = 0; i < size; ++i) {
     param[i] += 10;
  }
  return param; // implicitly calls unique_ptr(unique_ptr&&)
}

// Now use function     
unique_ptr<int[]> ptr{new int[10]};

// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(\
           static_cast<unique_ptr<int[]>&&>(ptr), 10);

cout << "output:\n";

for(auto i = 0; i< 10; ++i) {
   cout << new_owner[i] << ", ";
}

output:
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 

static_cast<unique_ptr<int[]>&&>(ptr) is usually done using std::move

// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(std::move(ptr),0);

An excellent article explaining all this and more (like how rvalues allow perfect forwarding and what that means) with lots of good examples is Thomas Becker's C++ Rvalue References Explained. This post relied heavily on his article.

A shorter introduction is A Brief Introduction to Rvalue References by Stroutrup, et. al

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

OK, two steps to this - first is to write a function that does the translation you want - I've put an example together based on your pseudo-code:

def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

You may want to go over this, but it seems to do the trick - notice that the parameter going into the function is considered to be a Series object labelled "row".

Next, use the apply function in pandas to apply the function - e.g.

df.apply (lambda row: label_race(row), axis=1)

Note the axis=1 specifier, that means that the application is done at a row, rather than a column level. The results are here:

0           White
1        Hispanic
2           White
3           White
4           Other
5           White
6     Two Or More
7           White
8    Haw/Pac Isl.
9           White

If you're happy with those results, then run it again, saving the results into a new column in your original dataframe.

df['race_label'] = df.apply (lambda row: label_race(row), axis=1)

The resultant dataframe looks like this (scroll to the right to see the new column):

      lname   fname rno_cd  eri_afr_amer  eri_asian  eri_hawaiian   eri_hispanic  eri_nat_amer  eri_white rno_defined    race_label
0      MOST    JEFF      E             0          0             0              0             0          1       White         White
1    CRUISE     TOM      E             0          0             0              1             0          0       White      Hispanic
2      DEPP  JOHNNY    NaN             0          0             0              0             0          1     Unknown         White
3     DICAP     LEO    NaN             0          0             0              0             0          1     Unknown         White
4    BRANDO  MARLON      E             0          0             0              0             0          0       White         Other
5     HANKS     TOM    NaN             0          0             0              0             0          1     Unknown         White
6    DENIRO  ROBERT      E             0          1             0              0             0          1       White   Two Or More
7    PACINO      AL      E             0          0             0              0             0          1       White         White
8  WILLIAMS   ROBIN      E             0          0             1              0             0          0       White  Haw/Pac Isl.
9  EASTWOOD   CLINT      E             0          0             0              0             0          1       White         White

Set and Get Methods in java?

Having accessor methods is preferred to accessing fields directly, because it controls how fields are accessed (may impose data checking etc) and fits with interfaces (interfaces can not requires fields to be present, only methods).

Convert a hexadecimal string to an integer efficiently in C?

This currently only works with lower case but its super easy to make it work with both.

cout << "\nEnter a hexadecimal number: ";
cin >> hexNumber;
orighex = hexNumber;

strlength = hexNumber.length();

for (i=0;i<strlength;i++)
{
    hexa = hexNumber.substr(i,1);
    if ((hexa>="0") && (hexa<="9"))
    {
        //cout << "This is a numerical value.\n";
    }
    else
    {
        //cout << "This is a alpabetical value.\n";
        if (hexa=="a"){hexa="10";}
        else if (hexa=="b"){hexa="11";}
        else if (hexa=="c"){hexa="12";}
        else if (hexa=="d"){hexa="13";}
        else if (hexa=="e"){hexa="14";}
        else if (hexa=="f"){hexa="15";}
        else{cout << "INVALID ENTRY! ANSWER WONT BE CORRECT\n";}
    }
    //convert from string to integer

    hx = atoi(hexa.c_str());
    finalhex = finalhex + (hx*pow(16.0,strlength-i-1));
}
cout << "The hexadecimal number: " << orighex << " is " << finalhex << " in decimal.\n";

notifyDataSetChange not working from custom adapter

In my case I simply forget to add in my fragment mRecyclerView.setAdapter(adapter)

How to convert between bytes and strings in Python 3?

The 'mangler' in the above code sample was doing the equivalent of this:

bytesThing = stringThing.encode(encoding='UTF-8')

There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8'), but the above syntax makes it obvious what is going on, and also what to do to recover the string:

newStringThing = bytesThing.decode(encoding='UTF-8')

When we do this, the original string is recovered.

Note, using str(bytesThing) just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8'). No error is reported if the encoding is not specified.

Unable to create Genymotion Virtual Device

Have a look at this blog.

Genymotion is previously known as AndroidVM.

As the blog stated:

Known bugs (same as 20121119 release) :

Hardware OpenGL/Intel HD/Windows : On most Intel HD drivers running Windows, the AndroVMplayer might crash (in the driver DLL) when starting Android ; you may have to restart AndroVMplayer an important number of times before it suceeds
Hardware OpenGL/WebView : On some GPUs (mostly NVidia ?), the browser and all apps which use the WebView component might show scrambled HTML content
AndroVMplayer now support window resizing, as well as fullscreen mode ; to use AndroVMplayer in fullscreen mode, you have to :

select “manual resolution” and tick the “fullscreen” box
press F11 (Ctrl+F11 on Mac) to switch to fullscreen when the player window has appeared
When starting the virtual machine, AndroVMplayer now check different things :

If your AndroVM virtual machine doesn’t have the “hardware OpenGL” option enabled, it can enable it for you before starting the VM.
If your AndroVM virtual machine first network adapter is not configured, it can configure it for you (as well as create the host-only network for you).
To summarize that, with this new AndroVMplayer, to use OpenGL hardware you just have to :

Import the AndroVM ova in VirtualBox
Start AndroVMplayer, choose your resolution and the virtual machine you’ve just imported
Click “Run” and it should work
You can still use AndroVMplayer with non-VirtualBox systems (e.g VMWare) but, obviously, you won’t benefit from automatic VirtualBox configuration and VM start/stop ; in this case, you have to choose ‘none’ as the VM name and directly type the IP address of your virtual machine.

Please note that, due to the change in communication, old AndroVMplayer won’t work with 20130222 OVAs and old OVAs won’t work with 20130222 AndroVMplayer.

Styling the last td in a table with css

For IE, how about using a CSS expression:

<style type="text/css">
table td { 
  h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : '1px solid #000' ) );
}
</style>

How to get last inserted row ID from WordPress database?

just like this :

global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);

simply your selecting all the rows then order them DESC by id , and displaying only the first

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy so it was slightly different. However the same should work for add policy as well.

services.AddAuthorization(options =>
        {
            options.AddPolicy(DefaultAuthorizedPolicy, policy =>
            {
                policy.Requirements.Add(new TokenAuthRequirement());
                policy.AuthenticationSchemes = new List<string>()
                                {
                                    CookieAuthenticationDefaults.AuthenticationScheme
                                }
            });
        });

Do take into consideration that by Default AuthenticationSchemes property uses a read only list. I think it would be better to implement that instead of List as well.

How to generate JAXB classes from XSD?

For Eclipse STS (3.5 at least) you don't need to install anything. Right click on schema.xsd -> Generate -> JAXB Classes. You'll have to specify the package & location in the next step and that's all, your classes should be generated. I guess all the above mentioned solutions work, but this seems by far the easiest (for STS users).

[UPDATE] Eclipse STS version 3.6 (based on Kepler) comes with the same functionality.

blah

How can I make Java print quotes, like "Hello"?

You can do it using a unicode character also

System.out.print('\u0022' + "Hello" + '\u0022');

Mix Razor and Javascript code

Never ever mix more languages.

<script type="text/javascript">
    var data = @Json.Encode(Model); // !!!! export data !!!!

    for(var prop in data){
      console.log( prop + " "+ data[prop]);
    }

In case of problem you can also try

@Html.Raw(Json.Encode(Model));

How do I format a date as ISO 8601 in moment.js?

When you use Mongoose to store dates into MongoDB you need to use toISOString() because all dates are stored as ISOdates with miliseconds.

moment.format() 

2018-04-17T20:00:00Z

moment.toISOString() -> USE THIS TO STORE IN MONGOOSE

2018-04-17T20:00:00.000Z

Import JavaScript file and call functions using webpack, ES6, ReactJS

import * as utils from './utils.js'; 

If you do the above, you will be able to use functions in utils.js as

utils.someFunction()

Change navbar text color Bootstrap

Add some inline css to the anchor tag

<li><a style = "color:blue" href="#"><span class="glyphicon glyphicon-user"></span> About</a></li>

This should add the color blue to the anchor tag text.

Invalid Host Header when ngrok tries to connect to React dev server

Option 1

If you do not need to use Authentication you can add configs to ngrok commands

ngrok http 9000 --host-header=rewrite

or

ngrok http 9000 --host-header="localhost:9000"

But in this case Authentication will not work on your website because ngrok rewriting headers and session is not valid for your ngrok domain

Option 2

If you are using webpack you can add the following configuration

devServer: {
    disableHostCheck: true
}

In that case Authentication header will be valid for your ngrok domain

Android Studio build fails with "Task '' not found in root project 'MyProject'."

This is what I did

  1. Remove .idea folder

    $ mv .idea .idea.bak

  2. Import the project again

What does ENABLE_BITCODE do in xcode 7?

Update

Apple has clarified that slicing occurs independent of enabling bitcode. I've observed this in practice as well where a non-bitcode enabled app will only be downloaded as the architecture appropriate for the target device.

Original

More specifically:

Bitcode. Archive your app for submission to the App Store in an intermediate representation, which is compiled into 64- or 32-bit executables for the target devices when delivered.

Slicing. Artwork incorporated into the Asset Catalog and tagged for a platform allows the App Store to deliver only what is needed for installation.

The way I read this, if you support bitcode, downloaders of your app will only get the compiled architecture needed for their own device.

How to add and remove classes in Javascript without jQuery

For future friendliness, I second the recommendation for classList with polyfill/shim: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#wrapper

var elem = document.getElementById( 'some-id' );
elem.classList.add('some-class'); // Add class
elem.classList.remove('some-other-class'); // Remove class
elem.classList.toggle('some-other-class'); // Add or remove class
if ( elem.classList.contains('some-third-class') ) { // Check for class
    console.log('yep!');
}

inline conditionals in angular.js

I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):

ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"

The same approach should work for other attribute types.

(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)

I have published an article on working with AngularJS+SVG that talks about this and related issues. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS

MVC Razor view nested foreach's model

You could add a Category partial and a Product partial, each would take a smaller part of the main model as it's own model, i.e. Category's model type might be an IEnumerable, you would pass in Model.Theme to it. The Product's partial might be an IEnumerable that you pass Model.Products into (from within the Category partial).

I'm not sure if that would be the right way forward, but would be interested in knowing.

EDIT

Since posting this answer, I've used EditorTemplates and find this the easiest way to handle repeating input groups or items. It handles all your validation message problems and form submission/model binding woes automatically.

ASP.NET Setting width of DataBound column in GridView

<asp:GridView ID="GridView1" AutoGenerateEditButton="True" 
ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" width="600px">

<Columns>
                <asp:BoundField HeaderText="UserId" 
                DataField="UserId" 
                SortExpression="UserId" ItemStyle-Width="400px"></asp:BoundField>
   </Columns>
</asp:GridView>

Rename computer and join to domain in one step with PowerShell

the Options JoinWithNewName in Add-Computer can do this work .

-- JoinWithNewName: Renames the computer name in the new domain to the name specified by the NewName parameter. When you use the NewName parameter, this option is set automatically. This option is designed to be used with the Rename-Computer cmdlet. If you use the Rename-Computer cmdlet to rename the computer, but do not restart the computer to make the change effective, you can use this parameter to join the computer to a domain with its new name.

$oldName = Read-Host -Prompt "Enter Original Computer Name"
$newName = Read-Host -Prompt "Enter New Computer Name"
$domain = Read-Host -Prompt "Enter Domain Name to be added"
$user = Read-Host -Prompt "Enter Domain user name"
$password = Read-Host -Prompt "Enter password for $user" -AsSecureString 
$username = "$domain\$user" 
$credential = New-Object System.Management.Automation.PSCredential($username,$password) 
Rename-Computer -NewName $newName -LocalCredential admin -Force
Write-Host "Please waiting for a moment to change Domain and then restart" -ForegroundColor Red
Add-Computer -ComputerName $oldName -DomainName $domain -Options JoinWithNewName -Credential $credential -Restart

Output grep results to text file, need cleaner output

grep -n "YOUR SEARCH STRING" * > output-file

The -n will print the line number and the > will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe | for example:
grep -n "test" * | grep -v "mytest" > output-file will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v) - and will redirect the result to an output file.
A few good grep-tips can be found on this post

saving a file (from stream) to disk using c#

if the data is already valid and already contains a pdf, word or image, then you could use a StreamWriter and save it.

More than 1 row in <Input type="textarea" />

Although <input> ignores the rows attribute, you can take advantage of the fact that <textarea> doesn't have to be inside <form> tags, but can still be a part of a form by referencing the form's id:

<form method="get" id="testformid">
    <input type="submit" />
</form> 
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>

Of course, <textarea> now appears below "submit" button, but maybe you'll find a way to reposition it.

How do I auto-hide placeholder text upon focus using css or jquery?

$("input[placeholder]").focusin(function () {
    $(this).data('place-holder-text', $(this).attr('placeholder')).attr('placeholder', '');
})
.focusout(function () {
    $(this).attr('placeholder', $(this).data('place-holder-text'));
});

Open a new tab on button click in AngularJS

Proper HTML way: just surround your button with anchor element and add attribute target="_blank". It is as simple as that:

<a ng-href="{{yourDynamicURL}}" target="_blank">
    <h1>Open me in new Tab</h1>
</a>

where you can set in the controller:

$scope.yourDynamicURL = 'https://stackoverflow.com';

How do I set/unset a cookie with jQuery?

I thought Vignesh Pichamani's answer was the simplest and cleanest. Just adding to his the ability to set the number of days before expiration:

EDIT: also added 'never expires' option if no day number is set

        function setCookie(key, value, days) {
            var expires = new Date();
            if (days) {
                expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
            } else {
                document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
            }
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }

Set the cookie:

setCookie('myData', 1, 30); // myData=1 for 30 days. 
setCookie('myData', 1); // myData=1 'forever' (until the year 9999) 

How do I see which checkbox is checked?

If you don't know which checkboxes your page has (ex: if you are creating them dynamically) you can simply put a hidden field with the same name and 0 value right above the checkbox.

<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">

This way you will get 1 or 0 based on whether the checkbox is selected or not.

Select statement to find duplicates on certain fields

To see duplicate values:

with MYCTE  as (
    select row_number() over ( partition by name  order by name) rown, *
    from tmptest  
    ) 
select * from MYCTE where rown <=1

How do I get an element to scroll into view, using jQuery?

Simple 2 steps for scrolling down to end or bottom.

Step1: get the full height of scrollable(conversation) div.

Step2: apply scrollTop on that scrollable(conversation) div using the value obtained in step1.

var fullHeight = $('#conversation')[0].scrollHeight;

$('#conversation').scrollTop(fullHeight);

Above steps must be applied for every append on the conversation div.

How do you convert WSDLs to Java classes using Eclipse?

Options are:

Read through the above links before taking a call

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

Send auto email programmatically

It might be an easiest way-

    String recipientList = mEditTextTo.getText().toString();
    String[] recipients = recipientList.split(",");

    String subject = mEditTextSubject.getText().toString();
    String message = mEditTextMessage.getText().toString();

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, recipients);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);

    intent.setType("message/rfc822");
    startActivity(Intent.createChooser(intent, "Choose an email client"));

How can I get href links from HTML using Python?

My answer probably sucks compared to the real gurus out there, but using some simple math, string slicing, find and urllib, this little script will create a list containing link elements. I test google and my output seems right. Hope it helps!

import urllib
test = urllib.urlopen("http://www.google.com").read()
sane = 0
needlestack = []
while sane == 0:
  curpos = test.find("href")
  if curpos >= 0:
    testlen = len(test)
    test = test[curpos:testlen]
    curpos = test.find('"')
    testlen = len(test)
    test = test[curpos+1:testlen]
    curpos = test.find('"')
    needle = test[0:curpos]
    if needle.startswith("http" or "www"):
        needlestack.append(needle)
  else:
    sane = 1
for item in needlestack:
  print item

How to hide app title in android?

You can do it programatically:

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class ActivityName extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // remove title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

Or you can do it via your AndroidManifest.xml file:

<activity android:name=".ActivityName"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>

Edit: I added some lines so that you can show it in fullscreen, as it seems that's what you want.

iOS application: how to clear notifications?

Just to expand on pcperini's answer. As he mentions you will need to add the following code to your application:didFinishLaunchingWithOptions: method;

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];

You Also need to increment then decrement the badge in your application:didReceiveRemoteNotification: method if you are trying to clear the message from the message centre so that when a user enters you app from pressing a notification the message centre will also clear, ie;

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];

How to make a transparent border using CSS?

use rgba (rgb with alpha transparency):

border: 10px solid rgba(0,0,0,0.5); // 0.5 means 50% of opacity

The alpha transparency variate between 0 (0% opacity = 100% transparent) and 1 (100 opacity = 0% transparent)