Programs & Examples On #Requirehttps

How to use a client certificate to authenticate and authorize in a Web API

Make sure HttpClient has access to the full client certificate (including the private key).

You are calling GetCert with a file "ClientCertificate.cer" which leads to the assumption that there is no private key contained - should rather be a pfx file within windows. It may be even better to access the certificate from the windows cert store and search it using the fingerprint.

Be careful when copying the fingerprint: There are some non-printable characters when viewing in cert management (copy the string over to notepad++ and check the length of the displayed string).

'uint32_t' identifier not found error

I have the same error and it fixed it including in the file the following

#include <stdint.h>

at the beginning of your file.

How to execute a file within the python interpreter?

From my view, the best way is:

import yourfile

and after modifying yourfile.py

reload(yourfile)   

or

import imp; 
imp.reload(yourfile) in python3

but this will make the function and classes looks like that: yourfile.function1, yourfile.class1.....

If you cannot accept those, the finally solution is:

reload(yourfile)
from yourfile import *

Javascript get object key name

Change alert(buttons[i].text); to alert(i);

Laravel 5.2 not reading env file

I had a similar issue in my config/services.php and I solved using config clear and optimize commands:

php artisan config:clear
php artisan optimize

combining two data frames of different lengths

My idea is to get max of rows count of all data.frames and next append empty matrix to every data.frame if need. This method doesn't require additional packages, only base is used. Code looks following:

list.df <- list(data.frame(a = 1:10), data.frame(a = 1:5), data.frame(a = 1:3))

max.rows <- max(unlist(lapply(list.df, nrow), use.names = F))

list.df <- lapply(list.df, function(x) {
    na.count <- max.rows - nrow(x)
    if (na.count > 0L) {
        na.dm <- matrix(NA, na.count, ncol(x))
        colnames(na.dm) <- colnames(x)
        rbind(x, na.dm)
    } else {
        x
    }
})

do.call(cbind, list.df)

#     a  a  a
# 1   1  1  1
# 2   2  2  2
# 3   3  3  3
# 4   4  4 NA
# 5   5  5 NA
# 6   6 NA NA
# 7   7 NA NA
# 8   8 NA NA
# 9   9 NA NA
# 10 10 NA NA

How connect Postgres to localhost server using pgAdmin on Ubuntu?

Create a user first. You must do this as user postgres. Because the postgres system account has no password assigned, you can either set a password first, or you go like this:

sudo /bin/bash
# you should be root now  
su postgres
# you are postgres now
createuser --interactive

and the programm will prompt you.

Sort tuples based on second parameter

    def findMaxSales(listoftuples):
        newlist = []
        tuple = ()
        for item in listoftuples:
             movie = item[0]
             value = (item[1])
             tuple = value, movie

             newlist += [tuple]
             newlist.sort()
             highest = newlist[-1]
             result = highest[1]
       return result

             movieList = [("Finding Dory", 486), ("Captain America: Civil                      

             War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The  Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
             print(findMaxSales(movieList))

output --> Rogue One

How to bind Dataset to DataGridView in windows application

following will show one table of dataset

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = ds; // dataset
DataGridView1.DataMember = "TableName"; // table name you need to show

if you want to show multiple tables, you need to create one datatable or custom object collection out of all tables.

if two tables with same table schema

dtAll = dtOne.Copy(); // dtOne = ds.Tables[0]
dtAll.Merge(dtTwo); // dtTwo = dtOne = ds.Tables[1]

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ; // datatable

sample code to mode all tables

DataTable dtAll = ds.Tables[0].Copy();
for (var i = 1; i < ds.Tables.Count; i++)
{
     dtAll.Merge(ds.Tables[i]);
}
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ;

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

In my case, the backup file was compressed, but the file extension didn't indicate this, didn't end in .zip, .tgz, etc. Once I decompressed my backup file I was able to import it.

Including JavaScript class definition from another file in Node.js

Another way in addition to the ones provided here for ES6

module.exports = class TEST{
    constructor(size) {
        this.map = new MAp();
        this.size = size;

    }

    get(key) {
        return this.map.get(key);
    }

    length() {
        return this.map.size;
    }    

}

and include the same as

var TEST= require('./TEST');
var test = new TEST(1);

If '<selector>' is an Angular component, then verify that it is part of this module

Don't export **default** class MyComponentComponent!

Related issue that might fall under the title, if not the specific question:

I accidentally did a...

export default class MyComponentComponent {

... and that screwed things up too.

Why? VS Code added the import to my module when I put it into declarations, but instead of...

import { MyComponentComponent } from '...';

it had

import MyComponentComponent from '...';

And that didn't map up downstream, assumedly since it wasn't "really" named anywhere with the default import.

export class MyComponentComponent {

No default. Profit.

How to append to a file in Node?

If you want an easy and stress-free way to write logs line by line in a file, then I recommend fs-extra:

const os = require('os');
const fs = require('fs-extra');

const file = 'logfile.txt';
const options = {flag: 'a'};

async function writeToFile(text) {
  await fs.outputFile(file, `${text}${os.EOL}`, options);
}

writeToFile('First line');
writeToFile('Second line');
writeToFile('Third line');
writeToFile('Fourth line');
writeToFile('Fifth line');

Tested with Node v8.9.4.

What's the difference between REST & RESTful

"REST" is an architectural paradigm. "RESTful" describes using that paradigm.

How to parse JSON in Scala using standard Scala classes?

val jsonString =
  """
    |{
    | "languages": [{
    |     "name": "English",
    |     "is_active": true,
    |     "completeness": 2.5
    | }, {
    |     "name": "Latin",
    |     "is_active": false,
    |     "completeness": 0.9
    | }]
    |}
  """.stripMargin

val result = JSON.parseFull(jsonString).map {
  case json: Map[String, List[Map[String, Any]]] =>
    json("languages").map(l => (l("name"), l("is_active"), l("completeness")))
}.get

println(result)

assert( result == List(("English", true, 2.5), ("Latin", false, 0.9)) )

Open and write data to text file using Bash?

For environments where here documents are unavailable (Makefile, Dockerfile, etc) you can often use printf for a reasonably legible and efficient solution.

printf '%s\n' '#!/bin/sh' '# Second line' \
    '# Third line' \
    '# Conveniently mix single and double quotes, too' \
    "# Generated $(date)" \
    '# ^ the date command executes when the file is generated' \
    'for file in *; do' \
    '    echo "Found $file"' \
    'done' >outputfile

Vuejs: v-model array in multiple input

If you were asking how to do it in vue2 and make options to insert and delete it, please, have a look an js fiddle

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    finds: [] _x000D_
  },_x000D_
  methods: {_x000D_
    addFind: function () {_x000D_
      this.finds.push({ value: 'def' });_x000D_
    },_x000D_
    deleteFind: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.finds.splice(index, 1);_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Finds</h1>_x000D_
  <div v-for="(find, index) in finds">_x000D_
    <input v-model="find.value">_x000D_
    <button @click="deleteFind(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addFind">_x000D_
    New Find_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

HTTP Status 405 - Method Not Allowed Error for Rest API

I also had this problem and was able to solve it by enabling CORS support on the server. In my case it was an Azure server and it was easy: Enable CORS on Azure

So check for your server how it works and enable CORS. I didn't even need a browser plugin or proxy :)

How to fix committing to the wrong Git branch?

If you haven't yet pushed your changes, you can also do a soft reset:

git reset --soft HEAD^

This will revert the commit, but put the committed changes back into your index. Assuming the branches are relatively up-to-date with regard to each other, git will let you do a checkout into the other branch, whereupon you can simply commit:

git checkout branch
git commit

The disadvantage is that you need to re-enter your commit message.

window.onload vs $(document).ready()

A little tip:

Always use the window.addEventListener to add an event to window. Because that way you can execute the code in different event handlers .

Correct code:

_x000D_
_x000D_
window.addEventListener('load', function () {_x000D_
  alert('Hello!')_x000D_
})_x000D_
_x000D_
window.addEventListener('load', function () {_x000D_
  alert('Bye!')_x000D_
})
_x000D_
_x000D_
_x000D_

Invalid code:

_x000D_
_x000D_
window.onload = function () {_x000D_
  alert('Hello!') // it will not work!!!_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
  alert('Bye!') _x000D_
}
_x000D_
_x000D_
_x000D_

This is because onload is just property of the object, which is overwritten.

By analogy with addEventListener, it is better to use $(document).ready() rather than onload.

Is it better to use std::memcpy() or std::copy() in terms to performance?

Just a minor addition: The speed difference between memcpy() and std::copy() can vary quite a bit depending on if optimizations are enabled or disabled. With g++ 6.2.0 and without optimizations memcpy() clearly wins:

Benchmark             Time           CPU Iterations
---------------------------------------------------
bm_memcpy            17 ns         17 ns   40867738
bm_stdcopy           62 ns         62 ns   11176219
bm_stdcopy_n         72 ns         72 ns    9481749

When optimizations are enabled (-O3), everything looks pretty much the same again:

Benchmark             Time           CPU Iterations
---------------------------------------------------
bm_memcpy             3 ns          3 ns  274527617
bm_stdcopy            3 ns          3 ns  272663990
bm_stdcopy_n          3 ns          3 ns  274732792

The bigger the array the less noticeable the effect gets, but even at N=1000 memcpy() is about twice as fast when optimizations aren't enabled.

Source code (requires Google Benchmark):

#include <string.h>
#include <algorithm>
#include <vector>
#include <benchmark/benchmark.h>

constexpr int N = 10;

void bm_memcpy(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    memcpy(r.data(), a.data(), N * sizeof(int));
  }
}

void bm_stdcopy(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    std::copy(a.begin(), a.end(), r.begin());
  }
}

void bm_stdcopy_n(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    std::copy_n(a.begin(), N, r.begin());
  }
}

BENCHMARK(bm_memcpy);
BENCHMARK(bm_stdcopy);
BENCHMARK(bm_stdcopy_n);

BENCHMARK_MAIN()

/* EOF */

How to make a SIMPLE C++ Makefile

Why does everyone like to list out source files? A simple find command can take care of that easily.

Here's an example of a dirt simple C++ Makefile. Just drop it in a directory containing .C files and then type make...

appname := myapp

CXX := clang++
CXXFLAGS := -std=c++11

srcfiles := $(shell find . -name "*.C")
objects  := $(patsubst %.C, %.o, $(srcfiles))

all: $(appname)

$(appname): $(objects)
    $(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)

depend: .depend

.depend: $(srcfiles)
    rm -f ./.depend
    $(CXX) $(CXXFLAGS) -MM $^>>./.depend;

clean:
    rm -f $(objects)

dist-clean: clean
    rm -f *~ .depend

include .depend

Is it possible to add an array or object to SharedPreferences on Android

Shared preferences introduced a getStringSet and putStringSet methods in API Level 11, but that's not compatible with older versions of Android (which are still popular), and also is limited to sets of strings.

Android does not provide better methods, and looping over maps and arrays for saving and loading them is not very easy and clean, specially for arrays. But a better implementation isn't that hard:

package com.example.utils;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.content.SharedPreferences;

public class JSONSharedPreferences {
    private static final String PREFIX = "json";

    public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
        editor.commit();
    }

    public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
        editor.commit();
    }

    public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
    }

    public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
    }

    public static void remove(Context c, String prefName, String key) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
            SharedPreferences.Editor editor = settings.edit();
            editor.remove(JSONSharedPreferences.PREFIX+key);
            editor.commit();
        }
    }
}

Now you can save any collection in shared preferences with this five methods. Working with JSONObject and JSONArray is very easy. You can use JSONArray (Collection copyFrom) public constructor to make a JSONArray out of any Java collection and use JSONArray's get methods to access the elements.

There is no size limit for shared preferences (besides device's storage limits), so these methods can work for most of usual cases where you want a quick and easy storage for some collection in your app. But JSON parsing happens here, and preferences in Android are stored as XMLs internally, so I recommend using other persistent data store mechanisms when you're dealing with megabytes of data.

How to download an entire directory and subdirectories using wget?

wget -r --no-parent URL --user=username --password=password

the last two options are optional if you have the username and password for downloading, otherwise no need to use them.

You can also see more options in the link https://www.howtogeek.com/281663/how-to-use-wget-the-ultimate-command-line-downloading-tool/

Jackson overcoming underscores in favor of camel-case

If its a spring boot application, In application.properties file, just use

spring.jackson.property-naming-strategy=SNAKE_CASE

Or Annotate the model class with this annotation.

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

Properly escape a double quote in CSV

Use 2 quotes:

"Samsung U600 24"""

Removing items from a list

for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
    String a = iter.next();
    if (...) {
        iter.remove();
    }
}

Making an additional assumption that the list is of strings. As already answered, an list.iterator() is needed. The listIterator can do a bit of navigation too.

How can I check if an ip is in a network in Python?

previous solution have a bug in ip & net == net. Correct ip lookup is ip & netmask = net

bugfixed code:

import socket
import struct

def makeMask(n):
    "return a mask of n bits as a long integer"
    return (2L<<n-1) - 1

def dottedQuadToNum(ip):
    "convert decimal dotted quad string to long integer"
    return struct.unpack('L',socket.inet_aton(ip))[0]

def addressInNetwork(ip,net,netmask):
   "Is an address in a network"
   print "IP "+str(ip) + " NET "+str(net) + " MASK "+str(netmask)+" AND "+str(ip & netmask)
   return ip & netmask == net

def humannetcheck(ip,net):
        address=dottedQuadToNum(ip)
        netaddr=dottedQuadToNum(net.split("/")[0])
        netmask=makeMask(long(net.split("/")[1]))
        return addressInNetwork(address,netaddr,netmask)


print humannetcheck("192.168.0.1","192.168.0.0/24");
print humannetcheck("192.169.0.1","192.168.0.0/24");

In angular $http service, How can I catch the "status" of error?

Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.

Taken from the angular docs:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

So you'd need to change your code to:

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status); 
  }); 

Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.

How to query first 10 rows and next time query other 10 rows from table

for first 10 rows...

SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT 0,10

for next 10 rows

SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT 10,10

Cannot declare instance members in a static class in C#

As John Weldon said all members must be static in a static class. Try

public static class employee
{
     static NameValueCollection appSetting = ConfigurationManager.AppSettings;    

}

Apply style ONLY on IE

As well as a conditional comment could also use CSS Browser Selector http://rafael.adm.br/css_browser_selector/ as this will allow you to target specific browsers. You can then set your CSS as

.ie .actual-form table {
    width: 100%
    }

This will also allow you to target specific browsers within your main stylesheet without the need for conditional comments.

how to use getSharedPreferences in android

First get the instance of SharedPreferences using

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);

Now to save the values in the SharedPreferences

Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();

Above lines will write username and password to preference

Now to to retrieve saved values from preference, you can follow below lines of code

String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");

(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

If you want to learn, REALLY want to learn, then time is not of consequence. Just move forward everyday. Let your passion for this stuff drive you forward. And one day you'll see that you are good at C#/.NET.

Binding arrow keys in JS/jQuery

This is a bit late, but HotKeys has a very major bug which causes events to get executed multiple times if you attach more than one hotkey to an element. Just use plain jQuery.

$(element).keydown(function(ev) {
    if(ev.which == $.ui.keyCode.DOWN) {
        // your code
        ev.preventDefault();
    }
});

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

You should be able to alias them and use as subqueries (part of the reason your first effort was invalid was because the first select had two columns (ID and ReceivedDate) but your second only had one (ID) - also, Type is a reserved word in SQL Server, and can't be used as you had it as a column name):

declare @Tbl1 table(ID int, ReceivedDate datetime, ItemType Varchar(10))
declare @Tbl2 table(ID int, ReceivedDate datetime, ItemType Varchar(10))

insert into @Tbl1 values(1, '20010101', 'Type_1')
insert into @Tbl1 values(2, '20010102', 'Type_1')
insert into @Tbl1 values(3, '20010103', 'Type_3')

insert into @Tbl2 values(10, '20010101', 'Type_2')
insert into @Tbl2 values(20, '20010102', 'Type_3')
insert into @Tbl2 values(30, '20010103', 'Type_2')

SELECT a.ID, a.ReceivedDate FROM
 (select top 2 t1.ID, t1.ReceivedDate
  from @tbl1 t1
  where t1.ItemType = 'TYPE_1'
  order by ReceivedDate desc
 ) a
union
SELECT b.ID, b.ReceivedDate FROM
 (select top 2 t2.ID, t2.ReceivedDate
  from @tbl2 t2
  where t2.ItemType = 'TYPE_2'
  order by t2.ReceivedDate desc
 ) b

Highest Salary in each department

Not sure why no one has mentioned the Group By .... Having syntax. It specifically addresses these requirements.

select EmpName,DeptId,Salary from EmpDetails group by DeptId having Salary=max(Salary);

Setting Spring Profile variable

In the <tomcat-home>\conf\catalina.properties file, add this new line:

spring.profiles.active=dev

Variable not accessible when initialized outside function

To define a global variable which is based off a DOM element a few things must be checked. First, if the code is in the <head> section, then the DOM will not loaded on execution. In this case, an event handler must be placed in order to set the variable after the DOM has been loaded, like this:

var systemStatus;
window.onload = function(){ systemStatus = document.getElementById("system_status"); };

However, if this script is inline in the page as the DOM loads, then it can be done as long as the DOM element in question has loaded above where the script is located. This is because javascript executes synchronously. This would be valid:

<div id="system_status"></div>
<script type="text/javascript">
 var systemStatus = document.getElementById("system_status");
</script>

As a result of the latter example, most pages which run scripts in the body save them until the very end of the document. This will allow the page to load, and then the javascript to execute which in most cases causes a visually faster rendering of the DOM.

How to check if an email address is real or valid using PHP

I have been searching for this same answer all morning and have pretty much found out that it's probably impossible to verify if every email address you ever need to check actually exists at the time you need to verify it. So as a work around, I kind of created a simple PHP script to verify that the email address is formatted correct and it also verifies that the domain name used is correct as well.

GitHub here https://github.com/DukeOfMarshall/PHP---JSON-Email-Verification/tree/master

<?php

# What to do if the class is being called directly and not being included in a script     via PHP
# This allows the class/script to be called via other methods like JavaScript

if(basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])){
$return_array = array();

if($_GET['address_to_verify'] == '' || !isset($_GET['address_to_verify'])){
    $return_array['error']              = 1;
    $return_array['message']            = 'No email address was submitted for verification';
    $return_array['domain_verified']    = 0;
    $return_array['format_verified']    = 0;
}else{
    $verify = new EmailVerify();

    if($verify->verify_formatting($_GET['address_to_verify'])){
        $return_array['format_verified']    = 1;

        if($verify->verify_domain($_GET['address_to_verify'])){
            $return_array['error']              = 0;
            $return_array['domain_verified']    = 1;
            $return_array['message']            = 'Formatting and domain have been verified';
        }else{
            $return_array['error']              = 1;
            $return_array['domain_verified']    = 0;
            $return_array['message']            = 'Formatting was verified, but verification of the domain has failed';
        }
    }else{
        $return_array['error']              = 1;
        $return_array['domain_verified']    = 0;
        $return_array['format_verified']    = 0;
        $return_array['message']            = 'Email was not formatted correctly';
    }
}

echo json_encode($return_array);

exit();
}

class EmailVerify {
public function __construct(){

}

public function verify_domain($address_to_verify){
    // an optional sender  
    $record = 'MX';
    list($user, $domain) = explode('@', $address_to_verify);
    return checkdnsrr($domain, $record);
}

public function verify_formatting($address_to_verify){
    if(strstr($address_to_verify, "@") == FALSE){
        return false;
    }else{
        list($user, $domain) = explode('@', $address_to_verify);

        if(strstr($domain, '.') == FALSE){
            return false;
        }else{
            return true;
        }
    }
    }
}
?>

Cache an HTTP 'Get' service response in AngularJS?

I think there's an even easier way now. This enables basic caching for all $http requests (which $resource inherits):

 var app = angular.module('myApp',[])
      .config(['$httpProvider', function ($httpProvider) {
            // enable http caching
           $httpProvider.defaults.cache = true;
      }])

copy all files and folders from one drive to another drive using DOS (command prompt)

xcopy "C:\SomeFolderName" "D:\SomeFolderName" /h /i /c /k /e /r /y

Use the above command. It will definitely work.

In this command data will be copied from c:\ to D:\, even folders and system files as well. Here's what the flags do:

  • /h copies hidden and system files also
  • /i if destination does not exist and copying more than one file, assume that destination must be a directory
  • /c continue copying even if error occurs
  • /k copies attributes
  • /e copies directories and subdirectories, including empty ones
  • /r overwrites read-only files
  • /y suppress prompting to confirm whether you want to overwrite a file

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

ASP.NET MVC - Extract parameter of an URL

I'm not familiar with ASP.NET but I guess you could use a split function to split it in an array using the / as delimiter, then grab the last element in the array (usually the array length -1) to get the extract you want.

Ok this does not seem to work for all the examples.

What about a regex?

.*(/|[a-zA-Z]+\?)(.*)

then get that last subexpression (.*), I believe it's $+ in .Net, I'm not sure

Rename multiple files based on pattern in Unix

Generic command would be

find /path/to/files -name '<search>*' -exec bash -c 'mv $0 ${0/<search>/<replace>}' {} \;

where <search> and <replace> should be replaced with your source and target respectively.

As a more specific example tailored to your problem (should be run from the same folder where your files are), the above command would look like:

find . -name 'gfh*' -exec bash -c 'mv $0 ${0/gfh/jkl}' {} \;

For a "dry run" add echo before mv, so that you'd see what commands are generated:

find . -name 'gfh*' -exec bash -c 'echo mv $0 ${0/gfh/jkl}' {} \;

Make one div visible and another invisible

Making it invisible with visibility still makes it use up space. Rather try set the display to none to make it invisible, and then set the display to block to make it visible.

How to restart remote MySQL server running on Ubuntu linux?

sudo service mysql stop;
sudo service mysql start;

If the above process will not work let's check one the given code above you can stop Mysql server and again start server

How to use boolean datatype in C?

If you have a compiler that supports C99 you can

#include <stdbool.h>

Otherwise, you can define your own if you'd like. Depending on how you want to use it (and whether you want to be able to compile your code as C++), your implementation could be as simple as:

#define bool int
#define true 1
#define false 0

In my opinion, though, you may as well just use int and use zero to mean false and nonzero to mean true. That's how it's usually done in C.

A fast way to delete all rows of a datatable at once

That's the easiest way to delete all rows from the table in dbms via DataAdapter. But if you want to do it in one batch, you can set the DataAdapter's UpdateBatchSize to 0(unlimited).

Another way would be to use a simple SqlCommand with CommandText DELETE FROM Table:

using(var con = new SqlConnection(ConfigurationSettings.AppSettings["con"]))
using(var cmd = new SqlCommand())
{
    cmd.CommandText = "DELETE FROM Table";
    cmd.Connection = con;
    con.Open();
    int numberDeleted = cmd.ExecuteNonQuery();  // all rows deleted
}

But if you instead only want to remove the DataRows from the DataTable, you just have to call DataTable.Clear. That would prevent any rows from being deleted in dbms.

From io.Reader to string in Go

var b bytes.Buffer
b.ReadFrom(r)

// b.String()

How do I install cURL on cygwin?

I just ran into this.

If you're not seeing curl in the list (see ibaralf's screenshot), then you may have out-of-date cygwin sources. In one of the screens in cygwin's setup.exe wizard, you have the option to "Install from Internet" or "Install from Local Directory". If you have the "Install from Local Directory" option enabled, then you may not see curl in the list. Switch to "Install from Internet" and select a mirror and then you should see curl.

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

Failed to install *.apk on device 'emulator-5554': EOF

Neither above helped me, instead, I connected my phone through the back USB hubs (I used forward USB hubs previously), and this helped me!

Reading Excel file using node.js

Useful link

https://ciphertrick.com/read-excel-files-convert-json-node-js/

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

how to use LIKE with column name

...
WHERE table1.x LIKE table2.y + '%'

How to align footer (div) to the bottom of the page?

This will make the div fixed at the bottom of the page but in case the page is long it will only be visible when you scroll down.

<style type="text/css">
  #footer {
    position : absolute;
    bottom : 0;
    height : 40px;
    margin-top : 40px;
  }
</style>
<div id="footer">I am footer</div>

The height and margin-top should be the same so that the footer doesnt show over the content.

How do you reverse a string in place in JavaScript?

My own original attempt...

var str = "The Car";

function reverseStr(str) {
  var reversed = "";
  var len = str.length;
  for (var i = 1; i < (len + 1); i++) {  
    reversed += str[len - i];      
  }

  return reversed;
}

var strReverse = reverseStr(str);    
console.log(strReverse);
// "raC ehT"

http://jsbin.com/bujiwo/19/edit?js,console,output

How to run a makefile in Windows?

I tried with cygwin & gnuwin, and didn't worked for me, I guess because the makefile used mainly specific linux code.

What it worked was use Ubuntu Bash for Windows 10. This is a Marvel if you come from MAC as it is my case:

  1. To install the Ubuntu Bash: https://itsfoss.com/install-bash-on-windows/
  2. Once in the console, to install make simply type "make" and it gives the instructions to download it.

Extras:

  1. Useful enable copy / paste on bash: Copy Paste in Bash on Ubuntu on Windows
  2. In my case the make called Maven, so I have to install it as well: https://askubuntu.com/questions/722993/unable-to-locate-package-maven
  3. To access windows filesystem C: drive, for example: "cd /mnt/c/"

Hope it helps

If Cell Starts with Text String... Formula

I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.

I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"s","l","m"}, {-1,1,0})

and it started working when I did this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"l","m","s"}, {1,0,-1})

I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.

Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.

Changing the page title with Jquery

There's no need to use jQuery to change the title. Try:

document.title = "blarg";

See this question for more details.

To dynamically change on button click:

$(selectorForMyButton).click(function(){
    document.title = "blarg";
});

To dynamically change in loop, try:

var counter = 0;

var titleTimerId = setInterval(function(){
    document.title = document.title + '>';
    counter++;
    if(counter == 5){
        clearInterval(titleTimerId);
    }
}, 100);

To string the two together so that it dynamically changes on button click, in a loop:

var counter = 0;

$(selectorForMyButton).click(function(){
  titleTimerId = setInterval(function(){
    document.title = document.title + '>';
    counter++;
    if(counter == 5){
        clearInterval(titleTimerId);
    }
  }, 100);
});

Is it safe to expose Firebase apiKey to the public?

EXPOSURE OF API KEYS ISN'T A SECURITY RISK BUT ANYONE CAN PUT YOUR CREDENTIALS ON THEIR SITE.

Open api keys leads to attacks that can use a lot resources at firebase that will definitely cost your hard money.

You can always restrict you firebase project keys to domains / IP's.

https://console.cloud.google.com/apis/credentials/key

select your project Id and key and restrict it to Your Android/iOs/web App.

javascript, is there an isObject function like isArray?

You can use typeof operator.

if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
    alert("A is object");
}

Note that because typeof new Number(1) === 'object' while typeof Number(1) === 'number'; the first syntax should be avoided.

Android Use Done button on Keyboard to click button

You can implement on key listener:

public class ProbabilityActivity extends Activity implements OnClickListener, View.OnKeyListener {

In onCreate:

max.setOnKeyListener(this);

...

@Override
public boolean onKey(View v, int keyCode, KeyEvent event){
    if(keyCode == event.KEYCODE_ENTER){
        //call your button method here
    }
    return true;
}

How can I disable the bootstrap hover color for links?

I would go with something like this JSFiddle:

HTML:

<a class="green" href="#">green text</a>
<a class="yellow" href="#">yellow text</a>

CSS:

body  { background: #ccc }
/* Green */
a.green,
a.green:hover { color: green; }
/* Yellow */
a.yellow,
a.yellow:hover { color: yellow; }

How to link external javascript file onclick of button

I have to agree with the comments above, that you can't call a file, but you could load a JS file like this, I'm unsure if it answers your question but it may help... oh and I've used a link instead of a button in my example...

<a href='linkhref.html' id='mylink'>click me</a>

<script type="text/javascript">

var myLink = document.getElementById('mylink');

myLink.onclick = function(){

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "Public/Scripts/filename.js."; 
    document.getElementsByTagName("head")[0].appendChild(script);
    return false;

}


</script>

How to write a link like <a href="#id"> which link to the same page in PHP?

Edit:

Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs


See the working example: http://jsfiddle.net/U6aKT/

<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>

How to set a value to a file input in HTML?

Actually we can do it. we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form. Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed. So,

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
       FormToMultipartPostData postData = 
            new FormToMultipartPostData(webBrowser1, form);
        postData.SetFile("fileField", @"C:\windows\win.ini");
        postData.Submit();
    }

Refer the below link for downloading and complete reference.

https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com

How to find the socket buffer size of linux

For getting the buffer size in c/c++ program the following is the flow

int n;
unsigned int m = sizeof(n);
int fdsocket;
fdsocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); // example
getsockopt(fdsocket,SOL_SOCKET,SO_RCVBUF,(void *)&n, &m);
// now the variable n will have the socket size

Search for a string in all tables, rows and columns of a DB

I adapted a script originally written by Narayana Vyas Kondreddi in 2002. I changed the where clause to check text/ntext fields as well, by using patindex rather than like. I also changed the results table slightly. Unreasonably, I changed variable names, and aligned as I prefer (no disrespect to Mr. Kondretti). The user may want to change the data types searched. I used a global table to allow querying mid-processing, but a permanent table might be a smarter way to go.

/* original script by Narayana Vyas Kondreddi, 2002 */
/* adapted by Oliver Holloway, 2009 */

/* these lines can be replaced by use of input parameter for a proc */
declare @search_string varchar(1000);
set @search_string = 'what.you.are.searching.for';

/* create results table */
create table ##string_locations (
  table_name varchar(1000),
  field_name varchar(1000),
  field_value varchar(8000)
)
;
/* special settings */
set nocount on
;
/* declare variables */
declare
  @table_name varchar(1000),
  @field_name varchar(1000)
;
/* variable settings */
set @table_name = ''
;
set @search_string = QUOTENAME('%' + @search_string + '%','''')
;
/* for each table */
while @table_name is not null
begin

  set @field_name = ''
  set @table_name = (
    select MIN(QUOTENAME(table_schema) + '.' + QUOTENAME(table_name))
    from INFORMATION_SCHEMA.TABLES
    where 
      table_type = 'BASE TABLE' and
      QUOTENAME(table_schema) + '.' + QUOTENAME(table_name) > @table_name and
      OBJECTPROPERTY(OBJECT_ID(QUOTENAME(table_schema) + '.' + QUOTENAME(table_name)), 'IsMSShipped') = 0
  )

  /* for each string-ish field */
  while (@table_name is not null) and (@field_name is not null)
  begin
    set @field_name = (
      select MIN(QUOTENAME(column_name))
      from INFORMATION_SCHEMA.COLUMNS
      where 
        table_schema    = PARSENAME(@table_name, 2) and
        table_name  = PARSENAME(@table_name, 1) and
        data_type in ('char', 'varchar', 'nchar', 'nvarchar', 'text', 'ntext') and
        QUOTENAME(column_name) > @field_name
    )

    /* search that field for the string supplied */
    if @field_name is not null
    begin
      insert into ##string_locations
      exec(
        'select ''' + @table_name + ''',''' + @field_name + ''',' + @field_name + 
        'from ' + @table_name + ' (nolock) ' +
        'where patindex(' + @search_string + ',' + @field_name + ') > 0'  /* patindex works with char & text */
      )
    end
    ;
  end
  ;
end
;

/* return results */
select table_name, field_name, field_value from ##string_locations (nolock)
;
/* drop temp table */
--drop table ##string_locations
;

Print a list in reverse order with range()?

I thought that many (as myself) could be more interested in a common case of traversing an existing list in reversed order instead, as it's stated in the title, rather than just generating indices for such traversal.

Even though, all the right answers are still perfectly fine for this case, I want to point out that the performance comparison done in Wolf's answer is for generating indices only. So I've made similar benchmark for traversing an existing list in reversed order.

TL;DR a[::-1] is the fastest.

NB: If you want more detailed analysis of different reversal alternatives and their performance, check out this great answer.

Prerequisites:

a = list(range(10))

Jason's answer:

%timeit [a[9-i] for i in range(10)]
1.27 µs ± 61.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

martineau's answer:

%timeit a[::-1]
135 ns ± 4.07 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Michal Šrajer's answer:

%timeit list(reversed(a))
374 ns ± 9.87 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

bene's answer:

%timeit [a[i] for i in range(9, -1, -1)]
1.09 µs ± 11.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

As you see, in this case there's no need to explicitly generate indices, so the fastest method is the one that makes less extra actions.

NB: I tested in JupyterLab which has handy "magic command" %timeit. It uses standard timeit.timeit under the hood. Tested for Python 3.7.3

React - How to get parameter value from query string?

you can check the react-router, in simple,you can use the code to get query parameter as long as you defined in your router:

this.props.params.userId

How can I create directories recursively?

Here is my implementation for your reference:

def _mkdir_recursive(self, path):
    sub_path = os.path.dirname(path)
    if not os.path.exists(sub_path):
        self._mkdir_recursive(sub_path)
    if not os.path.exists(path):
        os.mkdir(path)

Hope this help!

Function to calculate R2 (R-squared) in R

You can also use the summary for linear models:

summary(lm(obs ~ mod, data=df))$r.squared 

Installing a pip package from within a Jupyter Notebook not working

Alternative option : you can also create a bash cell in jupyter using bash kernel and then pip install geocoder. That should work

MySQL, Check if a column exists in a table with SQL

I threw this stored procedure together with a start from @lain's comments above, kind of nice if you need to call it more than a few times (and not needing php):

delimiter //
-- ------------------------------------------------------------
-- Use the inforamtion_schema to tell if a field exists.
-- Optional param dbName, defaults to current database
-- ------------------------------------------------------------
CREATE PROCEDURE fieldExists (
OUT _exists BOOLEAN,      -- return value
IN tableName CHAR(255),   -- name of table to look for
IN columnName CHAR(255),  -- name of column to look for
IN dbName CHAR(255)       -- optional specific db
) BEGIN
-- try to lookup db if none provided
SET @_dbName := IF(dbName IS NULL, database(), dbName);

IF CHAR_LENGTH(@_dbName) = 0
THEN -- no specific or current db to check against
  SELECT FALSE INTO _exists;
ELSE -- we have a db to work with
  SELECT IF(count(*) > 0, TRUE, FALSE) INTO _exists
  FROM information_schema.COLUMNS c
  WHERE 
  c.TABLE_SCHEMA    = @_dbName
  AND c.TABLE_NAME  = tableName
  AND c.COLUMN_NAME = columnName;
END IF;
END //
delimiter ;

Working with fieldExists

mysql> call fieldExists(@_exists, 'jos_vm_product', 'child_option', NULL) //
Query OK, 0 rows affected (0.01 sec)

mysql> select @_exists //
+----------+
| @_exists |
+----------+
|        0 |
+----------+
1 row in set (0.00 sec)

mysql> call fieldExists(@_exists, 'jos_vm_product', 'child_options', 'etrophies') //
Query OK, 0 rows affected (0.01 sec)

mysql> select @_exists //
+----------+
| @_exists |
+----------+
|        1 |
+----------+

How to run a script file remotely using SSH

If you want to execute a local script remotely without saving that script remotely you can do it like this:

cat local_script.sh | ssh user@remotehost 'bash -'

It works like a charm for me.

I do that even from Windows to Linux given that you have MSYS installed on your Windows computer.

MongoDB SELECT COUNT GROUP BY

Starting in MongoDB 3.4, you can use the $sortByCount aggregation.

Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.

https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/

For example:

db.contest.aggregate([
    { $sortByCount: "$province" }
]);

async at console app in C#?

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

class Program
{
    public static JSONServer srv = null;

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

        srv = new JSONServer(100);
        srv.Start();

        InputLoopProcessor();

        while(srv.IsRunning)
        {
            Thread.Sleep(250);
        }

    }

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

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

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

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

    }
}

Parse usable Street Address, City, State, Zip from a string

+1 on James A. Rosen's suggested solution as it has worked well for me, however for completists this site is a fascinating read and the best attempt I've seen in documenting addresses worldwide: http://www.columbia.edu/kermit/postal.html

Waiting for another flutter command to release the startup lock

There are some action to do:

1- in pubspec.yaml press "packages get" or in terminal type " flutter packages get" and wait seconds.

if this doesn't work :

2-type flutter clean then do step(1)

if this doesn't work too :

3-type killtask /f /im dart.exe

if this doesn't work too :

4- close android studio and then restart your pc.

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

I have encountered this problem.

I'm using buildSrc in my project.

I think the problem is with buildSrc. To solve the problem;

1- Kotlin and Android Stuido version updated (Kotlin version is 1.3.21, Android Studio version is 3.4)

2- Clean cache and restart android studio

But the problem is not solved.

As a last resort, I deleted the project file and clone it over git and the problem is solved

How to fix the "508 Resource Limit is reached" error in WordPress?

Actually it happens when the number of processes exceeds the limits set by the hosting provider.

To avoid either we need to enhance the capacity by hosting providers or we need to check in the code whether any process takes longer time (like background tasks).

Unix: How to delete files listed in a file

Just to provide an another way, you can also simply use the following command

$ cat to_remove
/tmp/file1
/tmp/file2
/tmp/file3
$ rm $( cat to_remove )

.NET - Get protocol, host, and port

Well if you are doing this in Asp.Net or have access to HttpContext.Current.Request I'd say these are easier and more general ways of getting them:

var scheme = Request.Url.Scheme; // will get http, https, etc.
var host = Request.Url.Host; // will get www.mywebsite.com
var port = Request.Url.Port; // will get the port
var path = Request.Url.AbsolutePath; // should get the /pages/page1.aspx part, can't remember if it only get pages/page1.aspx

I hope this helps. :)

YAML mapping values are not allowed in this context

The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:

jobs:
 - - name: A
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120
 - - name: B
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120

Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.

Gaussian fit for Python

sigma = sum(y*(x - mean)**2)

should be

sigma = np.sqrt(sum(y*(x - mean)**2))

Using %f with strftime() in Python to get microseconds

You can use datetime's strftime function to get this. The problem is that time's strftime accepts a timetuple that does not carry microsecond information.

from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")

Should do the trick!

Get multiple elements by Id

More than one Element with the same ID is not allowed, getElementById Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.

Extract substring using regexp in plain bash

If your string is

foo="US/Central - 10:26 PM (CST)"

then

echo "${foo}" | cut -d ' ' -f3

will do the job.

How can I submit a POST form using the <a href="..."> tag?

You have to use Javascript submit function on your form object. Take a look in other functions.

<form action="showMessage.jsp" method="post">
    <a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
    <input type="hidden" name="mess" value=<%=n%>/>
</form>

Can an XSLT insert the current date?

For MSXML parser, try this:

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt"
                xmlns:my="urn:sample" extension-element-prefixes="msxml">

    <msxsl:script language="JScript" implements-prefix="my">
       function today()
       {
          return new Date(); 
       } 
    </msxsl:script> 
    <xsl:template match="/">

        Today = <xsl:value-of select="my:today()"/>

    </xsl:template> 
</xsl:stylesheet>

Also read XSLT Stylesheet Scripting using msxsl:script and Extending XSLT with JScript, C#, and Visual Basic .NET

What is the Swift equivalent of isEqualToString in Objective-C?

For the UITextField text comparison I am using below code and working fine for me, let me know if you find any error.

if(txtUsername.text.isEmpty || txtPassword.text.isEmpty)
{
    //Do some stuff
}
else if(txtUsername.text == "****" && txtPassword.text == "****")
{
    //Do some stuff
}

How to open local files in Swagger-UI

This is how I worked with local swagger JSON

  1. Have tomcat running in local machine
  2. Download Swagger UI application and unzip it into tomcat's /webapps/swagger folder
  3. Drop local swagger json file inside /webapps/swagger folder of tomcat
  4. Start up tomcat (/bin/sh startup.sh)
  5. Open a browser and navigate to http://localhost:8080/swagger/
  6. type your swagger json file in the Swagger Explore test box and this should render the APIs.

Hope this works for you

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

This one just worked for me....

The error message displayed is:

“# 1146 – Table ‘phpmyadmin.pma_table_uiprefs’ doesn’t exist“

on your programme files,locate the configuration file config.inc.php phpmyadmin

Then trace the file $Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma_table_uiprefs’;

and replace it to the code : $cfg ['Servers'] [$ i] ['pma__table_uiprefs'] = ‘pma__table_uiprefs’;

restart your XAMMP and start localhost

solved.

Showing percentages above bars on Excel column graph

You can do this with a pivot table and add a line with the pourcentage for each category like brettdj showed in his answer. But if you want to keep your data as it is, there is a solution by using some javascript.

Javascript is a powerful language offering a lot of useful data visualization libraries like plotly.js.

Here is a working code I have written for you:

https://www.funfun.io/1/#/edit/5a58c6368dfd67466879ed27

In this example, I use a Json file to get the data from the embedded spreadsheet, so I can use it in my javascript code and create a bar chart.

I calculate the percentage by adding the values of all the category present in the table and using this formula (you can see it in the script.js file): Percentage (%) = 100 x partial value / total value

It automatically calculates the total and pourcentage even if you add more categories.

I used plotly.js to create my chart, it has a good documentation and lots of examples for beginners, this code gets all the option you want to use:

var trace1 = {
    x: xValue, 
    y: data,
    type: 'bar',
    text: yValue,
    textposition: 'auto',
    hoverinfo: 'none',
    marker: {
    color: 'yellow',
    opacity: 0.6,
    line: {
      color: 'yellow',
      width: 1.5
    }
  }
};

It is rather self explanatory, the text is where you put the percentage.

Once you've made your chart you can load it in excel by passing the URL in the Funfun add-in. Here is how it looks like with my example:

final

I know it is an old post but I hope it helps people with the same problem !

Disclosure : I’m a developer of funfun

Zero an array in C code

int arr[20];
memset(arr, 0, sizeof arr);

See the reference for memset

How can I remove a style added with .css() function?

This one also work!!

$elem.attr('style','');

What is the OAuth 2.0 Bearer Token exactly?

Please read the example in rfc6749 sec 7.1 first.

The bearer token is a type of access token, which does NOT require PoP(proof-of-possession) mechanism.

PoP means kind of multi-factor authentication to make access token more secure. ref

Proof-of-Possession refers to Cryptographic methods that mitigate the risk of Security Tokens being stolen and used by an attacker. In contrast to 'Bearer Tokens', where mere possession of the Security Token allows the attacker to use it, a PoP Security Token cannot be so easily used - the attacker MUST have both the token itself and access to some key associated with the token (which is why they are sometimes referred to 'Holder-of-Key' (HoK) tokens).

Maybe it's not the case, but I would say,

  • access token = payment methods
  • bearer token = cash
  • access token with PoP mechanism = credit card (signature or password will be verified, sometimes need to show your ID to match the name on the card)

BTW, there's a draft of "OAuth 2.0 Proof-of-Possession (PoP) Security Architecture" now.

Dump a NumPy array into a csv file

numpy.savetxt saves an array to a text file.

import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")

How to check if a double value has no decimal part

double d = 14.4;
if((d-(int)d)!=0)
    System.out.println("decimal value is there");
else
    System.out.println("decimal value is not there");

phpMyAdmin allow remote users

Replace the contents of the first <directory> tag.

Remove:

<Directory /usr/share/phpMyAdmin/>
 <IfModule mod_authz_core.c>
  # Apache 2.4
  <RequireAny>
    Require ip 127.0.0.1
    Require ip ::1
  </RequireAny>
 </IfModule>
 <IfModule !mod_authz_core.c>
  # Apache 2.2
  Order Deny,Allow
  Deny from All
  Allow from 127.0.0.1
  Allow from ::1
 </IfModule>
</Directory>

And place this instead:

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

Don't forget to restart Apache afterwards.

Xcode 4: How do you view the console?

There's two options:

  1. Log Navigator (command-7 or view|navigators|log) and select your debug session.

  2. "View | Show Debug Area" to view the NSLog output and interact with the debugger.

Here's a pic with both on. You wouldn't normally have both on, but I can only link one image per post! http://i.stack.imgur.com/4gG4P.png

How can I set the background color of <option> in a <select> element?

Just like normal background-color: #f0f

You just need a way to target it, eg: <option id="myPinkOption">blah</option>

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

When working with HTTP it's almost always more useful to refer to HttpURLConnection rather than the base class URLConnection (since URLConnection is an abstract class when you ask for URLConnection.openConnection() on a HTTP URL that's what you'll get back anyway).

Then you can instead of relying on URLConnection#setDoOutput(true) to implicitly set the request method to POST instead do httpURLConnection.setRequestMethod("POST") which some might find more natural (and which also allows you to specify other request methods such as PUT, DELETE, ...).

It also provides useful HTTP constants so you can do:

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

error LNK2005, already defined?

In the Project’s Settings, add /FORCE:MULTIPLE to the Linker’s Command Line options.

From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."

Ruby max integer

In ruby Fixnums are automatically converted to Bignums.

To find the highest possible Fixnum you could do something like this:

class Fixnum
 N_BYTES = [42].pack('i').size
 N_BITS = N_BYTES * 8
 MAX = 2 ** (N_BITS - 2) - 1
 MIN = -MAX - 1
end
p(Fixnum::MAX)

Shamelessly ripped from a ruby-talk discussion. Look there for more details.

How do I get the time of day in javascript/Node.js?

If you only want the time string you can use this expression (with a simple RegEx):

new Date().toISOString().match(/(\d{2}:){2}\d{2}/)[0]
// "23:00:59"

How do I install cURL on Windows?

You may find XAMPP at http://www.apachefriends.org/en/xampp.html

http://www.apachefriends.org/en/xampp-windows.html explains XMAPP for Windows.

Yes, there are 3 php.ini files after installation, one is for php4, one is for php5, and one is for apache. Please modify them accordingly.

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

By using synchronized on a static method lock you will synchronize the class methods and attributes ( as opposed to instance methods and attributes )

So your assumption is correct.

I am wondering if making the method synchronized is the right approach to ensure thread-safety.

Not really. You should let your RDBMS do that work instead. They are good at this kind of stuff.

The only thing you will get by synchronizing the access to the database is to make your application terribly slow. Further more, in the code you posted you're building a Session Factory each time, that way, your application will spend more time accessing the DB than performing the actual job.

Imagine the following scenario:

Client A and B attempt to insert different information into record X of table T.

With your approach the only thing you're getting is to make sure one is called after the other, when this would happen anyway in the DB, because the RDBMS will prevent them from inserting half information from A and half from B at the same time. The result will be the same but only 5 times ( or more ) slower.

Probably it could be better to take a look at the "Transactions and Concurrency" chapter in the Hibernate documentation. Most of the times the problems you're trying to solve, have been solved already and a much better way.

How to parse the AndroidManifest.xml file inside an .apk package

for reference here is my version of Ribo's code. The main difference is that decompressXML() directly returns a String, which for my purposes was a more appropriate usage.

NOTE: my sole purpose in using Ribo's solution was to fetch an .APK file's published version from the Manifest XML file, and I confirm that for this purpose it works beautifully.

EDIT [2013-03-16]: It works beautifully IF the version is set as plain text, but if it's set to refer to a Resource XML, it'll show up as 'Resource 0x1' for example. In this particular case, you'll probably have to couple this solution to another solution that will fetch the proper string resource reference.

/**
 * Binary XML doc ending Tag
 */
public static int endDocTag = 0x00100101;

/**
 * Binary XML start Tag
 */
public static int startTag =  0x00100102;

/**
 * Binary XML end Tag
 */
public static int endTag =    0x00100103;


/**
 * Reference var for spacing
 * Used in prtIndent()
 */
public static String spaces = "                                             ";


/**
 * Parse the 'compressed' binary form of Android XML docs 
 * such as for AndroidManifest.xml in .apk files
 * Source: http://stackoverflow.com/questions/2097813/how-to-parse-the-androidmanifest-xml-file-inside-an-apk-package/4761689#4761689
 * 
 * @param xml Encoded XML content to decompress
 */
public static String decompressXML(byte[] xml) {

    StringBuilder resultXml = new StringBuilder();

    // Compressed XML file/bytes starts with 24x bytes of data,
    // 9 32 bit words in little endian order (LSB first):
    //   0th word is 03 00 08 00
    //   3rd word SEEMS TO BE:  Offset at then of StringTable
    //   4th word is: Number of strings in string table
    // WARNING: Sometime I indiscriminently display or refer to word in 
    //   little endian storage format, or in integer format (ie MSB first).
    int numbStrings = LEW(xml, 4*4);

    // StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
    // of the length/string data in the StringTable.
    int sitOff = 0x24;  // Offset of start of StringIndexTable

    // StringTable, each string is represented with a 16 bit little endian 
    // character count, followed by that number of 16 bit (LE) (Unicode) chars.
    int stOff = sitOff + numbStrings*4;  // StringTable follows StrIndexTable

    // XMLTags, The XML tag tree starts after some unknown content after the
    // StringTable.  There is some unknown data after the StringTable, scan
    // forward from this point to the flag for the start of an XML start tag.
    int xmlTagOff = LEW(xml, 3*4);  // Start from the offset in the 3rd word.
    // Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
    for (int ii=xmlTagOff; ii<xml.length-4; ii+=4) {
      if (LEW(xml, ii) == startTag) { 
        xmlTagOff = ii;  break;
      }
    } // end of hack, scanning for start of first start tag

    // XML tags and attributes:
    // Every XML start and end tag consists of 6 32 bit words:
    //   0th word: 02011000 for startTag and 03011000 for endTag 
    //   1st word: a flag?, like 38000000
    //   2nd word: Line of where this tag appeared in the original source file
    //   3rd word: FFFFFFFF ??
    //   4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
    //   5th word: StringIndex of Element Name
    //   (Note: 01011000 in 0th word means end of XML document, endDocTag)

    // Start tags (not end tags) contain 3 more words:
    //   6th word: 14001400 meaning?? 
    //   7th word: Number of Attributes that follow this tag(follow word 8th)
    //   8th word: 00000000 meaning??

    // Attributes consist of 5 words: 
    //   0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
    //   1st word: StringIndex of Attribute Name
    //   2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
    //   3rd word: Flags?
    //   4th word: str ind of attr value again, or ResourceId of value

    // TMP, dump string table to tr for debugging
    //tr.addSelect("strings", null);
    //for (int ii=0; ii<numbStrings; ii++) {
    //  // Length of string starts at StringTable plus offset in StrIndTable
    //  String str = compXmlString(xml, sitOff, stOff, ii);
    //  tr.add(String.valueOf(ii), str);
    //}
    //tr.parent();

    // Step through the XML tree element tags and attributes
    int off = xmlTagOff;
    int indent = 0;
    int startTagLineNo = -2;
    while (off < xml.length) {
      int tag0 = LEW(xml, off);
      //int tag1 = LEW(xml, off+1*4);
      int lineNo = LEW(xml, off+2*4);
      //int tag3 = LEW(xml, off+3*4);
      int nameNsSi = LEW(xml, off+4*4);
      int nameSi = LEW(xml, off+5*4);

      if (tag0 == startTag) { // XML START TAG
        int tag6 = LEW(xml, off+6*4);  // Expected to be 14001400
        int numbAttrs = LEW(xml, off+7*4);  // Number of Attributes to follow
        //int tag8 = LEW(xml, off+8*4);  // Expected to be 00000000
        off += 9*4;  // Skip over 6+3 words of startTag data
        String name = compXmlString(xml, sitOff, stOff, nameSi);
        //tr.addSelect(name, null);
        startTagLineNo = lineNo;

        // Look for the Attributes
        StringBuffer sb = new StringBuffer();
        for (int ii=0; ii<numbAttrs; ii++) {
          int attrNameNsSi = LEW(xml, off);  // AttrName Namespace Str Ind, or FFFFFFFF
          int attrNameSi = LEW(xml, off+1*4);  // AttrName String Index
          int attrValueSi = LEW(xml, off+2*4); // AttrValue Str Ind, or FFFFFFFF
          int attrFlags = LEW(xml, off+3*4);  
          int attrResId = LEW(xml, off+4*4);  // AttrValue ResourceId or dup AttrValue StrInd
          off += 5*4;  // Skip over the 5 words of an attribute

          String attrName = compXmlString(xml, sitOff, stOff, attrNameSi);
          String attrValue = attrValueSi!=-1
            ? compXmlString(xml, sitOff, stOff, attrValueSi)
            : "resourceID 0x"+Integer.toHexString(attrResId);
          sb.append(" "+attrName+"=\""+attrValue+"\"");
          //tr.add(attrName, attrValue);
        }
        resultXml.append(prtIndent(indent, "<"+name+sb+">"));
        indent++;

      } else if (tag0 == endTag) { // XML END TAG
        indent--;
        off += 6*4;  // Skip over 6 words of endTag data
        String name = compXmlString(xml, sitOff, stOff, nameSi);
        resultXml.append(prtIndent(indent, "</"+name+">  (line "+startTagLineNo+"-"+lineNo+")"));
        //tr.parent();  // Step back up the NobTree

      } else if (tag0 == endDocTag) {  // END OF XML DOC TAG
        break;

      } else {
          Log.e(TAG, "  Unrecognized tag code '"+Integer.toHexString(tag0)
          +"' at offset "+off);
        break;
      }
    } // end of while loop scanning tags and attributes of XML tree
    Log.i(TAG, "    end at offset "+off);

    return resultXml.toString();
} // end of decompressXML


/**
 * Tool Method for decompressXML();
 * Compute binary XML to its string format 
 * Source: Source: http://stackoverflow.com/questions/2097813/how-to-parse-the-androidmanifest-xml-file-inside-an-apk-package/4761689#4761689
 * 
 * @param xml Binary-formatted XML
 * @param sitOff
 * @param stOff
 * @param strInd
 * @return String-formatted XML
 */
public static String compXmlString(byte[] xml, int sitOff, int stOff, int strInd) {
  if (strInd < 0) return null;
  int strOff = stOff + LEW(xml, sitOff+strInd*4);
  return compXmlStringAt(xml, strOff);
}


/**
 * Tool Method for decompressXML(); 
 * Apply indentation
 * 
 * @param indent Indentation level
 * @param str String to indent
 * @return Indented string
 */
public static String prtIndent(int indent, String str) {

    return (spaces.substring(0, Math.min(indent*2, spaces.length()))+str);
}


/** 
 * Tool method for decompressXML()
 * Return the string stored in StringTable format at
 * offset strOff.  This offset points to the 16 bit string length, which 
 * is followed by that number of 16 bit (Unicode) chars.
 * 
 * @param arr StringTable array
 * @param strOff Offset to get string from
 * @return String from StringTable at offset strOff
 * 
 */
public static String compXmlStringAt(byte[] arr, int strOff) {
  int strLen = arr[strOff+1]<<8&0xff00 | arr[strOff]&0xff;
  byte[] chars = new byte[strLen];
  for (int ii=0; ii<strLen; ii++) {
    chars[ii] = arr[strOff+2+ii*2];
  }
  return new String(chars);  // Hack, just use 8 byte chars
} // end of compXmlStringAt


/** 
 * Return value of a Little Endian 32 bit word from the byte array
 *   at offset off.
 * 
 * @param arr Byte array with 32 bit word
 * @param off Offset to get word from
 * @return Value of Little Endian 32 bit word specified
 */
public static int LEW(byte[] arr, int off) {
  return arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000
    | arr[off+1]<<8&0xff00 | arr[off]&0xFF;
} // end of LEW

Hope it can help other people too.

How can I check if a file exists in Perl?

#!/usr/bin/perl -w

$fileToLocate = '/whatever/path/for/file/you/are/searching/MyFile.txt';
if (-e $fileToLocate) {
    print "File is present";
}

User GETDATE() to put current date into SQL variable

You don't need the SELECT

DECLARE @LastChangeDate as date
SET @LastChangeDate = GetDate()

Casting a variable using a Type variable

Other answers do not mention "dynamic" type. So to add one more answer, you can use "dynamic" type to store your resulting object without having to cast converted object with a static type.

dynamic changedObj = Convert.ChangeType(obj, typeVar);
changedObj.Method();

Keep in mind that with the use of "dynamic" the compiler is bypassing static type checking which could introduce possible runtime errors if you are not careful.

Also, it is assumed that the obj is an instance of Type typeVar or is convertible to that type.

Disable asp.net button after click to prevent double clicking

<script type = "text/javascript">
function DisableButtons() {
    var inputs = document.getElementsByTagName("INPUT");
    for (var i in inputs) {
        if (inputs[i].type == "button" || inputs[i].type == "submit") {
            inputs[i].disabled = true;
        }
    }
}
window.onbeforeunload = DisableButtons;
</script>

Setting focus to a textbox control

I think what you're looking for is:

textBox1.Select();

in the constructor. (This is in C#. Maybe in VB that would be the same but without the semicolon.)

From http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx :

Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.

How to create a QR code reader in a HTML5 website?

Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.

However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.

Happy coding.

How to spawn a process and capture its STDOUT in .NET?

I just tried this very thing and the following worked for me:

StringBuilder outputBuilder;
ProcessStartInfo processStartInfo;
Process process;

outputBuilder = new StringBuilder();

processStartInfo = new ProcessStartInfo();
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.Arguments = "<insert command line arguments here>";
processStartInfo.FileName = "<insert tool path here>";

process = new Process();
process.StartInfo = processStartInfo;
// enable raising events because Process does not raise events by default
process.EnableRaisingEvents = true;
// attach the event handler for OutputDataReceived before starting the process
process.OutputDataReceived += new DataReceivedEventHandler
(
    delegate(object sender, DataReceivedEventArgs e)
    {
        // append the new data to the data already read-in
        outputBuilder.Append(e.Data);
    }
);
// start the process
// then begin asynchronously reading the output
// then wait for the process to exit
// then cancel asynchronously reading the output
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
process.CancelOutputRead();

// use the output
string output = outputBuilder.ToString();

Multiple files upload (Array) with CodeIgniter 2.0

    public function imageupload() 
    {

      $count = count($_FILES['userfile']['size']);

  $config['upload_path'] = './uploads/';
  $config['allowed_types'] = 'gif|jpg|png|bmp';
  $config['max_size']   = '0';
  $config['max_width']  = '0';
  $config['max_height']  = '0';

  $config['image_library'] = 'gd2';
  $config['create_thumb'] = TRUE;
  $config['maintain_ratio'] = FALSE;
  $config['width'] = 50;
  $config['height'] = 50;

  foreach($_FILES as $key=>$value)
  { 
     for($s=0; $s<=$count-1; $s++)
     {
     $_FILES['userfile']['name']=$value['name'][$s];
     $_FILES['userfile']['type']    = $value['type'][$s];
     $_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s]; 
     $_FILES['userfile']['error']       = $value['error'][$s];
     $_FILES['userfile']['size']    = $value['size'][$s];  

         $this->load->library('upload', $config);

         if ($this->upload->do_upload('userfile'))
         {
           $data['userfile'][$i] = $this->upload->data();
       $full_path = $data['userfile']['full_path'];


           $config['source_image'] = $full_path;
           $config['new_image'] = './uploads/resiezedImage';

           $this->load->library('image_lib', $config);
           $this->image_lib->resize(); 
           $this->image_lib->clear();

         }
         else
         {
           $data['upload_errors'][$i] = $this->upload->display_errors();
         } 
     }
  }
}

How to set the Default Page in ASP.NET?

Map default.aspx as HttpHandler route and redirect to CreateThings.aspx from within the HttpHandler.

<add verb="GET" path="default.aspx" type="RedirectHandler"/>

Make sure Default.aspx does not exists physically at your application root. If it exists physically the HttpHandler will not be given any chance to execute. Physical file overrides HttpHandler mapping.

Moreover you can re-use this for pages other than default.aspx.

<add verb="GET" path="index.aspx" type="RedirectHandler"/>

//RedirectHandler.cs in your App_Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for RedirectHandler
/// </summary>
public class RedirectHandler : IHttpHandler
{
    public RedirectHandler()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Redirect("CreateThings.aspx");
        context.Response.End();
    }

    #endregion
}

How to convert a file into a dictionary?

You can also use a dict comprehension like:

with open("infile.txt") as f:
    d = {int(k): v for line in f for (k, v) in [line.strip().split(None, 1)]}

Does calling clone() on an array also clone its contents?

If I invoke clone() method on array of Objects of type A, how will it clone its elements?

The elements of the array will not be cloned.

Will the copy be referencing to the same objects?

Yes.

Or will it call (element of type A).clone() for each of them?

No, it will not call clone() on any of the elements.

What is TypeScript and why would I use it in place of JavaScript?

TypeScript does something similar to what less or sass does for CSS. They are super sets of it, which means that every JS code you write is valid TypeScript code. Plus you can use the other goodies that it adds to the language, and the transpiled code will be valid js. You can even set the JS version that you want your resulting code on.

Currently TypeScript is a super set of ES2015, so might be a good choice to start learning the new js features and transpile to the needed standard for your project.

Replacement for deprecated sizeWithFont: in iOS 7?

Multi-line labels using dynamic height may require additional information to set the size properly. You can use sizeWithAttributes with UIFont and NSParagraphStyle to specify both the font and the line-break mode.

You would define the Paragraph Style and use an NSDictionary like this:

// set paragraph style
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];
// make dictionary of attributes with paragraph style
NSDictionary *sizeAttributes        = @{NSFontAttributeName:myLabel.font, NSParagraphStyleAttributeName: style};
// get the CGSize
CGSize adjustedSize = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);

// alternatively you can also get a CGRect to determine height
CGRect rect = [myLabel.text boundingRectWithSize:adjustedSize
                                                         options:NSStringDrawingUsesLineFragmentOrigin
                                                      attributes:sizeAttributes
                                                         context:nil];

You can use the CGSize 'adjustedSize' or CGRect as rect.size.height property if you're looking for the height.

More info on NSParagraphStyle here: https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSParagraphStyle_Class/Reference/Reference.html

Hide Command Window of .BAT file that Executes Another .EXE File

Or you can use:

Start /d "the directory of the executable" /b "the name of the executable" "parameters of the executable" %1

If %1 is a file then it is passed to your executable. For example in notepad.exe foo.txt %1 is "foo.txt".

The /b parameter of the start command does this:

Starts an application without opening a new Command Prompt window. CTRL+C handling is ignored unless the application enables CTRL+C processing. Use CTRL+BREAK to interrupt the application.

Which is exactly what we want.

What is %0|%0 and how does it work?

It's a logic bomb, it keeps recreating itself and takes up all your CPU resources. It overloads your computer with too many processes and it forces it to shut down. If you make a batch file with this in it and start it you can end it using taskmgr. You have to do this pretty quickly or your computer will be too slow to do anything.

How to extract the substring between two markers?

import re
print re.search('AAA(.*?)ZZZ', 'gfgfdAAA1234ZZZuijjk').group(1)

Reading and writing value from a textfile by using vbscript code

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("listfile.txt")
Dim inFile: Set inFile = obj.OpenTextFile("listfile.txt")

' read file
data = inFile.ReadAll
inFile.Close

' write file
outFile.write (data)
outFile.Close

Replace multiple strings with multiple other strings

With my replace-once package, you could do the following:

const replaceOnce = require('replace-once')

var str = 'I have a cat, a dog, and a goat.'
var find = ['cat', 'dog', 'goat']
var replace = ['dog', 'goat', 'cat']
replaceOnce(str, find, replace, 'gi')
//=> 'I have a dog, a goat, and a cat.'

How to use Oracle ORDER BY and ROWNUM correctly?

An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.

select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo) 
limit 1

My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...

SQLer

How do I update a Python package?

  1. Via windows command prompt, run: pip list --outdated You will get the list of outdated packages.
  2. Run: pip install [package] --upgrade It will upgrade the [package] and uninstall the previous version.

To update pip:

py -m pip install --upgrade pip

Again, this will uninstall the previous version of pip and will install the latest version of pip.

Get cookie by name

Just use the following function (a pure javascript code)

const getCookie = (name) => {
 const cookies = Object.assign({}, ...document.cookie.split('; ').map(cookie => {
    const name = cookie.split('=')[0];
    const value = cookie.split('=')[1];

    return {[name]: value};
  }));

  return cookies[name];
};

Proper use cases for Android UserManager.isUserAGoat()?

Google has a serious liking for goats and goat based Easter eggs. There has even been previous Stack Overflow posts about it.

As has been mentioned in previous posts, it also exists within the Chrome task manager (it first appeared in the wild in 2009):

<message name="IDS_TASK_MANAGER_GOATS_TELEPORTED_COLUMN" desc="The goats teleported column">
    Goats Teleported
</message>

And then in Windows, Linux and Mac versions of Chrome early 2010). The number of "Goats Teleported" is in fact random:

 int TaskManagerModel::GetGoatsTeleported(int index) const {
     int seed = goat_salt_ * (index + 1);
     return (seed >> 16) & 255;
 }

Other Google references to goats include:

The earliest correlation of goats and Google belongs in the original "Mowing with goats" blog post, as far as I can tell.

We can safely assume that it's merely an Easter egg and has no real-world use, except for returning false.

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-

(untested code)

Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")

' now you can manipulate the data in the workbook anyway you want, e.g. '

Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value

Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False

' etc '

Call wbk.Close(False)

Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.

How do I generate a random integer between min and max in Java?

Using the Random class is the way to go as suggested in the accepted answer, but here is a less straight-forward correct way of doing it if you didn't want to create a new Random object :

min + (int) (Math.random() * (max - min + 1));

Android: Cancel Async Task

I spent a while figuring this out, all I wanted was a simple example of how to do it, so I thought I'd post how I did it. This is some code that updates a library and has a progress dialog showing how many books have been updated and cancels when a user dismisses the dialog:

private class UpdateLibrary extends AsyncTask<Void, Integer, Boolean>{
    private ProgressDialog dialog = new ProgressDialog(Library.this);
    private int total = Library.instance.appState.getAvailableText().length;
    private int count = 0;

    //Used as handler to cancel task if back button is pressed
    private AsyncTask<Void, Integer, Boolean> updateTask = null;

    @Override
    protected void onPreExecute(){
        updateTask = this;
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setOnDismissListener(new OnDismissListener() {               
            @Override
            public void onDismiss(DialogInterface dialog) {
                updateTask.cancel(true);
            }
        });
        dialog.setMessage("Updating Library...");
        dialog.setMax(total);
        dialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
            for (int i = 0; i < appState.getAvailableText().length;i++){
                if(isCancelled()){
                    break;
                }
                //Do your updating stuff here
            }
        }

    @Override
    protected void onProgressUpdate(Integer... progress){
        count += progress[0];
        dialog.setProgress(count);
    }

    @Override
    protected void onPostExecute(Boolean finished){
        dialog.dismiss();
        if (finished)
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY, Str.TEXT_UPDATECOMPLETED, Library.instance);
        else 
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY,Str.TEXT_NOUPDATE , Library.instance);
    }
}

Verify if file exists or not in C#

These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.

The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)

How to search for a string inside an array of strings

In-case if someone wants a little dynamic search.

 let searchInArray=(searchQuery, array, objectKey=null)=>{

  return array.filter(d=>{
      let data =objectKey? d[objectKey] : d //Incase If It's Array Of Objects.
       let dataWords= typeof data=="string" && data?.split(" ")?.map(b=>b&&b.toLowerCase().trim()).filter(b=>b)
      let searchWords = typeof searchQuery=="string"&&searchQuery?.split(" ").map(b=>b&&b.toLowerCase().trim()).filter(b=>b)

     let matchingWords = searchWords.filter(word=>dataWords.includes(word))

    return matchingWords.length

})
    
    
}

For an Array of strings:

let arrayOfStr = [
  "Search for words",
  "inside an array",
  "dynamic searching",
  "match rate 90%"
]

searchInArray("dynamic search", arrayOfStr)

//Results: [ "Search for words", "dynamic searching" ]

For an Array of Objects:

let arrayOfObject = [
  {
    "address": "Karachi Pakistan"
  },
  {
    "address": "UK London"
  },
  {
    "address": "Pakistan Lahore"
  }
]

searchInArray("Pakistan", arrayOfObject,"address")

//Results: [ { "address": "Karachi Pakistan" }, { "address": "Pakistan Lahore" } ]

Could not locate Gemfile

I solved similar problem just by backing out of the project directory, then cd back into the project directory and bundle install.

What is the difference between SQL, PL-SQL and T-SQL?

SQL

SQL is used to communicate with a database, it is the standard language for relational database management systems.

In detail Structured Query Language is a special-purpose programming language designed for managing data held in a relational database management system (RDBMS), or for stream processing in a relational data stream management system (RDSMS).

Originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language and a data manipulation language. The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. Although SQL is often described as, and to a great extent is, a declarative language (4GL), it also includes procedural elements.

PL/SQL

PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation

Specialities of PL/SQL

  • completely portable, high-performance transaction-processing language.
  • provides a built-in interpreted and OS independent programming environment.
  • directly be called from the command-line SQL*Plus interface.
  • Direct call can also be made from external programming language calls to database.
  • general syntax is based on that of ADA and Pascal programming language.
  • Apart from Oracle, it is available in TimesTen in-memory database and IBM DB2.

T-SQL

Short for Transaction-SQL, an extended form of SQL that adds declared variables, transaction control, error and exceptionhandling and row processing to SQL

The Structured Query Language or SQL is a programming language that focuses on managing relational databases. SQL has its own limitations which spurred the software giant Microsoft to build on top of SQL with their own extensions to enhance the functionality of SQL. Microsoft added code to SQL and called it Transact-SQL or T-SQL. Keep in mind that T-SQL is proprietary and is under the control of Microsoft while SQL, although developed by IBM, is already an open format.

T-SQL adds a number of features that are not available in SQL.

This includes procedural programming elements and a local variable to provide more flexible control of how the application flows. A number of functions were also added to T-SQL to make it more powerful; functions for mathematical operations, string operations, date and time processing, and the like. These additions make T-SQL comply with the Turing completeness test, a test that determines the universality of a computing language. SQL is not Turing complete and is very limited in the scope of what it can do.

Another significant difference between T-SQL and SQL is the changes done to the DELETE and UPDATE commands that are already available in SQL. With T-SQL, the DELETE and UPDATE commands both allow the inclusion of a FROM clause which allows the use of JOINs. This simplifies the filtering of records to easily pick out the entries that match a certain criteria unlike with SQL where it can be a bit more complicated.

Choosing between T-SQL and SQL is all up to the user. Still, using T-SQL is still better when you are dealing with Microsoft SQL Server installations. This is because T-SQL is also from Microsoft, and using the two together maximizes compatibility. SQL is preferred by people who have multiple backends.

References , Wikipedea , Tutorial Points :www.differencebetween.com

Trigger function when date is selected with jQuery UI datepicker

Use the following code:

$(document).ready(function() {
    $('.date-pick').datepicker( {
     onSelect: function(date) {
        alert(date)
     },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1,
  });
});

You can adjust the parameters yourself :-)

How to submit http form using C#

Your HTML file is not going to interact with C# directly, but you can write some C# to behave as if it were the HTML file.

For example: there is a class called System.Net.WebClient with simple methods:

using System.Net;
using System.Collections.Specialized;

...
using(WebClient client = new WebClient()) {

    NameValueCollection vals = new NameValueCollection();
    vals.Add("test", "test string");
    client.UploadValues("http://www.someurl.com/page.php", vals);
}

For more documentation and features, refer to the MSDN page.

Export HTML table to pdf using jspdf

Here is working example:

in head

<script type="text/javascript" src="jspdf.debug.js"></script>

script:

<script type="text/javascript">
        function demoFromHTML() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            // source can be HTML-formatted string, or a reference
            // to an actual DOM element from which the text will be scraped.
            source = $('#customers')[0];

            // we support special element handlers. Register them with jQuery-style 
            // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
            // There is no support for any other type of selectors 
            // (class, of compound) at this time.
            specialElementHandlers = {
                // element with id of "bypass" - jQuery style selector
                '#bypassme': function(element, renderer) {
                    // true = "handled elsewhere, bypass text extraction"
                    return true
                }
            };
            margins = {
                top: 80,
                bottom: 60,
                left: 40,
                width: 522
            };
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
            pdf.fromHTML(
                    source, // HTML string or DOM elem ref.
                    margins.left, // x coord
                    margins.top, {// y coord
                        'width': margins.width, // max width of content on PDF
                        'elementHandlers': specialElementHandlers
                    },
            function(dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            }
            , margins);
        }
    </script>

and table:

<div id="customers">
        <table id="tab_customers" class="table table-striped" >
            <colgroup>
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <col width="20%">
            </colgroup>
            <thead>         
                <tr class='warning'>
                    <th>Country</th>
                    <th>Population</th>
                    <th>Date</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Chinna</td>
                    <td>1,363,480,000</td>
                    <td>March 24, 2014</td>
                    <td>19.1</td>
                </tr>
                <tr>
                    <td>India</td>
                    <td>1,241,900,000</td>
                    <td>March 24, 2014</td>
                    <td>17.4</td>
                </tr>
                <tr>
                    <td>United States</td>
                    <td>317,746,000</td>
                    <td>March 24, 2014</td>
                    <td>4.44</td>
                </tr>
                <tr>
                    <td>Indonesia</td>
                    <td>249,866,000</td>
                    <td>July 1, 2013</td>
                    <td>3.49</td>
                </tr>
                <tr>
                    <td>Brazil</td>
                    <td>201,032,714</td>
                    <td>July 1, 2013</td>
                    <td>2.81</td>
                </tr>
            </tbody>
        </table> 
    </div>

and button to run:

<button onclick="javascript:demoFromHTML()">PDF</button>

and working example online:

tabel to pdf jspdf

or try this: HTML Table Export

Android - Handle "Enter" in an EditText

   final EditText edittext = (EditText) findViewById(R.id.edittext);
    edittext.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                    (keyCode == KeyEvent.KEYCODE_ENTER)) {
                // Perform action on key press
                Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
                return true;
            }
            return false;
        }
    });

Explaining Python's '__enter__' and '__exit__'

In addition to the above answers to exemplify invocation order, a simple run example

class myclass:
    def __init__(self):
        print("__init__")

    def __enter__(self): 
        print("__enter__")

    def __exit__(self, type, value, traceback):
        print("__exit__")

    def __del__(self):
        print("__del__")

with myclass(): 
    print("body")

Produces the output:

__init__
__enter__
body
__exit__
__del__

A reminder: when using the syntax with myclass() as mc, variable mc gets the value returned by __enter__(), in the above case None! For such use, need to define return value, such as:

def __enter__(self): 
    print('__enter__')
    return self

How to initialize an array in Java?

Try data = new int[] {10,20,30,40,50,60,71,80,90,91 };

Get name of current class?

You can access it by the class' private attributes:

cls_name = self.__class__.__name__

EDIT:

As said by Ned Batcheler, this wouldn't work in the class body, but it would in a method.

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

Android ListView selected item stay highlighted

Simplistic way is,if you are using listview in a xml,use this attributes on your listview,

android:choiceMode="singleChoice"
android:listSelector="#your color code"

if not using xml,by programatically

listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setSelector(android.R.color.holo_blue_light);

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

For UTF-16LE with BOM if you use tab characters as your delimiters instead of commas Excel will recognise the fields. The reason it works is that Excel actually ends up using its Unicode *.txt parser.

Caveat: If the file is edited in Excel and saved, it will be saved as tab-delimited ASCII. The problem now is that when you re-open the file Excel assumes it's real CSV (with commas), sees that it's not Unicode, so parses it as comma-delimited - and hence will make a hash of it!

Update: The above caveat doesn't appear to be happening for me today in Excel 2010 (Windows) at least, although there does appear to be a difference in saving behaviour if:

  • you edit and quit Excel (tries to save as 'Unicode *.txt')

compared to:

  • editing and closing just the file (works as expected).

What is "android.R.layout.simple_list_item_1"?

android.R.layout.simple_list_item_1, this is row layout file in your res/layout folder which contains the corresponding design for your row in listview. Now we just bind the array list items to the row layout by using mylistview.setadapter(aa);

Phone: numeric keyboard for text input

I couldn't find a type that worked best for me in all situations: I needed to default to numeric entry (entry of "7.5" for example) but also at certain times allow text ("pass" for example). Users wanted a numeric keypad (entry of 7.5 for example) but occasional text entry was required ("pass" for example).

Rather what I did was to add a checkbox to the form and allow the user to toggle my input (id="inputSresult") between type="number" and type="text".

<input type="number" id="result"... >
<label><input id="cbAllowTextResults" type="checkbox" ...>Allow entry of text results.</label>

Then I wired a click handler to the checkbox that toggles the type between text and number based on whether the checkbox above is checked:

$(document).ready(function () {
    var cb = document.getElementById('cbAllowTextResults');
    cb.onclick = function (event) {
        if ($("#cbAllowTextResults").is(":checked"))
            $("#result").attr("type", "text");
        else
            $("#result").attr("type", "number");

    }
});

This worked out well for us.

Move entire line up and down in Vim

Just add this code to .vimrc (or .gvimrc)

nnoremap <A-j> :m+<CR>==
nnoremap <A-k> :m-2<CR>==
inoremap <A-j> <Esc>:m+<CR>==gi
inoremap <A-k> <Esc>:m-2<CR>==gi
vnoremap <A-j> :m'>+<CR>gv=gv
vnoremap <A-k> :m-2<CR>gv=gv

What are ABAP and SAP?

  • SAP SE is a German multinational that makes enterprise software. It is best known for SAP ERP and its predecessors (SAP R/2 & SAP R/3). As the name suggests, SAP ERP is an ERP system, which basically means that it supports a wide range of business processes from warehouse management and sales to HR, business intelligence, etc.

    Although SAP ERP isn't the only software sold by SAP, people are typically refering to SAP ERP when they say "they're using SAP at work". It's important to note, though, that SAP is the name of the company and no software is sold or licensed as just "SAP".

  • ABAP is a 4GL programming language created by SAP, and commonly compared with OpenEdge ABL or COBOL. Much of SAP's software is written in ABAP. SAP provides an ABAP Workbench, which is a collection of tools that allows third party developers to develop, test and run custom ABAP programs within the SAP ERP system. The ABAP Workbench is typically used only when business logic cannot be implemented in SAP ERP by means of mere configuration.

How can I change the default Mysql connection timeout when connecting through python?

MAX_EXECUTION_TIME is also an important parameter for long running queries.Will work for MySQL 5.7 or later.

Check the current value

SELECT @@GLOBAL.MAX_EXECUTION_TIME, @@SESSION.MAX_EXECUTION_TIME;

Then set it according to your needs.

SET SESSION MAX_EXECUTION_TIME=2000;
SET GLOBAL MAX_EXECUTION_TIME=2000;

python paramiko ssh

###### Use paramiko to connect to LINUX platform############
import paramiko

ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

--------Connection Established-----------------------------

######To run shell commands on remote connection###########
import paramiko

ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)


stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp) # Output 

Twitter bootstrap hide element on small devices

Bootstrap 4

The display (hidden/visible) classes are changed in Bootstrap 4. To hide on the xs viewport use:

d-none d-sm-block

Also see: Missing visible-** and hidden-** in Bootstrap v4


Bootstrap 3 (original answer)

Use the hidden-xs utility class..

<nav class="col-sm-3 hidden-xs">
        <ul class="list-unstyled">
        <li>Text 10</li>
        <li>Text 11</li>
        <li>Text 12</li>
        </ul>
</nav>

http://bootply.com/90722

Magento addFieldToFilter: Two fields, match as OR, not AND

Here is my solution in Enterprise 1.11 (should work in CE 1.6):

    $collection->addFieldToFilter('max_item_count',
                    array(
                        array('gteq' => 10),
                        array('null' => true),
                    )
            )
            ->addFieldToFilter('max_item_price',
                    array(
                        array('gteq' => 9.99),
                        array('null' => true),
                    )
            )
            ->addFieldToFilter('max_item_weight',
                    array(
                        array('gteq' => 1.5),
                        array('null' => true),
                    )
            );

Which results in this SQL:

    SELECT `main_table`.*
    FROM `shipping_method_entity` AS `main_table`
    WHERE (((max_item_count >= 10) OR (max_item_count IS NULL)))
      AND (((max_item_price >= 9.99) OR (max_item_price IS NULL)))
      AND (((max_item_weight >= 1.5) OR (max_item_weight IS NULL)))

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

I encountered this problem when working with COM objects. Under certain circumstances (my fault), I destroyed an external .EXE process, in a parallel thread, a variable tried to access the com interface app.method and a COM-level crash occurred. Task Scheduler noticed this and shut down the app. But if you run the app in the console and don't handle the exception, the app will continue to work ...

Please note that if you use unmanaged code or external objects (AD, Socket, COM ...), you need to monitor them!

Font Awesome not working, icons showing as squares

I tried to solve the same problem with a few previous solutions, but they didn't work in my situation. Finally, I added these 2 lines in HEAD and it worked:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="http://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css">   

Make flex items take content width, not width of parent container

In addtion to align-self you can also consider auto margin which will do almost the same thing

_x000D_
_x000D_
.container {_x000D_
  background: red;_x000D_
  height: 200px;_x000D_
  flex-direction: column;_x000D_
  padding: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
a {_x000D_
  margin-right:auto;_x000D_
  padding: 10px 40px;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
  <a href="#">Test</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MVC4 StyleBundle not resolving images

Another option would be to use the IIS URL Rewrite module to map the virtual bundle image folder to the physical image folder. Below is an example of a rewrite rule from that you could use for a bundle called "~/bundles/yourpage/styles" - note the regex matches on alphanumeric characters as well as hyphens, underscores and periods, which are common in image file names.

<rewrite>
  <rules>
    <rule name="Bundle Images">
      <match url="^bundles/yourpage/images/([a-zA-Z0-9\-_.]+)" />
      <action type="Rewrite" url="Content/css/jquery-ui/images/{R:1}" />
    </rule>
  </rules>
</rewrite>

This approach creates a little extra overhead, but allows you to have more control over your bundle names, and also reduces the number of bundles you may have to reference on one page. Of course, if you have to reference multiple 3rd party css files that contain relative image path references, you still can't get around creating multiple bundles.

How to use the "required" attribute with a "radio" input field

I had to use required="required" along with the same name and type, and then validation worked fine.

<input type="radio" name="user-radio"  id="" value="User" required="required" />

<input type="radio" name="user-radio" id="" value="Admin" />

<input type="radio" name="user-radio" id="" value="Guest" /> 

How to add message box with 'OK' button?

@Override
protected Dialog onCreateDialog(int id)
{
    switch(id)
    {
    case 0:
    {               
        return new AlertDialog.Builder(this)
        .setMessage("text here")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {                   
            @Override
            public void onClick(DialogInterface arg0, int arg1) 
            {
                try
                {

                }//end try
                catch(Exception e)
                {
                    Toast.makeText(getBaseContext(),  "", Toast.LENGTH_LONG).show();
                }//end catch
            }//end onClick()
        }).create();                
    }//end case
  }//end switch
    return null;
}//end onCreateDialog

Can a main() method of class be invoked from another class in java

If you want to call the main method of another class you can do it this way assuming I understand the question.

public class MyClass {

    public static void main(String[] args) {

        System.out.println("main() method of MyClass");
        OtherClass obj = new OtherClass();
    }
}

class OtherClass {

    public OtherClass() {

        // Call the main() method of MyClass
        String[] arguments = new String[] {"123"};
        MyClass.main(arguments);
    }
}

Align text in a table header

HTML:

<tr>
    <th>Language</th>
    <th>Skill Level</th>
    <th>&nbsp;</th>
</tr>

CSS:

tr, th {
    padding: 10px;
    text-align: center;
}

How do I determine file encoding in OS X?

In Mac OS X the command file -I (capital i) will give you the proper character set so long as the file you are testing contains characters outside of the basic ASCII range.

For instance if you go into Terminal and use vi to create a file eg. vi test.txt then insert some characters and include an accented character (try ALT-e followed by e) then save the file.

They type file -I text.txt and you should get a result like this:

test.txt: text/plain; charset=utf-8

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.

Cast IList to List

In my case I had to do this, because none of the suggested solutions were available:

List<SubProduct> subProducts = Model.subproduct.Cast<SubProduct>().ToList();

Disable validation of HTML5 form elements

Just use novalidate in your form.

<form name="myForm" role="form" novalidate class="form-horizontal" ng-hide="formMain">

Cheers!!!

Any way to declare an array in-line?

I'd like to add that the array initialization syntax is very succinct and flexible. I use it a LOT to extract data from my code and place it somewhere more usable.

As an example, I've often created menus like this:

Menu menu=initMenus(menuHandler, new String[]{"File", "+Save", "+Load", "Edit", "+Copy", ...});

This would allow me to write come code to set up a menu system. The "+" is enough to tell it to place that item under the previous item.

I could bind it to the menuHandler class either by a method naming convention by naming my methods something like "menuFile, menuFileSave, menuFileLoad, ..." and binding them reflectively (there are other alternatives).

This syntax allows AMAZINGLY brief menu definition and an extremely reusable "initMenus" method. (Yet I don't bother reusing it because it's always fun to write and only takes a few minutes+a few lines of code).

any time you see a pattern in your code, see if you can replace it with something like this, and always remember how succinct the array initialization syntax is!.

Select method of Range class failed via VBA

Here is a solution worked for me and also, I found all of the above solutions are correct. My excel model got corrupted and which is why my code (similar to this one) stopped working. Here is what worked for me and is working every time-

  1. Calculate the workbook- Formulas->Calculate Now (under calculation section)
  2. Save the workbook
  3. Close and re-open the file. It was fixed and works every time.

Why is PHP session_destroy() not working?

Add session_start(); before !Doctype Declaration

    <?php session_start(); ?>
    <!doctype html>
    <html>
    <body>
<?php 
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) 
{   
    session_destroy();   
    session_unset();     
} 
?>
</body>
</html>

Unique random string generation

My one stop solution for Linux commands on windows is scoop. Install scoop from scoop.sh

scoop install openssl
openssl rand -base64 32
Dca3c3pptVkcb8fx243wN/3f/rQxx/rWYL8y7rZrGrA=

How do I remove all non-ASCII characters with regex and Notepad++?

In Notepad++, if you go to menu Search ? Find characters in range ? Non-ASCII Characters (128-255) you can then step through the document to each non-ASCII character.

Be sure to tick off "Wrap around" if you want to loop in the document for all non-ASCII characters.

screenshot "Find in Range"

server error:405 - HTTP verb used to access this page is not allowed

Try renaming the default file. In my case, a recent move to IIS7.5 gave the 405 error. I changed index.aspx to default.aspx and it worked immediately for me.

How do I display a decimal value to 2 decimal places?

The top-rated answer describes a method for formatting the string representation of the decimal value, and it works.

However, if you actually want to change the precision saved to the actual value, you need to write something like the following:

public static class PrecisionHelper
{
    public static decimal TwoDecimalPlaces(this decimal value)
    {
        // These first lines eliminate all digits past two places.
        var timesHundred = (int) (value * 100);
        var removeZeroes = timesHundred / 100m;

        // In this implementation, I don't want to alter the underlying
        // value.  As such, if it needs greater precision to stay unaltered,
        // I return it.
        if (removeZeroes != value)
            return value;

        // Addition and subtraction can reliably change precision.  
        // For two decimal values A and B, (A + B) will have at least as 
        // many digits past the decimal point as A or B.
        return removeZeroes + 0.01m - 0.01m;
    }
}

An example unit test:

[Test]
public void PrecisionExampleUnitTest()
{
    decimal a = 500m;
    decimal b = 99.99m;
    decimal c = 123.4m;
    decimal d = 10101.1000000m;
    decimal e = 908.7650m

    Assert.That(a.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("500.00"));

    Assert.That(b.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("99.99"));

    Assert.That(c.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("123.40"));

    Assert.That(d.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("10101.10"));

    // In this particular implementation, values that can't be expressed in
    // two decimal places are unaltered, so this remains as-is.
    Assert.That(e.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("908.7650"));
}

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

Javascript split regex question

You need the put the characters you wish to split on in a character class, which tells the regular expression engine "any of these characters is a match". For your purposes, this would look like:

date.split(/[.,\/ -]/)

Although dashes have special meaning in character classes as a range specifier (ie [a-z] means the same as [abcdefghijklmnopqrstuvwxyz]), if you put it as the last thing in the class it is taken to mean a literal dash and does not need to be escaped.

To explain why your pattern didn't work, /-./ tells the regular expression engine to match a literal dash character followed by any character (dots are wildcard characters in regular expressions). With "02-25-2010", it would split each time "-2" is encountered, because the dash matches and the dot matches "2".

Redirecting to URL in Flask

You have to return a redirect:

import os
from flask import Flask,redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("http://www.example.com", code=302)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

See the documentation on flask docs. The default value for code is 302 so code=302 can be omitted or replaced by other redirect code (one in 301, 302, 303, 305, and 307).

Xcode 9 Swift Language Version (SWIFT_VERSION)

In my case, all warn disappeared after I directly changed swift version from 2.x to 4.0 in build settings except two warn.

These warning related to myprojectnameTests and myprojectnameUITests folder. I didn't notice and I thought its relate to direct immigration from Xcode 7 to Xcode 9 and I thought I couldn't solve this problem and I should install missed Xcode 8 version.

In my case, I deleted these folders and all warns disappeared, but you can recreate this folder and contains using this:

file > new > target > (uitest or unittest extensions)

and use this article for create test cases: https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/04-writing_tests.html

Java ArrayList of Doubles

double[] arr = new double[] {1.38, 2.56, 4.3};

ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
    Collectors.toCollection( new Supplier<ArrayList<Double>>() {
      public ArrayList<Double> get() {
        return( new ArrayList<Double>() );
      }
    } ) );

Find (and kill) process locking port 3000 on Mac

Step 1: Find server which are running: ps aux | grep puma Step 2: Kill those server Kill -9 [server number]

How to dynamically add elements to String array?

when using String array, you have to give size of array while initializing

eg

String[] str = new String[10];

you can use index 0-9 to store values

str[0] = "value1"
str[1] = "value2"
str[2] = "value3"
str[3] = "value4"
str[4] = "value5"
str[5] = "value6"
str[6] = "value7"
str[7] = "value8"
str[8] = "value9"
str[9] = "value10"

if you are using ArrayList instread of string array, you can use it without initializing size of array ArrayList str = new ArrayList();

you can add value by using add method of Arraylist

str.add("Value1");

get retrieve a value from arraylist, you can use get method

String s = str.get(0);

find total number of items by size method

int nCount = str.size();

read more from here

How to get featured image of a product in woocommerce

This should do the trick:

<?php
    $product_meta = get_post_meta($post_id);
    echo wp_get_attachment_image( $product_meta['_thumbnail_id'][0], 'full' );
?>

You can change the parameters according to your needs.

Why shouldn't I use "Hungarian Notation"?

It's incredibly redundant and useless is most modern IDEs, where they do a good job of making the type apparent.

Plus -- to me -- it's just annoying to see intI, strUserName, etc. :)

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I had this problem before, and solved it according to React official page isMounted is an Antipattern.

Set a property isMounted flag to be true in componentDidMount , and toggle it false in componentWillUnmount. When you setState() in your callbacks, check isMounted first! It works for me.

state = {
    isMounted: false
  }
  componentDidMount() {
      this.setState({isMounted: true})
  }
  componentWillUnmount(){
      this.setState({isMounted: false})
  }

callback:

if (this.state.isMounted) {
 this.setState({'time': remainTimeInfo});}

Unable to find a @SpringBootConfiguration when doing a JpaTest

In my case the packages were different between the Application and Test classes

package com.example.abc;
...
@SpringBootApplication
public class ProducerApplication {

and

package com.example.abc_etc;
...
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProducerApplicationTest {

After making them agree the tests ran correctly.

How to exit an if clause

while some_condition:
   ...
   if condition_a:
       # do something
       break
   ...
   if condition_b:
       # do something
       break
   # more code here
   break

SVG gradient using CSS

Thank you everyone, for all your precise replys.

Using the svg in a shadow dom, I add the 3 linear gradients I need within the svg, inside a . I place the css fill rule on the web component and the inheritance od fill does the job.

_x000D_
_x000D_
    <svg viewbox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
      <path
        d="m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z"></path>
    </svg>
    
    <svg height="0" width="0">
      <defs>
        <linearGradient id="lgrad-p" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#4169e1"></stop><stop offset="99%" stop-color="#c44764"></stop></linearGradient>
        <linearGradient id="lgrad-s" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#ef3c3a"></stop><stop offset="99%" stop-color="#6d5eb7"></stop></linearGradient>
        <linearGradient id="lgrad-g" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#585f74"></stop><stop offset="99%" stop-color="#b6bbc8"></stop></linearGradient>
      </defs>
    </svg>
    
    <div></div>

    <style>
      :first-child {
        height:150px;
        width:150px;
        fill:url(#lgrad-p) blue;
      }
      div{
        position:relative;
        width:150px;
        height:150px;
        fill:url(#lgrad-s) red;
      }
    </style>
    <script>
      const shadow = document.querySelector('div').attachShadow({mode: 'open'});
      shadow.innerHTML="<svg viewbox=\"0 0 512 512\">\
        <path d=\"m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z\"></path>\
      </svg>\
      <svg height=\"0\">\
      <defs>\
        <linearGradient id=\"lgrad-s\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#ef3c3a\"></stop><stop offset=\"99%\" stop-color=\"#6d5eb7\"></stop></linearGradient>\
        <linearGradient id=\"lgrad-g\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#585f74\"></stop><stop offset=\"99%\" stop-color=\"#b6bbc8\"></stop></linearGradient>\
      </defs>\
    </svg>\
    ";
    </script>
_x000D_
_x000D_
_x000D_

The first one is normal SVG, the second one is inside a shadow dom.

Android: Remove all the previous activities from the back stack

None of the intent flags worked for me, but this is how I fixed it:

When a user signs out from one activity I had to broadcast a message from that activity, then receive it in the activities that I wanted to close after which I call finish(); and it works pretty well.

CMake does not find Visual C++ compiler

Those stumbling with this on Visual Studio 2017: there is a feature related to CMake that needs to be selected and installed together with the relevant compiler toolsets. See the screenshot below.

Visaul C++ tools for CMake must be installed

C# : "A first chance exception of type 'System.InvalidOperationException'"

Consider using System.Windows.Forms.Timer instead of System.Threading.Timer for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.

In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.

Apply global variable to Vuejs

If the global variable should not be written to by anything, including Vuejs, you can use Object.freeze to freeze your object. Adding it to Vue's viewmodel won't unfreeze it. Another option is to provide Vuejs with a frozen copy of the object, if the object is intended to be written globally but just not by Vue: var frozenCopy = Object.freeze(Object.assign({}, globalObject))

How to delete all the rows in a table using Eloquent?

There is an indirect way:

myModel:where('anyColumnName', 'like', '%%')->delete();

Example:

User:where('id', 'like' '%%')->delete();

Laravel query builder information: https://laravel.com/docs/5.4/queries

How to update/modify an XML file in python?

To make this process more robust, you could consider using the SAX parser (that way you don't have to hold the whole file in memory), read & write till the end of tree and then start appending.

Is there a way to set background-image as a base64 encoded image?

I tried this (and worked for me):

var img = 'data:image/png;base64, ...'; //place ur base64 encoded img here
document.body.style.backgroundImage = 'url(\'' + img + '\')';

ES6 syntax:

let img = 'data:image/png;base64, ...'
document.body.style.backgroundImage = `url('${img}')`

A bit better:

let setBackground = src => {
    this.style.backgroundImage = `url('${src}')`
};

let node = nodeIGotFromDOM, img = imageBase64EncodedFromMyGF;
setBackground.call(node, img);