Programs & Examples On #Jbossws

JBossWS features include many specifications / standards implementations as well as additional features, options, tools to improve ease of use, endpoint management and monitoring, etc.

Dictionary with list of strings as value

A simpler way of doing it is:

var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());

Route [login] not defined

Laravel ^5.7

The Authenticate Middleware

Laravel ^5.7 includes new middleware to handle and redirect unauthenticated users.

It works well with "web" guard... of course the "login" route (or whatever you name your login route) should be defined in web.php.

the problem is when your are using custom guard. Different guard would redirect unauthenticated users to different route.

here's a quick workaround based on John's response (it works for me).


app/Http/Middleware/Authenticate.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * @var array
     */
    protected $guards = [];




    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $this->guards = $guards;

        return parent::handle($request, $next, ...$guards);
    }




    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {

            if (in_array('admin', $this->guards)) {

                return route('admin.login');
            }

            return route('login');
        }
    }
}

Source : Issue #26292

How can I change the color of my prompt in zsh (different from normal text)?

Here's an example of how to set a red prompt:

PS1=$'\e[0;31m$ \e[0m'

The magic is the \e[0;31m (turn on red foreground) and \e[0m (turn off character attributes). These are called escape sequences. Different escape sequences give you different results, from absolute cursor positioning, to color, to being able to change the title bar of your window, and so on.

For more on escape sequences, see the wikipedia entry on ANSI escape codes

Read file data without saving it in Flask

in function

def handleUpload():
    if 'photo' in request.files:
        photo = request.files['photo']
        if photo.filename != '':      
            image = request.files['photo']  
            image_string = base64.b64encode(image.read())
            image_string = image_string.decode('utf-8')
            #use this to remove b'...' to get raw string
            return render_template('handleUpload.html',filestring = image_string)
    return render_template('upload.html')

in html file

<html>
<head>
    <title>Simple file upload using Python Flask</title>
</head>
<body>
    {% if filestring %}
      <h1>Raw image:</h1>
      <h1>{{filestring}}</h1>
      <img src="data:image/png;base64, {{filestring}}" alt="alternate" />.
    {% else %}
      <h1></h1>
    {% endif %}
</body>

SQL Server Management Studio, how to get execution time down to milliseconds

Turn on Client Statistics by doing one of the following:

  • Menu: Query > Include client Statistics
  • Toolbar: Click the button (next to Include Actual Execution Time)
  • Keyboard: Shift-Alt-S

Then you get a new tab which records the timings, IO data and rowcounts etc for (up to) the last 10 exections (plus averages!):

enter image description here

Visual Studio 2015 doesn't have cl.exe

Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++

Converting file into Base64String and back again

Another working example in VB.NET:

Public Function base64Encode(ByVal myDataToEncode As String) As String
    Try
        Dim myEncodeData_byte As Byte() = New Byte(myDataToEncode.Length - 1) {}
        myEncodeData_byte = System.Text.Encoding.UTF8.GetBytes(myDataToEncode)
        Dim myEncodedData As String = Convert.ToBase64String(myEncodeData_byte)
        Return myEncodedData
    Catch ex As Exception
        Throw (New Exception("Error in base64Encode" & ex.Message))
    End Try
    '
End Function

Error when testing on iOS simulator: Couldn't register with the bootstrap server

I just had this happen to me: I was getting the error only on my device and the simulator was working fine. I ended up having to reset my device and the error went away.

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

Try reinstall by using the below link,

Download https://bootstrap.pypa.io/get-pip.py

After download, copy the "get-pip.py" to python installed main dirctory, then open cmd and navigate to python directory and type "python get-pip.py" (without quotes)

Note: Also make sure the python directory is set in the environmental variable.

Hope this might help.

pyplot scatter plot marker size

If the size of the circles corresponds to the square of the parameter in s=parameter, then assign a square root to each element you append to your size array, like this: s=[1, 1.414, 1.73, 2.0, 2.24] such that when it takes these values and returns them, their relative size increase will be the square root of the squared progression, which returns a linear progression.

If I were to square each one as it gets output to the plot: output=[1, 2, 3, 4, 5]. Try list interpretation: s=[numpy.sqrt(i) for i in s]

javascript - Create Simple Dynamic Array

I would do as follows;

_x000D_
_x000D_
var num = 10,_x000D_
  dynar = [...Array(num)].map((_,i) => ++i+"");_x000D_
console.log(dynar);
_x000D_
_x000D_
_x000D_

Replacing accented characters php

You can try this one

class Diacritic
{
    public function replaceDiacritic($input)
    {
        $input = iconv('UTF-8','ASCII//TRANSLIT',$input);
        $input = preg_replace("/['|^|`|~|]/","",$input);
        $input = preg_replace('/["]/','',$input);
        return preg_replace('/[" "]/','_',$input);
    }
}

Extend contigency table with proportions (percentages)

Here is another example using the lapply and table functions in base R.

freqList = lapply(select_if(tips, is.factor), 
              function(x) {
                  df = data.frame(table(x))

                  df = data.frame(fct = df[, 1], 
                                  n = sapply(df[, 2], function(y) {
                                      round(y / nrow(dat), 2)
                                    }
                                )
                            )
                  return(df) 
                    }
                )

Use print(freqList) to see the proportion tables (percent of frequencies) for each column/feature/variable (depending on your tradecraft) that is labeled as a factor.

How to navigate a few folders up?

If you know the folder you want to navigate to, find the index of it then substring.

            var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");

            string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);

How to get a DOM Element from a JQuery Selector

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html

$(this).attr("checked") ? $(this).val() : 0

This will return the value if it's checked, or 0 if it's not.

$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

How to see my Eclipse version?

Same issue i was getting , but When we open our eclipse software then automatically we can see eclipse version and workspace location like these pic below enter image description here

Convert command line arguments into an array in Bash

Easier Yet, you can operate directly on $@ ;)

Here is how to do pass a a list of args directly from the prompt:

function echoarg { for stuff in "$@" ; do echo $stuff ; done ; } 
    echoarg Hey Ho Lets Go
    Hey
    Ho
    Lets
    Go

Difference between multitasking, multithreading and multiprocessing?

A multiprogramming is the process when a computer system is performing different tasks all at once in a single computer system.

Filtering Pandas DataFrames on dates

You could just select the time range by doing: df.loc['start_date':'end_date']

javascript close current window

In JavaScript, we can close a window only if it is opened by using window.open method:

window.open('https://www.google.com');
window.close();

But to close a window which has not been opened using window.open(), you must

  1. Open any other URL or a blank page in the same tab
  2. Close this newly opened tab (this will work because it was opened by window.open())
window.open("", "_self");
window.close();

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

One contending technology you've omitted is Server-Sent Events / Event Source. What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet? has a good discussion of all of these. Keep in mind that some of these are easier than others to integrate with on the server side.

Why can't I center with margin: 0 auto?

I don't know why the first answer is the best one, I tried it and not working in fact, as @kalys.osmonov said, you can give text-align:center to header, but you have to make ul as inline-block rather than inline, and also you have to notice that text-align can be inherited which is not good to some degree, so the better way (not working below IE 9) is using margin and transform. Just remove float right and margin;0 auto from ul, like below:

#header ul {
   /* float: right; */
   /* margin: 0 auto; */
   display: inline-block;
   margin-left: 50%; /* From parent width */
   transform: translateX(-50%); /* use self width which can be unknown */
  -ms-transform: translateX(-50%); /* For IE9 */
}

This way can fix the problem that making dynamic width of ul center if you don't care IE8 etc.

How can I convert a string to boolean in JavaScript?

function parseBool(value) {
    if (typeof value === "boolean") return value;

    if (typeof value === "number") {
        return value === 1 ? true : value === 0 ? false : undefined;
    }

    if (typeof value != "string") return undefined;

    return value.toLowerCase() === 'true' ? true : false;
}

Is it possible to create a 'link to a folder' in a SharePoint document library?

i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.

Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.

.url files can be made by saving a favourite with internet exploiter.

Change NULL values in Datetime format to empty string

select case when IsNull(CONVERT(DATE, StartDate),'')='' then 'NA' else Convert(varchar(10),StartDate,121) end from table1

Iterate a list with indexes in Python

Here it is a solution using map function:

>>> a = [3, 7, 19]
>>> map(lambda x: (x, a[x]), range(len(a)))
[(0, 3), (1, 7), (2, 19)]

And a solution using list comprehensions:

>>> a = [3,7,19]
>>> [(x, a[x]) for x in range(len(a))]
[(0, 3), (1, 7), (2, 19)]

How to restart kubernetes nodes?

If a node is so unhealthy that the master can't get status from it -- Kubernetes may not be able to restart the node. And if health checks aren't working, what hope do you have of accessing the node by SSH?

In this case, you may have to hard-reboot -- or, if your hardware is in the cloud, let your provider do it.

For example, the AWS EC2 Dashboard allows you to right-click an instance to pull up an "Instance State" menu -- from which you can reboot/terminate an unresponsive node.

Before doing this, you might choose to kubectl cordon node for good measure. And you may find kubectl delete node to be an important part of the process for getting things back to normal -- if the node doesn't automatically rejoin the cluster after a reboot.


Why would a node become unresponsive? Probably some resource has been exhausted in a way that prevents the host operating system from handling new requests in a timely manner. This could be disk, or network -- but the more insidious case is out-of-memory (OOM), which Linux handles poorly.

To help Kubernetes manage node memory safely, it's a good idea to do both of the following:

  • Reserve some memory for the system.
  • Be very careful with (avoid) opportunistic memory specifications for your pods. In other words, don't allow different values of requests and limits for memory.

The idea here is to avoid the complications associated with memory overcommit, because memory is incompressible, and both Linux and Kubernetes' OOM killers may not trigger before the node has already become unhealthy and unreachable.

Get input value from TextField in iOS alert in Swift

Updated for Swift 3 and above:

//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.text = "Some default text"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.present(alert, animated: true, completion: nil)

Swift 2.x

Assuming you want an action alert on iOS:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

How to programmatically disable page scrolling with jQuery

  • To Hide Scroll: $("body").css("overflow", "hidden");
  • To Restore Scroll: $("body").css("overflow", "initial");

MS SQL 2008 - get all table names and their row counts in a DB

SELECT sc.name +'.'+ ta.name TableName
 ,SUM(pa.rows) RowCnt
 FROM sys.tables ta
 INNER JOIN sys.partitions pa
 ON pa.OBJECT_ID = ta.OBJECT_ID
 INNER JOIN sys.schemas sc
 ON ta.schema_id = sc.schema_id
 WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
 GROUP BY sc.name,ta.name
 ORDER BY SUM(pa.rows) DESC

See this:

How should I store GUID in MySQL tables?

char(36) would be a good choice. Also MySQL's UUID() function can be used which returns a 36-character text format (hex with hyphens) which can be used for retrievals of such IDs from the db.

ConcurrentHashMap vs Synchronized HashMap

A simple performance test for ConcurrentHashMap vs Synchronized HashMap . The test flow is calling put in one thread and calling get in three threads on Map concurrently. As @trshiv said, ConcurrentHashMap has higher throughput and speed for whose reading operation without lock. The result is when operation times is over 10^7, ConcurrentHashMap is 2x faster than Synchronized HashMap.

How to create unique keys for React elements?

To add the latest solution for 2021...

I found that the project nanoid provides unique string ids that can be used as key while also being fast and very small.

After installing using npm install nanoid, use as follows:

import { nanoid } from 'nanoid';

// Have the id associated with the data.
const todos = [{id: nanoid(), text: 'first todo'}];

// Then later, it can be rendered using a stable id as the key.
const todoItems = todos.map((todo) =>
  <li key={todo.id}>
    {todo.text}
  </li>
)

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

bootstrap 3 tabs not working properly

This will work

$(".nav-tabs a").click(function(){
     $(this).tab('show');
 });

How to print to console using swift playground?

As of Xcode 7.0.1 println is change to print. Look at the image. there are lot more we can print out. enter image description here

Python progression path - From apprentice to guru

Check out Peter Norvig's essay on becoming a master programmer in 10 years: http://norvig.com/21-days.html. I'd wager it holds true for any language.

Emulate a 403 error page

Seen a lot of the answers, but the correct one is to provide the full options for the header function call as per the php manual

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

If you invoke with

header('HTTP/1.0 403 Forbidden', true, 403);

the normal behavior of HTTP 403 as configured with Apache or any other server would follow.

Extract string between two strings in java

Your pattern is fine. But you shouldn't be split()ting it away, you should find() it. Following code gives the output you are looking for:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

invalid types 'int[int]' for array subscript

int myArray[10][10][10];

should be

int myArray[10][10][10][10];

net::ERR_INSECURE_RESPONSE in Chrome

Don't know if this question is relevant anymore, but this happened to me on a client wich had an incorrect datetime set on Windows. This will be an alternative to watch. If is this case, it will reproduce on other browsers as well (at least, on firefox and chrome).

I fixed it updating datetime on Windows to actual's real datetime. Hope it helps somebody.

How to capitalize the first letter of a String in Java?

Current answers are either incorrect or over-complicate this simple task. After doing some research, here are two approaches I come up with:

1. String's substring() Method

public static String capitalize(String str) {
    if(str== null || str.isEmpty()) {
        return str;
    }

    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

Examples:

System.out.println(capitalize("java")); // Java
System.out.println(capitalize("beTa")); // BeTa
System.out.println(capitalize(null)); // null

2. Apache Commons Lang

The Apache Commons Lang library provides StringUtils the class for this purpose:

System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null

Don't forget to add the following dependency to your pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

Get MIME type from filename extension

I know the question is for C# I just want to left in Javascript format because i just converted the Samuel's answer:

export const contentTypes = {

".323": "text/h323",
".3g2": "video/3gpp2",
".3gp": "video/3gpp",
".3gp2": "video/3gpp2",
".3gpp": "video/3gpp",
".7z": "application/x-7z-compressed",
".aa": "audio/audible",
".AAC": "audio/aac",
".aaf": "application/octet-stream",
".aax": "audio/vnd.audible.aax",
".ac3": "audio/ac3",
".aca": "application/octet-stream",
".accda": "application/msaccess.addin",
".accdb": "application/msaccess",
".accdc": "application/msaccess.cab",
".accde": "application/msaccess",
".accdr": "application/msaccess.runtime",
".accdt": "application/msaccess",
".accdw": "application/msaccess.webapplication",
".accft": "application/msaccess.ftemplate",
".acx": "application/internet-property-stream",
".AddIn": "text/xml",
".ade": "application/msaccess",
".adobebridge": "application/x-bridge-url",
".adp": "application/msaccess",
".ADT": "audio/vnd.dlna.adts",
".ADTS": "audio/aac",
".afm": "application/octet-stream",
".ai": "application/postscript",
".aif": "audio/x-aiff",
".aifc": "audio/aiff",
".aiff": "audio/aiff",
".air": "application/vnd.adobe.air-application-installer-package+zip",
".amc": "application/x-mpeg",
".application": "application/x-ms-application",
".art": "image/x-jg",
".asa": "application/xml",
".asax": "application/xml",
".ascx": "application/xml",
".asd": "application/octet-stream",
".asf": "video/x-ms-asf",
".ashx": "application/xml",
".asi": "application/octet-stream",
".asm": "text/plain",
".asmx": "application/xml",
".aspx": "application/xml",
".asr": "video/x-ms-asf",
".asx": "video/x-ms-asf",
".atom": "application/atom+xml",
".au": "audio/basic",
".avi": "video/x-msvideo",
".axs": "application/olescript",
".bas": "text/plain",
".bcpio": "application/x-bcpio",
".bin": "application/octet-stream",
".bmp": "image/bmp",
".c": "text/plain",
".cab": "application/octet-stream",
".caf": "audio/x-caf",
".calx": "application/vnd.ms-office.calx",
".cat": "application/vnd.ms-pki.seccat",
".cc": "text/plain",
".cd": "text/plain",
".cdda": "audio/aiff",
".cdf": "application/x-cdf",
".cer": "application/x-x509-ca-cert",
".chm": "application/octet-stream",
".class": "application/x-java-applet",
".clp": "application/x-msclip",
".cmx": "image/x-cmx",
".cnf": "text/plain",
".cod": "image/cis-cod",
".config": "application/xml",
".contact": "text/x-ms-contact",
".coverage": "application/xml",
".cpio": "application/x-cpio",
".cpp": "text/plain",
".crd": "application/x-mscardfile",
".crl": "application/pkix-crl",
".crt": "application/x-x509-ca-cert",
".cs": "text/plain",
".csdproj": "text/plain",
".csh": "application/x-csh",
".csproj": "text/plain",
".css": "text/css",
".csv": "text/csv",
".cur": "application/octet-stream",
".cxx": "text/plain",
".dat": "application/octet-stream",
".datasource": "application/xml",
".dbproj": "text/plain",
".dcr": "application/x-director",
".def": "text/plain",
".deploy": "application/octet-stream",
".der": "application/x-x509-ca-cert",
".dgml": "application/xml",
".dib": "image/bmp",
".dif": "video/x-dv",
".dir": "application/x-director",
".disco": "text/xml",
".dll": "application/x-msdownload",
".dll.config": "text/xml",
".dlm": "text/dlm",
".doc": "application/msword",
".docm": "application/vnd.ms-word.document.macroEnabled.12",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".dot": "application/msword",
".dotm": "application/vnd.ms-word.template.macroEnabled.12",
".dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
".dsp": "application/octet-stream",
".dsw": "text/plain",
".dtd": "text/xml",
".dtsConfig": "text/xml",
".dv": "video/x-dv",
".dvi": "application/x-dvi",
".dwf": "drawing/x-dwf",
".dwp": "application/octet-stream",
".dxr": "application/x-director",
".eml": "message/rfc822",
".emz": "application/octet-stream",
".eot": "application/octet-stream",
".eps": "application/postscript",
".etl": "application/etl",
".etx": "text/x-setext",
".evy": "application/envoy",
".exe": "application/octet-stream",
".exe.config": "text/xml",
".fdf": "application/vnd.fdf",
".fif": "application/fractals",
".filters": "Application/xml",
".fla": "application/octet-stream",
".flr": "x-world/x-vrml",
".flv": "video/x-flv",
".fsscript": "application/fsharp-script",
".fsx": "application/fsharp-script",
".generictest": "application/xml",
".gif": "image/gif",
".group": "text/x-ms-group",
".gsm": "audio/x-gsm",
".gtar": "application/x-gtar",
".gz": "application/x-gzip",
".h": "text/plain",
".hdf": "application/x-hdf",
".hdml": "text/x-hdml",
".hhc": "application/x-oleobject",
".hhk": "application/octet-stream",
".hhp": "application/octet-stream",
".hlp": "application/winhlp",
".hpp": "text/plain",
".hqx": "application/mac-binhex40",
".hta": "application/hta",
".htc": "text/x-component",
".htm": "text/html",
".html": "text/html",
".htt": "text/webviewhtml",
".hxa": "application/xml",
".hxc": "application/xml",
".hxd": "application/octet-stream",
".hxe": "application/xml",
".hxf": "application/xml",
".hxh": "application/octet-stream",
".hxi": "application/octet-stream",
".hxk": "application/xml",
".hxq": "application/octet-stream",
".hxr": "application/octet-stream",
".hxs": "application/octet-stream",
".hxt": "text/html",
".hxv": "application/xml",
".hxw": "application/octet-stream",
".hxx": "text/plain",
".i": "text/plain",
".ico": "image/x-icon",
".ics": "application/octet-stream",
".idl": "text/plain",
".ief": "image/ief",
".iii": "application/x-iphone",
".inc": "text/plain",
".inf": "application/octet-stream",
".inl": "text/plain",
".ins": "application/x-internet-signup",
".ipa": "application/x-itunes-ipa",
".ipg": "application/x-itunes-ipg",
".ipproj": "text/plain",
".ipsw": "application/x-itunes-ipsw",
".iqy": "text/x-ms-iqy",
".isp": "application/x-internet-signup",
".ite": "application/x-itunes-ite",
".itlp": "application/x-itunes-itlp",
".itms": "application/x-itunes-itms",
".itpc": "application/x-itunes-itpc",
".IVF": "video/x-ivf",
".jar": "application/java-archive",
".java": "application/octet-stream",
".jck": "application/liquidmotion",
".jcz": "application/liquidmotion",
".jfif": "image/pjpeg",
".jnlp": "application/x-java-jnlp-file",
".jpb": "application/octet-stream",
".jpe": "image/jpeg",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".js": "application/x-javascript",
".json": "application/json",
".jsx": "text/jscript",
".jsxbin": "text/plain",
".latex": "application/x-latex",
".library-ms": "application/windows-library+xml",
".lit": "application/x-ms-reader",
".loadtest": "application/xml",
".lpk": "application/octet-stream",
".lsf": "video/x-la-asf",
".lst": "text/plain",
".lsx": "video/x-la-asf",
".lzh": "application/octet-stream",
".m13": "application/x-msmediaview",
".m14": "application/x-msmediaview",
".m1v": "video/mpeg",
".m2t": "video/vnd.dlna.mpeg-tts",
".m2ts": "video/vnd.dlna.mpeg-tts",
".m2v": "video/mpeg",
".m3u": "audio/x-mpegurl",
".m3u8": "audio/x-mpegurl",
".m4a": "audio/m4a",
".m4b": "audio/m4b",
".m4p": "audio/m4p",
".m4r": "audio/x-m4r",
".m4v": "video/x-m4v",
".mac": "image/x-macpaint",
".mak": "text/plain",
".man": "application/x-troff-man",
".manifest": "application/x-ms-manifest",
".map": "text/plain",
".master": "application/xml",
".mda": "application/msaccess",
".mdb": "application/x-msaccess",
".mde": "application/msaccess",
".mdp": "application/octet-stream",
".me": "application/x-troff-me",
".mfp": "application/x-shockwave-flash",
".mht": "message/rfc822",
".mhtml": "message/rfc822",
".mid": "audio/mid",
".midi": "audio/mid",
".mix": "application/octet-stream",
".mk": "text/plain",
".mmf": "application/x-smaf",
".mno": "text/xml",
".mny": "application/x-msmoney",
".mod": "video/mpeg",
".mov": "video/quicktime",
".movie": "video/x-sgi-movie",
".mp2": "video/mpeg",
".mp2v": "video/mpeg",
".mp3": "audio/mpeg",
".mp4": "video/mp4",
".mp4v": "video/mp4",
".mpa": "video/mpeg",
".mpe": "video/mpeg",
".mpeg": "video/mpeg",
".mpf": "application/vnd.ms-mediapackage",
".mpg": "video/mpeg",
".mpp": "application/vnd.ms-project",
".mpv2": "video/mpeg",
".mqv": "video/quicktime",
".ms": "application/x-troff-ms",
".msi": "application/octet-stream",
".mso": "application/octet-stream",
".mts": "video/vnd.dlna.mpeg-tts",
".mtx": "application/xml",
".mvb": "application/x-msmediaview",
".mvc": "application/x-miva-compiled",
".mxp": "application/x-mmxp",
".nc": "application/x-netcdf",
".nsc": "video/x-ms-asf",
".nws": "message/rfc822",
".ocx": "application/octet-stream",
".oda": "application/oda",
".odc": "text/x-ms-odc",
".odh": "text/plain",
".odl": "text/plain",
".odp": "application/vnd.oasis.opendocument.presentation",
".ods": "application/oleobject",
".odt": "application/vnd.oasis.opendocument.text",
".one": "application/onenote",
".onea": "application/onenote",
".onepkg": "application/onenote",
".onetmp": "application/onenote",
".onetoc": "application/onenote",
".onetoc2": "application/onenote",
".orderedtest": "application/xml",
".osdx": "application/opensearchdescription+xml",
".p10": "application/pkcs10",
".p12": "application/x-pkcs12",
".p7b": "application/x-pkcs7-certificates",
".p7c": "application/pkcs7-mime",
".p7m": "application/pkcs7-mime",
".p7r": "application/x-pkcs7-certreqresp",
".p7s": "application/pkcs7-signature",
".pbm": "image/x-portable-bitmap",
".pcast": "application/x-podcast",
".pct": "image/pict",
".pcx": "application/octet-stream",
".pcz": "application/octet-stream",
".pdf": "application/pdf",
".pfb": "application/octet-stream",
".pfm": "application/octet-stream",
".pfx": "application/x-pkcs12",
".pgm": "image/x-portable-graymap",
".pic": "image/pict",
".pict": "image/pict",
".pkgdef": "text/plain",
".pkgundef": "text/plain",
".pko": "application/vnd.ms-pki.pko",
".pls": "audio/scpls",
".pma": "application/x-perfmon",
".pmc": "application/x-perfmon",
".pml": "application/x-perfmon",
".pmr": "application/x-perfmon",
".pmw": "application/x-perfmon",
".png": "image/png",
".pnm": "image/x-portable-anymap",
".pnt": "image/x-macpaint",
".pntg": "image/x-macpaint",
".pnz": "image/png",
".pot": "application/vnd.ms-powerpoint",
".potm": "application/vnd.ms-powerpoint.template.macroEnabled.12",
".potx": "application/vnd.openxmlformats-officedocument.presentationml.template",
".ppa": "application/vnd.ms-powerpoint",
".ppam": "application/vnd.ms-powerpoint.addin.macroEnabled.12",
".ppm": "image/x-portable-pixmap",
".pps": "application/vnd.ms-powerpoint",
".ppsm": "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
".ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
".ppt": "application/vnd.ms-powerpoint",
".pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".prf": "application/pics-rules",
".prm": "application/octet-stream",
".prx": "application/octet-stream",
".ps": "application/postscript",
".psc1": "application/PowerShell",
".psd": "application/octet-stream",
".psess": "application/xml",
".psm": "application/octet-stream",
".psp": "application/octet-stream",
".pub": "application/x-mspublisher",
".pwz": "application/vnd.ms-powerpoint",
".qht": "text/x-html-insertion",
".qhtm": "text/x-html-insertion",
".qt": "video/quicktime",
".qti": "image/x-quicktime",
".qtif": "image/x-quicktime",
".qtl": "application/x-quicktimeplayer",
".qxd": "application/octet-stream",
".ra": "audio/x-pn-realaudio",
".ram": "audio/x-pn-realaudio",
".rar": "application/octet-stream",
".ras": "image/x-cmu-raster",
".rat": "application/rat-file",
".rc": "text/plain",
".rc2": "text/plain",
".rct": "text/plain",
".rdlc": "application/xml",
".resx": "application/xml",
".rf": "image/vnd.rn-realflash",
".rgb": "image/x-rgb",
".rgs": "text/plain",
".rm": "application/vnd.rn-realmedia",
".rmi": "audio/mid",
".rmp": "application/vnd.rn-rn_music_package",
".roff": "application/x-troff",
".rpm": "audio/x-pn-realaudio-plugin",
".rqy": "text/x-ms-rqy",
".rtf": "application/rtf",
".rtx": "text/richtext",
".ruleset": "application/xml",
".s": "text/plain",
".safariextz": "application/x-safari-safariextz",
".scd": "application/x-msschedule",
".sct": "text/scriptlet",
".sd2": "audio/x-sd2",
".sdp": "application/sdp",
".sea": "application/octet-stream",
".searchConnector-ms": "application/windows-search-connector+xml",
".setpay": "application/set-payment-initiation",
".setreg": "application/set-registration-initiation",
".settings": "application/xml",
".sgimb": "application/x-sgimb",
".sgml": "text/sgml",
".sh": "application/x-sh",
".shar": "application/x-shar",
".shtml": "text/html",
".sit": "application/x-stuffit",
".sitemap": "application/xml",
".skin": "application/xml",
".sldm": "application/vnd.ms-powerpoint.slide.macroEnabled.12",
".sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide",
".slk": "application/vnd.ms-excel",
".sln": "text/plain",
".slupkg-ms": "application/x-ms-license",
".smd": "audio/x-smd",
".smi": "application/octet-stream",
".smx": "audio/x-smd",
".smz": "audio/x-smd",
".snd": "audio/basic",
".snippet": "application/xml",
".snp": "application/octet-stream",
".sol": "text/plain",
".sor": "text/plain",
".spc": "application/x-pkcs7-certificates",
".spl": "application/futuresplash",
".src": "application/x-wais-source",
".srf": "text/plain",
".SSISDeploymentManifest": "text/xml",
".ssm": "application/streamingmedia",
".sst": "application/vnd.ms-pki.certstore",
".stl": "application/vnd.ms-pki.stl",
".sv4cpio": "application/x-sv4cpio",
".sv4crc": "application/x-sv4crc",
".svc": "application/xml",
".swf": "application/x-shockwave-flash",
".t": "application/x-troff",
".tar": "application/x-tar",
".tcl": "application/x-tcl",
".testrunconfig": "application/xml",
".testsettings": "application/xml",
".tex": "application/x-tex",
".texi": "application/x-texinfo",
".texinfo": "application/x-texinfo",
".tgz": "application/x-compressed",
".thmx": "application/vnd.ms-officetheme",
".thn": "application/octet-stream",
".tif": "image/tiff",
".tiff": "image/tiff",
".tlh": "text/plain",
".tli": "text/plain",
".toc": "application/octet-stream",
".tr": "application/x-troff",
".trm": "application/x-msterminal",
".trx": "application/xml",
".ts": "video/vnd.dlna.mpeg-tts",
".tsv": "text/tab-separated-values",
".ttf": "application/octet-stream",
".tts": "video/vnd.dlna.mpeg-tts",
".txt": "text/plain",
".u32": "application/octet-stream",
".uls": "text/iuls",
".user": "text/plain",
".ustar": "application/x-ustar",
".vb": "text/plain",
".vbdproj": "text/plain",
".vbk": "video/mpeg",
".vbproj": "text/plain",
".vbs": "text/vbscript",
".vcf": "text/x-vcard",
".vcproj": "Application/xml",
".vcs": "text/plain",
".vcxproj": "Application/xml",
".vddproj": "text/plain",
".vdp": "text/plain",
".vdproj": "text/plain",
".vdx": "application/vnd.ms-visio.viewer",
".vml": "text/xml",
".vscontent": "application/xml",
".vsct": "text/xml",
".vsd": "application/vnd.visio",
".vsi": "application/ms-vsi",
".vsix": "application/vsix",
".vsixlangpack": "text/xml",
".vsixmanifest": "text/xml",
".vsmdi": "application/xml",
".vspscc": "text/plain",
".vss": "application/vnd.visio",
".vsscc": "text/plain",
".vssettings": "text/xml",
".vssscc": "text/plain",
".vst": "application/vnd.visio",
".vstemplate": "text/xml",
".vsto": "application/x-ms-vsto",
".vsw": "application/vnd.visio",
".vsx": "application/vnd.visio",
".vtx": "application/vnd.visio",
".wav": "audio/wav",
".wave": "audio/wav",
".wax": "audio/x-ms-wax",
".wbk": "application/msword",
".wbmp": "image/vnd.wap.wbmp",
".wcm": "application/vnd.ms-works",
".wdb": "application/vnd.ms-works",
".wdp": "image/vnd.ms-photo",
".webarchive": "application/x-safari-webarchive",
".webtest": "application/xml",
".wiq": "application/xml",
".wiz": "application/msword",
".wks": "application/vnd.ms-works",
".WLMP": "application/wlmoviemaker",
".wlpginstall": "application/x-wlpg-detect",
".wlpginstall3": "application/x-wlpg3-detect",
".wm": "video/x-ms-wm",
".wma": "audio/x-ms-wma",
".wmd": "application/x-ms-wmd",
".wmf": "application/x-msmetafile",
".wml": "text/vnd.wap.wml",
".wmlc": "application/vnd.wap.wmlc",
".wmls": "text/vnd.wap.wmlscript",
".wmlsc": "application/vnd.wap.wmlscriptc",
".wmp": "video/x-ms-wmp",
".wmv": "video/x-ms-wmv",
".wmx": "video/x-ms-wmx",
".wmz": "application/x-ms-wmz",
".wpl": "application/vnd.ms-wpl",
".wps": "application/vnd.ms-works",
".wri": "application/x-mswrite",
".wrl": "x-world/x-vrml",
".wrz": "x-world/x-vrml",
".wsc": "text/scriptlet",
".wsdl": "text/xml",
".wvx": "video/x-ms-wvx",
".x": "application/directx",
".xaf": "x-world/x-vrml",
".xaml": "application/xaml+xml",
".xap": "application/x-silverlight-app",
".xbap": "application/x-ms-xbap",
".xbm": "image/x-xbitmap",
".xdr": "text/plain",
".xht": "application/xhtml+xml",
".xhtml": "application/xhtml+xml",
".xla": "application/vnd.ms-excel",
".xlam": "application/vnd.ms-excel.addin.macroEnabled.12",
".xlc": "application/vnd.ms-excel",
".xld": "application/vnd.ms-excel",
".xlk": "application/vnd.ms-excel",
".xll": "application/vnd.ms-excel",
".xlm": "application/vnd.ms-excel",
".xls": "application/vnd.ms-excel",
".xlsb": "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
".xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".xlt": "application/vnd.ms-excel",
".xltm": "application/vnd.ms-excel.template.macroEnabled.12",
".xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
".xlw": "application/vnd.ms-excel",
".xml": "text/xml",
".xmta": "application/xml",
".xof": "x-world/x-vrml",
".XOML": "text/plain",
".xpm": "image/x-xpixmap",
".xps": "application/vnd.ms-xpsdocument",
".xrm-ms": "text/xml",
".xsc": "application/xml",
".xsd": "text/xml",
".xsf": "text/xml",
".xsl": "text/xml",
".xslt": "text/xml",
".xsn": "application/octet-stream",
".xss": "application/xml",
".xtp": "application/octet-stream",
".xwd": "image/x-xwindowdump",
".z": "application/x-compress",
".zip": "application/x-zip-compressed"
}

Send FormData with other field in AngularJS

You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.

var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)

CSS submit button weird rendering on iPad/iPhone

oops! just found myself: just add this line on any element you need

   -webkit-appearance: none;

chai test array equality doesn't work as expected

You can use .deepEqual()

const { assert } = require('chai');

assert.deepEqual([0,0], [0,0]);

How to keep keys/values in same order as declared?

Dictionaries will use an order that makes searching efficient, and you cant change that,

You could just use a list of objects (a 2 element tuple in a simple case, or even a class), and append items to the end. You can then use linear search to find items in it.

Alternatively you could create or use a different data structure created with the intention of maintaining order.

How can I select an element in a component template?

For components inside *ngIf, another approach:

The component I wanted to select was inside a div's *ngIf statement, and @jsgoupil's answer above probably works (Thanks @jsgoupil!), but I ended up finding a way to avoid using *ngIf, by using CSS to hide the element.

When the condition in the [className] is true, the div gets displayed, and naming the component using # works and it can be selected from within the typescript code. When the condition is false, it's not displayed, and I don't need to select it anyway.

Component:

@Component({
    selector: 'bla',
    templateUrl: 'bla.component.html',
    styleUrls: ['bla.component.scss']
})
export class BlaComponent implements OnInit, OnDestroy {
    @ViewChild('myComponentWidget', {static: true}) public myComponentWidget: any;
    @Input('action') action: ActionType; // an enum defined in our code. (action could also be declared locally)

constructor() {
   etc;
}

// this lets you use an enum in the HMTL (ActionType.SomeType)
public get actionTypeEnum(): typeOf ActionType {
    return ActionType;
}

public someMethodXYZ: void {
    this.myComponentWidget.someMethod(); // use it like that, assuming the method exists
}

and then in the bla.component.html file:

<div [className]="action === actionTypeEnum.SomeType ? 'show-it' : 'do-not-show'">

    <my-component #myComponentWidget etc></my-component>
</div>
<div>
    <button type="reset" class="bunch-of-classes" (click)="someMethodXYZ()">
        <span>XYZ</span>
    </button>
</div>   

and the CSS file:

 ::ng-deep {
    .show-it {
         display: block;   // example, actually a lot more css in our code
    }
    .do-not-show {
        display: none'; 
    }
}

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

x_train = x_train.reshape(-1,28, 28, 1)   #Reshape for CNN -  should work!!
x_test = x_test.reshape(-1,28, 28, 1)
history_cnn = cnn.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))

Output:

Train on 60000 samples, validate on 10000 samples Epoch 1/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0981 - acc: 0.9692 - val_loss: 0.0468 - val_acc: 0.9861 Epoch 2/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0352 - acc: 0.9892 - val_loss: 0.0408 - val_acc: 0.9879 Epoch 3/5 60000/60000 [==============================] - 159s 3ms/step - loss: 0.0242 - acc: 0.9924 - val_loss: 0.0291 - val_acc: 0.9913 Epoch 4/5 60000/60000 [==============================] - 165s 3ms/step - loss: 0.0181 - acc: 0.9945 - val_loss: 0.0361 - val_acc: 0.9888 Epoch 5/5 60000/60000 [==============================] - 168s 3ms/step - loss: 0.0142 - acc: 0.9958 - val_loss: 0.0354 - val_acc: 0.9906

java : convert float to String and String to float

String str = "1234.56";
float num = 0.0f;

int digits = str.length()- str.indexOf('.') - 1;

float factor = 1f;

for(int i=0;i<digits;i++) factor /= 10;

for(int i=str.length()-1;i>=0;i--){

    if(str.charAt(i) == '.'){
        factor = 1;
        System.out.println("Reset, value="+num);
        continue;
    }

    num += (str.charAt(i) - '0') * factor;
    factor *= 10;
}

System.out.println(num);

AssertNull should be used or AssertNotNull

assertNotNull asserts that the object is not null. If it is null the test fails, so you want that.

Sum a list of numbers in Python

The simplest way to solve this problem:

l =[1,2,3,4,5]
sum=0
for element in l:
    sum+=element
print sum

jQuery Keypress Arrow Keys

You can check wether an arrow key is pressed by:

$(document).keydown(function(e){
    if (e.keyCode > 36 && e.keyCode < 41) 
      alert( "arrowkey pressed" );          
});

jsfiddle demo

navbar color in Twitter Bootstrap

You can download a custom version of bootstrap and set @navbarBackground to the color you want.

http://twitter.github.com/bootstrap/customize.html

List files committed for a revision

svn log --verbose -r 42

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

Update August 20, 2020 -- Now is simple!

from selenium.webdriver.support.ui import WebDriverWait

chrome_options = webdriver.ChromeOptions()
chrome_options.headless = True

self.driver = webdriver.Chrome(
            executable_path=DRIVER_PATH, chrome_options=chrome_options)

How to get Printer Info in .NET?

As dowski suggested, you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.

using System.Management;

...

string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
    try
    {
        foreach (ManagementObject printer in coll)
        {
            foreach (PropertyData property in printer.Properties)
            {
                Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
            }
        }
    }
    catch (ManagementException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Xcode Objective-C | iOS: delay function / NSTimer help?

Try

NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.06 ];
[NSThread sleepUntilDate:future];

CUDA incompatible with my gcc version

As already pointed out, nvcc depends on gcc 4.4. It is possible to configure nvcc to use the correct version of gcc without passing any compiler parameters by adding softlinks to the bin directory created with the nvcc install.

The default cuda binary directory (the installation default) is /usr/local/cuda/bin, adding a softlink to the correct version of gcc from this directory is sufficient:

sudo ln -s /usr/bin/gcc-4.4 /usr/local/cuda/bin/gcc

How can I rename a project folder from within Visual Studio?

I use Visual Studio 2013 and TFS 2013.

I did it like this:

  1. Open Visual Studio, without opening the solution itself, and use Source Control Explorer to find and rename folders for projects
  2. Double-click the solution file in Source Control Explorer to open a solution.
  3. You get a question: "Projects have recently been added to this solution. Do you want to get them from source control?", and you choose Yes.
  4. Now the folder and project structure are there, but now files, so now you get the latest version from source control
  5. Try to build and commit changes.

Making authenticated POST requests with Spring RestTemplate for Android

Slightly different approach:

MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("HeaderName", "value");
headers.add("Content-Type", "application/json");

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

HttpEntity<ObjectToPass> request = new HttpEntity<ObjectToPass>(objectToPass, headers);

restTemplate.postForObject(url, request, ClassWhateverYourControllerReturns.class);

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

In my case, this error comes from my trial to remove dependencies to MSVC-version dependent runtime library DLL (msvcr10.dll or so) and/or remove static runtime library too, to remove excess fat from my executables.

So I use /NODEFAULTLIB linker switch, my self-made "msvcrt-light.lib" (google for it when you need), and mainCRTStartup() / WinMainCRTStartup() entries.

It is IMHO since Visual Studio 2015, so I stuck to older compilers.

However, defining symbol _NO_CRT_STDIO_INLINE removes all hassle, and a simple "Hello World" application is again 3 KB small and doesn't depend to unusual DLLs. Tested in Visual Studio 2017.

EF LINQ include multiple and nested entities

Include is a part of fluent interface, so you can write multiple Include statements each following other

 db.Courses.Include(i => i.Modules.Select(s => s.Chapters))
           .Include(i => i.Lab)
           .Single(x => x.Id == id); 

Android overlay a view ontop of everything?

The best way is ViewOverlay , You can add any drawable as overlay to any view as its overlay since Android JellyBeanMR2(Api 18).

Add mMyDrawable to mMyView as its overlay:

mMyDrawable.setBounds(0, 0, mMyView.getMeasuredWidth(), mMyView.getMeasuredHeight())
mMyView.getOverlay().add(mMyDrawable)

Git clone without .git directory

since you only want the files, you don't need to treat it as a git repo.

rsync -rlp --exclude '.git' user@host:path/to/git/repo/ .

and this only works with local path and remote ssh/rsync path, it may not work if the remote server only provides git:// or https:// access.

How to use pip with python 3.4 on windows?

I had the same problem when I install python3.5.3. And finally I find the pip.exe in this folder: ~/python/scripts/pip.exe. Hope that help.

How to create byte array from HttpPostedFile

BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);

line 2 should be replaced with

byte[] binData = b.ReadBytes(file.ContentLength);

Most efficient conversion of ResultSet to JSON?

I think there's a way to use less memory (a fixed and not linear amount depending on data cardinality) but this imply to change the method signature. In fact we may print the Json data directly on an output stream as soon as we fetch them from the ResultSet: the already written data will be garbage collected since we don't need an array that keeps them in memory.

I use GSON that accepts type adapters. I wrote a type adapter to convert ResultSet to JsonArray and it looks very like to your code. I'm waiting the "Gson 2.1: Targeted Dec 31, 2011" release which will have the "Support for user-defined streaming type adapters". Then I'll modify my adapter to be a streaming adapter.


Update

As promised I'm back but not with Gson, instead with Jackson 2. Sorry to be late (of 2 years).

Preface: The key to use less memory of the result itsef is in the "server side" cursor. With this kind of cursors (a.k.a. resultset to Java devs) the DBMS sends data incrementally to client (a.k.a. driver) as the client goes forward with the reading. I think Oracle cursor are server side by default. For MySQL > 5.0.2 look for useCursorFetch at connection url paramenter. Check about your favourite DBMS.

1: So to use less memory we must:

  • use server side cursor behind the scene
  • use resultset open as read only and, of course, forward only;
  • avoid to load all the cursor in a list (or a JSONArray) but write each row directly on an output line, where for output line I mean an output stream or a writer or also a json generator that wraps an output stream or a writer.

2: As Jackson Documentation says:

Streaming API is best performing (lowest overhead, fastest read/write; other 2 methods build on it)

3: I see you in your code use getInt, getBoolean. getFloat... of ResultSet without wasNull. I expect this can yield problems.

4: I used arrays to cache thinks and to avoid to call getters each iteration. Although not a fan of the switch/case construct, I used it for that int SQL Types.

The answer: Not yet fully tested, it's based on Jackson 2.2:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.2.2</version>
</dependency>

The ResultSetSerializer object instructs Jackson on how to serialize (tranform the object to JSON) a ResultSet. It uses the Jackson Streaming API inside. Here the code of a test:

SimpleModule module = new SimpleModule();
module.addSerializer(new ResultSetSerializer());

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);

[ . . . do the query . . . ]
ResultSet resultset = statement.executeQuery(query);

// Use the DataBind Api here
ObjectNode objectNode = objectMapper.createObjectNode();

// put the resultset in a containing structure
objectNode.putPOJO("results", resultset);

// generate all
objectMapper.writeValue(stringWriter, objectNode);

And, of course, the code of the ResultSetSerializer class:

public class ResultSetSerializer extends JsonSerializer<ResultSet> {

    public static class ResultSetSerializerException extends JsonProcessingException{
        private static final long serialVersionUID = -914957626413580734L;

        public ResultSetSerializerException(Throwable cause){
            super(cause);
        }
    }

    @Override
    public Class<ResultSet> handledType() {
        return ResultSet.class;
    }

    @Override
    public void serialize(ResultSet rs, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {

        try {
            ResultSetMetaData rsmd = rs.getMetaData();
            int numColumns = rsmd.getColumnCount();
            String[] columnNames = new String[numColumns];
            int[] columnTypes = new int[numColumns];

            for (int i = 0; i < columnNames.length; i++) {
                columnNames[i] = rsmd.getColumnLabel(i + 1);
                columnTypes[i] = rsmd.getColumnType(i + 1);
            }

            jgen.writeStartArray();

            while (rs.next()) {

                boolean b;
                long l;
                double d;

                jgen.writeStartObject();

                for (int i = 0; i < columnNames.length; i++) {

                    jgen.writeFieldName(columnNames[i]);
                    switch (columnTypes[i]) {

                    case Types.INTEGER:
                        l = rs.getInt(i + 1);
                        if (rs.wasNull()) {
                            jgen.writeNull();
                        } else {
                            jgen.writeNumber(l);
                        }
                        break;

                    case Types.BIGINT:
                        l = rs.getLong(i + 1);
                        if (rs.wasNull()) {
                            jgen.writeNull();
                        } else {
                            jgen.writeNumber(l);
                        }
                        break;

                    case Types.DECIMAL:
                    case Types.NUMERIC:
                        jgen.writeNumber(rs.getBigDecimal(i + 1));
                        break;

                    case Types.FLOAT:
                    case Types.REAL:
                    case Types.DOUBLE:
                        d = rs.getDouble(i + 1);
                        if (rs.wasNull()) {
                            jgen.writeNull();
                        } else {
                            jgen.writeNumber(d);
                        }
                        break;

                    case Types.NVARCHAR:
                    case Types.VARCHAR:
                    case Types.LONGNVARCHAR:
                    case Types.LONGVARCHAR:
                        jgen.writeString(rs.getString(i + 1));
                        break;

                    case Types.BOOLEAN:
                    case Types.BIT:
                        b = rs.getBoolean(i + 1);
                        if (rs.wasNull()) {
                            jgen.writeNull();
                        } else {
                            jgen.writeBoolean(b);
                        }
                        break;

                    case Types.BINARY:
                    case Types.VARBINARY:
                    case Types.LONGVARBINARY:
                        jgen.writeBinary(rs.getBytes(i + 1));
                        break;

                    case Types.TINYINT:
                    case Types.SMALLINT:
                        l = rs.getShort(i + 1);
                        if (rs.wasNull()) {
                            jgen.writeNull();
                        } else {
                            jgen.writeNumber(l);
                        }
                        break;

                    case Types.DATE:
                        provider.defaultSerializeDateValue(rs.getDate(i + 1), jgen);
                        break;

                    case Types.TIMESTAMP:
                        provider.defaultSerializeDateValue(rs.getTime(i + 1), jgen);
                        break;

                    case Types.BLOB:
                        Blob blob = rs.getBlob(i);
                        provider.defaultSerializeValue(blob.getBinaryStream(), jgen);
                        blob.free();
                        break;

                    case Types.CLOB:
                        Clob clob = rs.getClob(i);
                        provider.defaultSerializeValue(clob.getCharacterStream(), jgen);
                        clob.free();
                        break;

                    case Types.ARRAY:
                        throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type ARRAY");

                    case Types.STRUCT:
                        throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type STRUCT");

                    case Types.DISTINCT:
                        throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type DISTINCT");

                    case Types.REF:
                        throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type REF");

                    case Types.JAVA_OBJECT:
                    default:
                        provider.defaultSerializeValue(rs.getObject(i + 1), jgen);
                        break;
                    }
                }

                jgen.writeEndObject();
            }

            jgen.writeEndArray();

        } catch (SQLException e) {
            throw new ResultSetSerializerException(e);
        }
    }
}

What is the result of % in Python?

Python - Basic Operators
http://www.tutorialspoint.com/python/python_basic_operators.htm

Modulus - Divides left hand operand by right hand operand and returns remainder

a = 10 and b = 20

b % a = 0

Post parameter is always null

Double check your data types. The dotnet model binder will not convert a float to an integer (and I'm assuming other related concepts). This will cause the entire model to be rejected.

If you have json like this:

{
    "shoeSize": 10.5
}

but your c# model looks like this:

class Shoe{
    public int shoeSize;
}

the model binder will reject the model and you will get null.

Finding row index containing maximum value using R

How about the following, where y is the name of your matrix and you are looking for the maximum in the entire matrix:

row(y)[y==max(y)]

if you want to extract the row:

y[row(y)[y==max(y)],] # this returns unsorted rows.

To return sorted rows use:

y[sort(row(y)[y==max(y)]),]

The advantage of this approach is that you can change the conditional inside to anything you need. Also, using col(y) and location of the hanging comma you can also extract columns.

y[,col(y)[y==max(y)]]

To find just the row for the max in a particular column, say column 2 you could use:

seq(along=y[,2])[y[,2]==max(y[,2])]

again the conditional is flexible to look for different requirements.

See Phil Spector's excellent "An introduction to S and S-Plus" Chapter 5 for additional ideas.

How to make a HTTP PUT request?

My Final Approach:

    public void PutObject(string postUrl, object payload)
        {
            var request = (HttpWebRequest)WebRequest.Create(postUrl);
            request.Method = "PUT";
            request.ContentType = "application/xml";
            if (payload !=null)
            {
                request.ContentLength = Size(payload);
                Stream dataStream = request.GetRequestStream();
                Serialize(dataStream,payload);
                dataStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string returnString = response.StatusCode.ToString();
        }

public void Serialize(Stream output, object input)
            {
                var ser = new DataContractSerializer(input.GetType());
                ser.WriteObject(output, input);
            }

AngularJS : When to use service instead of factory

Factory and Service are the most commonly used method. The only difference between them is that the Service method works better for objects that need inheritance hierarchy, while the Factory can produce JavaScript primitives and functions.

The Provider function is the core method and all the other ones are just syntactic sugar on it. You need it only if you are building a reusable piece of code that needs global configuration.

There are five methods to create services: Value, Factory, Service, Provider and Constant. You can learn more about this here angular service, this article explain all this methods with practical demo examples.

.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

In Intellij 13, it looks it's slightly different again. Here are the instructions for Intellij 13:

  1. click on the Project view or unhide it by clicking on the "1: Project" button on the left border of the window or by pressing Alt + 1
  2. find your project or sub-module and click on it to highlight it, then press F4, or right click and choose "Open Module Settings" (on IntelliJ 14 it became F12)
  3. click on the dependencies tab
  4. Click the "+" button on the right and select "Jars or directories..."
  5. Find your path and click OK
  6. In the dialog with "Choose Categories of Selected File", choose Classes (even if it's properties), press OK and OK again
  7. You can now run your application and it will have the selected path in the class path

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

An Iframe I need to refresh every 30 seconds (but not the whole page)

I have a simpler solution. In your destination page (irc_online.php) add an auto-refresh tag in the header.

Difference between objectForKey and valueForKey?

Here's a great reason to use objectForKey: wherever possible instead of valueForKey: - valueForKey: with an unknown key will throw NSUnknownKeyException saying "this class is not key value coding-compliant for the key ".

Get paragraph text inside an element

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Where to JavaScript</title>
    <!-- JavaScript in head tag-->
    <script>
        function changeHtmlContent() {
            var content = document.getElementById('content').textContent;
            alert(content);
        }
    </script>
</head>
<body>
    <h4 id="content">Welcome to JavaScript!</h4>
    <button onclick="changeHtmlContent()">Change the content</button>
</body>

Here, we can get the text content of h4 by using:

document.getElementById('content').textContent

Can you nest html forms?

Note you are not allowed to nest FORM elements!

http://www.w3.org/MarkUp/html3/forms.html

https://www.w3.org/TR/html4/appendix/changes.html#h-A.3.9 (html4 specification notes no changes regarding nesting forms from 3.2 to 4)

https://www.w3.org/TR/html4/appendix/changes.html#h-A.1.1.12 (html4 specification notes no changes regarding nesting forms from 4.0 to 4.1)

https://www.w3.org/TR/html5-diff/ (html5 specification notes no changes regarding nesting forms from 4 to 5)

https://www.w3.org/TR/html5/forms.html#association-of-controls-and-forms comments to "This feature allows authors to work around the lack of support for nested form elements.", but does not cite where this is specified, I think they are assuming that we should assume that it's specified in the html3 specification :)

How to get all key in JSON object (javascript)

I use Object.keys which is built into JavaScript Object, it will return an array of keys from given object MDN Reference

var obj = {name: "Jeeva", age: "22", gender: "Male"}
console.log(Object.keys(obj))

Get user's non-truncated Active Directory groups from command line

GPRESULT is the right command, but it cannot be run without parameters. /v or verbose option is difficult to manage without also outputting to a text file. E.G. I recommend using

gpresult /user myAccount /v > C:\dev\me.txt--Ensure C:\Dev\me.txt exists

Another option is to display summary information only which may be entirely visible in the command window:

gpresult /user myAccount /r

The accounts are listed under the heading:

The user is a part of the following security groups
---------------------------------------------------

How to read the RGB value of a given pixel in Python?

If you are looking to have three digits in the form of an RGB colour code, the following code should do just that.

i = Image.open(path)
pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size

all_pixels = []
for x in range(width):
    for y in range(height):
        cpixel = pixels[x, y]
        all_pixels.append(cpixel)

This may work for you.

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

How to set menu to Toolbar in Android

In my case, I'm using an AppBarLayout with a CollapsingToolbarLayout and the menu was always being scrolled out of the screen, I solved my problem by switching android:actionLayout in menu's XML to the toolbar's id. I hope it can help people in the same situation!

activity_main.xml

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.MainScreenActivity"
    android:screenOrientation="portrait">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        app:elevation="0dp"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingBar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="exitUntilCollapsed|scroll"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="48dp"
            >
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:elevation="0dp"
                app:popupTheme="@style/AppTheme.PopupOverlay"
                app:layout_collapseMode="pin"/>
        </android.support.design.widget.CollapsingToolbarLayout>


    </android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

main_menu.xml

<?xml version="1.0" encoding="utf-8"?> <menu
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/logoutMenu"
        android:orderInCategory="100"
        android:title="@string/log_out"
        app:showAsAction="never"
        android:actionLayout="@id/toolbar"/>
    <item
        android:id="@+id/sortMenu"
        android:orderInCategory="100"
        android:title="@string/sort"
        app:showAsAction="never"/> </menu>

Replacing H1 text with a logo image: best method for SEO and accessibility?

I think you'd be interested in the H1 debate. It's a debate about whether to use the h1 element for the page's title or for the logo.

Personally I'd go with your first suggestion, something along these lines:

<div id="header">
    <a href="http://example.com/"><img src="images/logo.png" id="site-logo" alt="MyCorp" /></a>
</div>

<!-- or alternatively (with css in a stylesheet ofc-->
<div id="header">
    <div id="logo" style="background: url('logo.png'); display: block; 
        float: left; width: 100px; height: 50px;">
        <a href="#" style="display: block; height: 50px; width: 100px;">
            <span style="visibility: hidden;">Homepage</span>
        </a>
    </div>
    <!-- with css in a stylesheet: -->
    <div id="logo"><a href="#"><span>Homepage</span></a></div>
</div>


<div id="body">
    <h1>About Us</h1>
    <p>MyCorp has been dealing in narcotics for over nine-thousand years...</p>
</div>

Of course this depends on whether your design uses page titles but this is my stance on this issue.

How to add images in select list?

You already have several answers that suggest using JavaScript/jQuery. I am going to add an alternative that only uses HTML and CSS without any JS.

The basic idea is to use a set of radio buttons and labels (that will activate/deactivate the radio buttons), and with CSS control that only the label associated to the selected radio button will be displayed. If you want to allow selecting multiple values, you could achieve it by using checkboxes instead of radio buttons.

Here is an example. The code may be a bit messier (specially compared to the other solutions):

_x000D_
_x000D_
.select-sim {_x000D_
  width:200px;_x000D_
  height:22px;_x000D_
  line-height:22px;_x000D_
  vertical-align:middle;_x000D_
  position:relative;_x000D_
  background:white;_x000D_
  border:1px solid #ccc;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
.select-sim::after {_x000D_
  content:"?";_x000D_
  font-size:0.5em;_x000D_
  font-family:arial;_x000D_
  position:absolute;_x000D_
  top:50%;_x000D_
  right:5px;_x000D_
  transform:translate(0, -50%);_x000D_
}_x000D_
_x000D_
.select-sim:hover::after {_x000D_
  content:"";_x000D_
}_x000D_
_x000D_
.select-sim:hover {_x000D_
  overflow:visible;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option label {_x000D_
  display:inline-block;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options {_x000D_
  background:white;_x000D_
  border:1px solid #ccc;_x000D_
  position:absolute;_x000D_
  top:-1px;_x000D_
  left:-1px;_x000D_
  width:100%;_x000D_
  height:88px;_x000D_
  overflow-y:scroll;_x000D_
}_x000D_
_x000D_
.select-sim .options .option {_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option {_x000D_
  height:22px;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
.select-sim .options .option img {_x000D_
  vertical-align:middle;_x000D_
}_x000D_
_x000D_
.select-sim .options .option label {_x000D_
  display:none;_x000D_
}_x000D_
_x000D_
.select-sim .options .option input {_x000D_
  width:0;_x000D_
  height:0;_x000D_
  overflow:hidden;_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  float:left;_x000D_
  display:inline-block;_x000D_
  /* fix specific for Firefox */_x000D_
  position: absolute;_x000D_
  left: -10000px;_x000D_
}_x000D_
_x000D_
.select-sim .options .option input:checked + label {_x000D_
  display:block;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option input + label {_x000D_
  display:block;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option input:checked + label {_x000D_
  background:#fffff0;_x000D_
}
_x000D_
<div class="select-sim" id="select-color">_x000D_
  <div class="options">_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="" id="color-" checked />_x000D_
      <label for="color-">_x000D_
        <img src="http://placehold.it/22/ffffff/ffffff" alt="" /> Select an option_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="red" id="color-red" />_x000D_
      <label for="color-red">_x000D_
        <img src="http://placehold.it/22/ff0000/ffffff" alt="" /> Red_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="green" id="color-green" />_x000D_
      <label for="color-green">_x000D_
        <img src="http://placehold.it/22/00ff00/ffffff" alt="" /> Green_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="blue" id="color-blue" />_x000D_
      <label for="color-blue">_x000D_
        <img src="http://placehold.it/22/0000ff/ffffff" alt="" /> Blue_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="yellow" id="color-yellow" />_x000D_
      <label for="color-yellow">_x000D_
        <img src="http://placehold.it/22/ffff00/ffffff" alt="" /> Yellow_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="pink" id="color-pink" />_x000D_
      <label for="color-pink">_x000D_
        <img src="http://placehold.it/22/ff00ff/ffffff" alt="" /> Pink_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="turquoise" id="color-turquoise" />_x000D_
      <label for="color-turquoise">_x000D_
        <img src="http://placehold.it/22/00ffff/ffffff" alt="" /> Turquoise_x000D_
      </label>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why can't C# interfaces contain fields?

Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-properties

interface IEmployee
{
    string Name
    {
        get;
        set;
    }

    int Counter
    {
        get;
    }
}

public class Employee : IEmployee
{
    public static int numberOfEmployees;

    private string _name;
    public string Name  // read-write instance property
    {
        get => _name;
        set => _name = value;
    }

    private int _counter;
    public int Counter  // read-only instance property
    {
        get => _counter;
    }

    // constructor
    public Employee() => _counter = ++numberOfEmployees;
}

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

How can I read command line parameters from an R script?

Try library(getopt) ... if you want things to be nicer. For example:

spec <- matrix(c(
        'in'     , 'i', 1, "character", "file from fastq-stats -x (required)",
        'gc'     , 'g', 1, "character", "input gc content file (optional)",
        'out'    , 'o', 1, "character", "output filename (optional)",
        'help'   , 'h', 0, "logical",   "this help"
),ncol=5,byrow=T)

opt = getopt(spec);

if (!is.null(opt$help) || is.null(opt$in)) {
    cat(paste(getopt(spec, usage=T),"\n"));
    q();
}

How can I go back/route-back on vue-router?

You can use Programmatic Navigation.In order to go back, you use this:

router.go(n) 

Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:

<a @click="$router.go(-1)">back</a>

How do I perform HTML decoding/encoding using Python/Django?

For html encoding, there's cgi.escape from the standard library:

>> help(cgi.escape)
cgi.escape = escape(s, quote=None)
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
    is also translated.

For html decoding, I use the following:

import re
from htmlentitydefs import name2codepoint
# for some reason, python 2.5.2 doesn't have this one (apostrophe)
name2codepoint['#39'] = 39

def unescape(s):
    "unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml"
    return re.sub('&(%s);' % '|'.join(name2codepoint),
              lambda m: unichr(name2codepoint[m.group(1)]), s)

For anything more complicated, I use BeautifulSoup.

Missing Maven dependencies in Eclipse project

My answer is similar to that of @JerylCook: find another .classpath file in a working Maven project, edit your bad ones as that good working ones. The key is to add

<attributes>
    <attribute name="maven.pomderived" value="true"/>
</attributes>

in every <classpathentry> of type con and src. Don't forget to change <classpathentry .... /> to <classpathentry ...>xxx</classpathentry>.

At last, update the maven project and reinstall/rebuild in maven.

Why use 'virtual' for class properties in Entity Framework model definitions?

It allows the Entity Framework to create a proxy around the virtual property so that the property can support lazy loading and more efficient change tracking. See What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First? for a more thorough discussion.

Edit to clarify "create a proxy around": By "create a proxy around" I'm referring specifically to what the Entity Framework does. The Entity Framework requires your navigation properties to be marked as virtual so that lazy loading and efficient change tracking are supported. See Requirements for Creating POCO Proxies.
The Entity Framework uses inheritance to support this functionality, which is why it requires certain properties to be marked virtual in your base class POCOs. It literally creates new types that derive from your POCO types. So your POCO is acting as a base type for the Entity Framework's dynamically created subclasses. That's what I meant by "create a proxy around".

The dynamically created subclasses that the Entity Framework creates become apparent when using the Entity Framework at runtime, not at static compilation time. And only if you enable the Entity Framework's lazy loading or change tracking features. If you opt to never use the lazy loading or change tracking features of the Entity Framework (which is not the default) then you needn't declare any of your navigation properties as virtual. You are then responsible for loading those navigation properties yourself, either using what the Entity Framework refers to as "eager loading", or manually retrieving related types across multiple database queries. You can and should use lazy loading and change tracking features for your navigation properties in many scenarios though.

If you were to create a standalone class and mark properties as virtual, and simply construct and use instances of those classes in your own application, completely outside of the scope of the Entity Framework, then your virtual properties wouldn't gain you anything on their own.

Edit to describe why properties would be marked as virtual

Properties such as:

 public ICollection<RSVP> RSVPs { get; set; }

Are not fields and should not be thought of as such. These are called getters and setters and at compilation time, they are converted into methods.

//Internally the code looks more like this:
public ICollection<RSVP> get_RSVPs()
{
    return _RSVPs;
}

public void set_RSVPs(RSVP value)
{
    _RSVPs = value;
}

private RSVP _RSVPs;

That's why they're marked as virtual for use in the Entity Framework, it allows the dynamically created classes to override the internally generated get and set functions. If your navigation property getter/setters are working for you in your Entity Framework usage, try revising them to just properties, recompile, and see if the Entity Framework is able to still function properly:

 public virtual ICollection<RSVP> RSVPs;

How do I enable TODO/FIXME/XXX task tags in Eclipse?

All those settings are necessary to choose which tags you are interested in, but in order to display these tags in a list, you also need to select the right Eclipse perspective. I finally discovered that the "Markers" tab containing the "Task" list is only available under the "Java EE" perspective... Hope this helps! :-)

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

I faced this error becouse I sent the Query string with wrong format

http://localhost:56110/user/updateuserinfo?Id=55?Name=Basheer&Phone=(111)%20111-1111
------------------------------------------^----(^)-----------^---...
--------------------------------------------must be &

so make sure your Query String or passed parameter in the right format

JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown

this is my code sample. I have comma separated numbers for multi select drop down and want to select options multiple options from comma separated values.

var selected_tags_arr = new Array();
var selected_tags = 1,2,4;
selected_tags_arr = selected_tags.split(",");
$('#contact_tags option').each(function (){
    var option_val = this.value;
    for (var i in selected_tags_arr) {
        if(selected_tags_arr[i] == option_val){
            $("#contact_tags option[value='" + this.value + "']").attr("selected", 1);
        }
    }
});

Remove/ truncate leading zeros by javascript/jquery

Try this,

   function ltrim(str, chars) {
        chars = chars || "\\s";
        return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    }

    var str =ltrim("01545878","0");

More here

How to show text in combobox when no item selected?

I was hoping to find a solution to this as well. I see that this is an older post, but hoping my approach might simplify this problem for someone else.

I was using a combobox with a drop down style of DropDownList, but this should work with other styles. In my case I wanted the text to read "Select Source" and I wanted the other options to be "File" and "Folder"

comboBox1.Items.AddRange(new string[] {"Select Source", "File", "Folder" });
comboBox1.Text = "Select Source";

You can select the 0 index instead if you like. I then removed the "Select Source" item when the index is changed as it no longer matters if that text is visible.

comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_IndexChanged);

private void comboBox1_IndexChanged(object sender, EventArgs e)
    {
        comboBox1.Items.Remove("Select Source");
        if (comboBox1.SelectedIndex != -1)
        {
            if (comboBox1.SelectedIndex == 0) // File
            {
                // Do things
            }
            else if (comboBox1.SelectedIndex == 1) // Folder
            {
                // Do things
            }
        }
    }

Thanks

How to set password for Redis?

you can also use following command on client

cmd :: config set requirepass p@ss$12E45

above command will set p@ss$12E45 as a redis server password.

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

I know this is an old question, and most people have replied with good answers. But for reference and hopefully saving somebody else's time. Check if your function:

$(document).ready(function(){}

is being called after you have loaded the JQuery library

Equivalent of "continue" in Ruby

next

also, look at redo which redoes the current iteration.

iOS 7 status bar back to iOS 6 default style in iPhone app?

Here another approach for projects that make extensive use of the Storyboard:

GOAL:

Goal of this approach is to recreate the same status bar style in iOS7 as there was in iOS6 (see question title "iOS 7 Status Bar Back to iOS 6 style?").

SUMMARY:

To achieve this we use the Storyboard as much as possible by shifting UI elements that are overlapped by the status bar (under iOS 7) downwards, whilst using deltas to revert the downwards layout change for iOS 6.1 or earlier. The resulting extra space in iOS 7 is then occupied by a UIView with the backgroundColor set to a color of our choosing. The latter can be created in code or using the Storyboard (see ALTERNATIVES below)

ASSUMPTIONS:

To get the desired result when following the steps below, it is assumed that View controller-based status bar appearance is set to NO and that your Status bar style is either set to "Transparent black style (alpha of 0.5)" or "Opaque black style". Both settings can be found/or added under "Info" in your project settings.

STEPS:

  • Add a subview to the UIWindow to serve as your status bar background. To achieve this, add the following to your AppDelegate's application: didFinishLaunchingWithOptions: after makeKeyAndVisible

    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        UIView *statusBarBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, yourAppsUIWindow.frame.size.width, 20)];
        statusBarBackgroundView.backgroundColor = [UIColor blackColor];
        [yourAppsUIWindow addSubview:statusBarBackgroundView];
    }
    
  • Since you programmatically added a background for iOS 7 ONLY, you will have to adjust the layout of your UI elements that are overlapped by the status bar accordingly whilst preserving their layout for iOS6. To achieve this, do the following:

    • Ensure that Use Autolayout is unchecked for your Storyboard (this is because otherwise "iOS 6/7 Deltas" is not shown in the Size Inspector). To do this:
      • select your Storyboard file
      • show Utilities
      • select "Show the File Inspector"
      • Under "Interface Builder Document" uncheck "Use Autolayout"
    • Optionally, to help you monitor the layout changes for both iOS 7 AND 6 as you apply them, select the "Assistant Editor", select "Preview" and "iOS 6.1 or earlier": enter image description here enter image description here
    • Now select the UI element you want to adjust so it isn't overlapped by the status bar anymore
    • Select "Show the Size Inspector" in the Utilities column
    • Reposition your UI element along the Y-axis by the same amount as the statusbar bg height: enter image description here
    • And change the iOS6/7 Deltas value for Y by the same NEGATIVE amount as the statusbar bg height (Note the change in the iOS 6 preview if you're using it): enter image description here

ALTERNATIVES:

To add even less code in storyboard-heavy projects and to have the statusbar background autorotate, instead of programmatically adding a background for your statusbar, you could add a colored view to each view controller that sits at the very top of said viewcontroller's main view. You would then change the height delta of this new view to the same negative amount as your view's height (to make it disappear under iOS 6).

The downside of this alternative (although maybe negligible considering the autorotate compatibility) is the fact that this extra view is not immediately visible if you are viewing your Storyboard for iOS 6. You would only know that it's there if you had a look at the "Document Outline" of the Storyboard.

Downloading a large file using curl

<?php
set_time_limit(0);
//This is the file where we save the    information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch); 
curl_close($ch);
fclose($fp);
?>

How to stop a PowerShell script on the first error?

$ErrorActionPreference = "Stop" will get you part of the way there (i.e. this works great for cmdlets).

However for EXEs you're going to need to check $LastExitCode yourself after every exe invocation and determine whether that failed or not. Unfortunately I don't think PowerShell can help here because on Windows, EXEs aren't terribly consistent on what constitutes a "success" or "failure" exit code. Most follow the UNIX standard of 0 indicating success but not all do. Check out the CheckLastExitCode function in this blog post. You might find it useful.

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

JUnit Testing private variables?

If you create your test classes in a seperate folder which you then add to your build path,

Then you could make the test class an inner class of the class under test by using package correctly to set the namespace. This gives it access to private fields and methods.

But dont forget to remove the folder from the build path for your release build.

How to close IPython Notebook properly?

If you run jupyter in the background like me:

jupyter notebook &> /dev/null &

Then to exit jupyter completely, instead of Ctl-C, make an alias command:

echo 'alias quitjupyter="kill $(pgrep jupyter)"' >> ~/.bashrc

Restart your terminal. Kill all jupyter instances:

quitjupyter

Note: use double quotes inside of single quotes as shown above. The other way around will evaluate the expression before writing it to your .bashrc (you want to write the command itself not 'kill 1430' or whatever process number may be associated with a current jupyter instance). Of course you can use any alias you wish. I actually use 'qjup':

echo 'alias qjup="kill $(pgrep jupyter)"' >> ~/.bashrc

Restart your terminal. Kill all jupyter instances:

qjup

How to do a deep comparison between 2 objects with lodash?

var isEqual = function(f,s) {
  if (f === s) return true;

  if (Array.isArray(f)&&Array.isArray(s)) {
    return isEqual(f.sort(), s.sort());
  }
  if (_.isObject(f)) {
    return isEqual(f, s);
  }
  return _.isEqual(f, s);
};

From inside of a Docker container, how do I connect to the localhost of the machine?

For those on Windows, assuming you're using the bridge network driver, you'll want to specifically bind MySQL to the ip address of the hyper-v network interface.

This is done via the configuration file under the normally hidden C:\ProgramData\MySQL folder.

Binding to 0.0.0.0 will not work. The address needed is shown in the docker configuration as well, and in my case was 10.0.75.1.

merge two object arrays with Angular 2 and TypeScript?

With angular 6 spread operator and concat not work. You can resolve it easy:

result.push(...data);

How to use double or single brackets, parentheses, curly braces

In Bash, test and [ are shell builtins.

The double bracket, which is a shell keyword, enables additional functionality. For example, you can use && and || instead of -a and -o and there's a regular expression matching operator =~.

Also, in a simple test, double square brackets seem to evaluate quite a lot quicker than single ones.

$ time for ((i=0; i<10000000; i++)); do [[ "$i" = 1000 ]]; done

real    0m24.548s
user    0m24.337s
sys 0m0.036s
$ time for ((i=0; i<10000000; i++)); do [ "$i" = 1000 ]; done

real    0m33.478s
user    0m33.478s
sys 0m0.000s

The braces, in addition to delimiting a variable name are used for parameter expansion so you can do things like:

  • Truncate the contents of a variable

    $ var="abcde"; echo ${var%d*}
    abc
    
  • Make substitutions similar to sed

    $ var="abcde"; echo ${var/de/12}
    abc12
    
  • Use a default value

    $ default="hello"; unset var; echo ${var:-$default}
    hello
    
  • and several more

Also, brace expansions create lists of strings which are typically iterated over in loops:

$ echo f{oo,ee,a}d
food feed fad

$ mv error.log{,.OLD}
(error.log is renamed to error.log.OLD because the brace expression
expands to "mv error.log error.log.OLD")

$ for num in {000..2}; do echo "$num"; done
000
001
002

$ echo {00..8..2}
00 02 04 06 08

$ echo {D..T..4}
D H L P T

Note that the leading zero and increment features weren't available before Bash 4.

Thanks to gboffi for reminding me about brace expansions.

Double parentheses are used for arithmetic operations:

((a++))

((meaning = 42))

for ((i=0; i<10; i++))

echo $((a + b + (14 * c)))

and they enable you to omit the dollar signs on integer and array variables and include spaces around operators for readability.

Single brackets are also used for array indices:

array[4]="hello"

element=${array[index]}

Curly brace are required for (most/all?) array references on the right hand side.

ephemient's comment reminded me that parentheses are also used for subshells. And that they are used to create arrays.

array=(1 2 3)
echo ${array[1]}
2

How to change JDK version for an Eclipse project

Click on the Add Library button. It brings your screen to point to the Java location.

Select "Directory", button right besides JRE home and point to the installed folder location.

Even though you want to just 1.5 compiler project, you can achieve it by changing compiler settings in Eclipse instead of removing 1.6 JRE and add 1.5 JRE.

GOTO -->JAVA--Compiler---> and change compiler level to `1.5` instead of `1.6`

As davidfmatheson suggested,

Just be careful, especially if you're setting this up for a team of people to work on. If anyone uses anything that is new or changed in 1.6, it will compile, but not run in an environment with JRE 1.5.

How to center horizontally div inside parent div

<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>

How to convert a ruby hash object to JSON?

You can also use JSON.generate:

require 'json'

JSON.generate({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

Or its alias, JSON.unparse:

require 'json'

JSON.unparse({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

if (navigator.geolocation) { //Checks if browser supports geolocation
navigator.geolocation.getCurrentPosition(function (position) {                                                                                            
 var latitude = position.coords.latitude;                    //users current
 var longitude = position.coords.longitude;                 //location
 var coords = new google.maps.LatLng(latitude, longitude); //Creates variable for map coordinates
 var directionsService = new google.maps.DirectionsService();
 var directionsDisplay = new google.maps.DirectionsRenderer();
 var mapOptions = //Sets map options
 {
   zoom: 15,  //Sets zoom level (0-21)
   center: coords, //zoom in on users location
   mapTypeControl: true, //allows you to select map type eg. map or satellite
   navigationControlOptions:
   {
     style: google.maps.NavigationControlStyle.SMALL //sets map controls size eg. zoom
   },
   mapTypeId: google.maps.MapTypeId.ROADMAP //sets type of map Options:ROADMAP, SATELLITE, HYBRID, TERRIAN
 };
 map = new google.maps.Map( /*creates Map variable*/ document.getElementById("map"),    mapOptions /*Creates a new map using the passed optional parameters in the mapOptions parameter.*/);
 directionsDisplay.setMap(map);
 directionsDisplay.setPanel(document.getElementById('panel'));
 var request = {
   origin: coords,
   destination: 'BT42 1FL',
   travelMode: google.maps.DirectionsTravelMode.DRIVING
 };

 directionsService.route(request, function (response, status) {
   if (status == google.maps.DirectionsStatus.OK) {
     directionsDisplay.setDirections(response);
   }
 });
 });
 }

Cannot access a disposed object - How to fix?

we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.

If I understand that stack trace, it's not your timer which is the problem, it's one in the control itself - it might be them who are not cleaning-up properly.

Are you explicitly calling Dispose on their control?

Is there a way to access the "previous row" value in a SELECT statement?

LEFT JOIN the table to itself, with the join condition worked out so the row matched in the joined version of the table is one row previous, for your particular definition of "previous".

Update: At first I was thinking you would want to keep all rows, with NULLs for the condition where there was no previous row. Reading it again you just want that rows culled, so you should an inner join rather than a left join.


Update:

Newer versions of Sql Server also have the LAG and LEAD Windowing functions that can be used for this, too.

How to do Base64 encoding in node.js?

You can do base64 encoding and decoding with simple javascript.

    $("input").keyup(function () {
     var value = $(this).val(),
         hash = Base64.encode(value);
     $(".test").html(hash);

     var decode = Base64.decode(hash);

     $(".decode").html(decode);
 });

var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"</script></div>

This is implemented in this Base64 encoder decoder

Difference between InvariantCulture and Ordinal string comparison

Pointing to Best Practices for Using Strings in the .NET Framework:

  • Use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.
  • Use comparisons with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for better performance.
  • Use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase values instead of string operations based on CultureInfo.InvariantCulture when the comparison is linguistically irrelevant (symbolic, for example).

And finally:

  • Do not use string operations based on StringComparison.InvariantCulture in most cases. One of the few exceptions is when you are persisting linguistically meaningful but culturally agnostic data.

I have never set any passwords to my keystore and alias, so how are they created?

if you want to configure them in gradle it should look like

signingConfigs {
        debug {
            storeFile file('PATH_TO_HOME/.android/debug.keystore')
            storePassword 'android'                   
            keyAlias 'AndroidDebugKey'
            keyPassword 'android'                     
        }
        ...
}

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

This worked for me.

<table>
  <tr>
    <td *ngFor="#group of groups">
       <h1>{{group.name}}</h1>
   </td>
  </tr>
</table>

jQuery.post( ) .done( ) and success:

The reason to prefer Promises over callback functions is to have multiple callbacks and to avoid the problems like Callback Hell.

Callback hell (for more details, refer http://callbackhell.com/): Asynchronous javascript, or javascript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:

asyncCall(function(err, data1){
    if(err) return callback(err);       
    anotherAsyncCall(function(err2, data2){
        if(err2) return calllback(err2);
        oneMoreAsyncCall(function(err3, data3){
            if(err3) return callback(err3);
            // are we done yet?
        });
    });
});

With Promises above code can be rewritten as below:

asyncCall()
.then(function(data1){
    // do something...
    return anotherAsyncCall();
})
.then(function(data2){
    // do something...  
    return oneMoreAsyncCall();    
})
.then(function(data3){
    // the third and final async response
})
.fail(function(err) {
    // handle any error resulting from any of the above calls    
})
.done();

How to create JSON string in JavaScript?

Use JSON.stringify:

> JSON.stringify({ asd: 'bla' });
'{"asd":"bla"}'

Track a new remote branch created on GitHub

git fetch
git branch --track branch-name origin/branch-name

First command makes sure you have remote branch in local repository. Second command creates local branch which tracks remote branch. It assumes that your remote name is origin and branch name is branch-name.

--track option is enabled by default for remote branches and you can omit it.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

It is a RAM related issue. The documentation is self explanatory:

You are trying to allocate >3GB of RAM to the VM. This requires: (a) a 64 bit host system; and (b) true hardware pass-through ie VT-x.

Fast solution

Allocate less than 3GB for the virtual machine.

Complete solution

  1. Make sure your system is 64 bit.
  2. Enable virtualisation in your host machine. You can find how to do it here or there are many other resources available on Google.

How do I base64 encode (decode) in C?

In case people need a c++ solution, I put this OpenSSL solution together (for both encode and decode). You'll need to link with the "crypto" library (which is OpenSSL). This has been checked for leaks with valgrind (although you could add some additional error checking code to make it a bit better - I know at least the write function should check for return value).

#include <openssl/bio.h>
#include <openssl/evp.h>
#include <stdlib.h>

string base64_encode( const string &str ){

    BIO *base64_filter = BIO_new( BIO_f_base64() );
    BIO_set_flags( base64_filter, BIO_FLAGS_BASE64_NO_NL );

    BIO *bio = BIO_new( BIO_s_mem() );
    BIO_set_flags( bio, BIO_FLAGS_BASE64_NO_NL );

    bio = BIO_push( base64_filter, bio );

    BIO_write( bio, str.c_str(), str.length() );

    BIO_flush( bio );

    char *new_data;

    long bytes_written = BIO_get_mem_data( bio, &new_data );

    string result( new_data, bytes_written );
    BIO_free_all( bio );

    return result;

}



string base64_decode( const string &str ){

    BIO *bio, *base64_filter, *bio_out;
    char inbuf[512];
    int inlen;
    base64_filter = BIO_new( BIO_f_base64() );
    BIO_set_flags( base64_filter, BIO_FLAGS_BASE64_NO_NL );

    bio = BIO_new_mem_buf( (void*)str.c_str(), str.length() );

    bio = BIO_push( base64_filter, bio );

    bio_out = BIO_new( BIO_s_mem() );

    while( (inlen = BIO_read(bio, inbuf, 512)) > 0 ){
        BIO_write( bio_out, inbuf, inlen );
    }

    BIO_flush( bio_out );

    char *new_data;
    long bytes_written = BIO_get_mem_data( bio_out, &new_data );

    string result( new_data, bytes_written );

    BIO_free_all( bio );
    BIO_free_all( bio_out );

    return result;

}

IllegalMonitorStateException on wait() call

wait is defined in Object, and not it Thread. The monitor on Thread is a little unpredictable.

Although all Java objects have monitors, it is generally better to have a dedicated lock:

private final Object lock = new Object();

You can get slightly easier to read diagnostics, at a small memory cost (about 2K per process) by using a named class:

private static final class Lock { }
private final Object lock = new Lock();

In order to wait or notify/notifyAll an object, you need to be holding the lock with the synchronized statement. Also, you will need a while loop to check for the wakeup condition (find a good text on threading to explain why).

synchronized (lock) {
    while (!isWakeupNeeded()) {
        lock.wait();
    }
}

To notify:

synchronized (lock) {
    makeWakeupNeeded();
    lock.notifyAll();
}

It is well worth getting to understand both Java language and java.util.concurrent.locks locks (and java.util.concurrent.atomic) when getting into multithreading. But use java.util.concurrent data structures whenever you can.

Why is Android Studio reporting "URI is not registered"?

  • Go to "Preferences > Languages&Frameworks > Schemas and DTDS"
  • Click "add(+)"
  • Click "apply" and then "ok"

hope it will works.

What is "git remote add ..." and "git push origin master"?

Git remote add origin:

It centralises your source code to the other projects.It is developed based on Linux, complete open source and make your code useful to the other git users.we call it as reference

Pushes your code into git repository using remote url of the git hub.

What is the C# version of VB.net's InputDialog?

To sum it up:

  • There is none in C#.
  • You can use the dialog from Visual Basic by adding a reference to Microsoft.VisualBasic:

    1. In Solution Explorer right-click on the References folder.
    2. Select Add Reference...
    3. In the .NET tab (in newer Visual Studio verions - Assembly tab) - select Microsoft.VisualBasic
    4. Click on OK

Then you can use the previously mentioned code:

string input = Microsoft.VisualBasic.Interaction.InputBox("Prompt", "Title", "Default", 0, 0);

That said, I suggest that you consider the need of an input box in the first place. Dialogs are not always the best way to do things and sometimes they do more harm than good - but that depends on the particular situation.

Conditional Replace Pandas

np.where function works as follows:

df['X'] = np.where(df['Y']>=50, 'yes', 'no')

In your case you would want:

import numpy as np
df['my_channel'] = np.where(df.my_channel > 20000, 0, df.my_channel)

How to download source in ZIP format from GitHub?

To clone that repository via a URL like that: yes, you do need a client, and that client is Git. That will let you make changes, your own branches, merge back in sync with other developers, maintain your own source that you can easily keep up to date without downloading the whole thing each time and writing over your own changes etc. A ZIP file won't let you do that.

It is mostly meant for people who want to develop the source rather than people who just want to get the source one off and not make changes.

But it just so happens you can get a ZIP file as well:

Click on http://github.com/zoul/Finch/ and then click on the green Clone or Download button. See here:

enter image description here

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

Use the getColor(Resources, int, Theme) method of the ResourcesCompat from the Android Support Library.

int white = ResourcesCompat.getColor(getResources(), R.color.white, null);

I think it reflect better your question than the getColor(Context, int) of the ContextCompat since you ask about Resources. Prior to API level 23, the theme will not be applied and the method calls through to getColor(int) but you'll not have the deprecated warning. The theme also may be null.

Android: How to handle right to left swipe gestures

If you want to display some buttons with actions when an list item is swipe are a lot of libraries on the internet that have this behavior. I implemented the library that I found on the internet and I am very satisfied. It is very simple to use and very quick. I improved the original library and I added a new click listener for item click. Also I added font awesome library (http://fortawesome.github.io/Font-Awesome/) and now you can simply add a new item title and specify the icon name from font awesome.

Here is the github link

Changing the CommandTimeout in SQL Management studio

If you are getting a timeout while on the table designer, change the "Transaction time-out after" value under Tools --> Options --> Designers --> Table and Database Designers

This will get rid of this message: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."

enter image description here

How to check if directory exists in %PATH%?

A comment to the "addPath" script; When supplying a path with spaces, it throws up.

Example: call addPath "c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin"

yields: 'Files' is not recognized as an internal or external command, operable program or batch file.

How do I get the command-line for an Eclipse run configuration?

Scan your workspace .metadata directory for files called *.launch. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core one.

Bash script to calculate time elapsed

start=$(date +%Y%m%d%H%M%S);
for x in {1..5};
do echo $x;
sleep 1; done;
end=$(date +%Y%m%d%H%M%S);
elapsed=$(($end-$start));
ftime=$(for((i=1;i<=$((${#end}-${#elapsed}));i++));
        do echo -n "-";
        done;
        echo ${elapsed});
echo -e "Start  : ${start}\nStop   : ${end}\nElapsed: ${ftime}"

Start  : 20171108005304
Stop   : 20171108005310
Elapsed: -------------6

Android: how to make keyboard enter button say "Search" and handle its click?

This answer is for TextInputEditText :

In the layout XML file set your input method options to your required type. for example done.

<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="actionGo"/>

</com.google.android.material.textfield.TextInputLayout>

Similarly, you can also set imeOptions to actionSubmit, actionSearch, etc

In the java add the editor action listener.

TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);

textInputLayout.getEditText().setOnEditorActionListener(new 

    TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                performYourAction();
                return true;
            }
            return false;
        }
    });

If you're using kotlin :

textInputLayout.editText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_GO) {
        performYourAction()
    }
    true
}

How to convert 2D float numpy array to 2D int numpy array?

Use the astype method.

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> x.astype(int)
array([[1, 2],
       [1, 2]])

What method in the String class returns only the first N characters?

Simply:

public static String Truncate(String input,int maxLength)
{
   if(input.Length > maxLength)
      return input.Substring(0,maxLength);
   return input;
}

Python convert tuple to string

Easiest way would be to use join like this:

>>> myTuple = ['h','e','l','l','o']
>>> ''.join(myTuple)
'hello'

This works because your delimiter is essentially nothing, not even a blank space: ''.

Pass a simple string from controller to a view MVC3

To pass a string to the view as the Model, you can do:

public ActionResult Index()
{
    string myString = "This is my string";
    return View((object)myString);
}

You must cast it to an object so that MVC doesn't try to load the string as the view name, but instead pass it as the model. You could also write:

return View("Index", myString);

.. which is a bit more verbose.

Then in your view, just type it as a string:

@model string

<p>Value: @Model</p>

Then you can manipulate Model how you want.

For accessing it from a Layout page, it might be better to create an HtmlExtension for this:

public static string GetThemePath(this HtmlHelper helper)
{
    return "/path-to-theme";
}

Then inside your layout page:

<p>Value: @Html.GetThemePath()</p>

Hopefully you can apply this to your own scenario.

Edit: explicit HtmlHelper code:

namespace <root app namespace>
{
    public static class Helpers
    {
        public static string GetThemePath(this HtmlHelper helper)
        {
            return System.Web.Hosting.HostingEnvironment.MapPath("~") + "/path-to-theme";
        }
    }
}

Then in your view:

@{
    var path = Html.GetThemePath();
    // .. do stuff
}

Or: <p>Path: @Html.GetThemePath()</p>

Edit 2:

As discussed, the Helper will work if you add a @using statement to the top of your view, with the namespace pointing to the one that your helper is in.

AngularJS : How to watch service variables?

In a scenario like this, where multiple/unkown objects might be interested in changes, use $rootScope.$broadcast from the item being changed.

Rather than creating your own registry of listeners (which have to be cleaned up on various $destroys), you should be able to $broadcast from the service in question.

You must still code the $on handlers in each listener but the pattern is decoupled from multiple calls to $digest and thus avoids the risk of long-running watchers.

This way, also, listeners can come and go from the DOM and/or different child scopes without the service changing its behavior.

** update: examples **

Broadcasts would make the most sense in "global" services that could impact countless other things in your app. A good example is a User service where there are a number of events that could take place such as login, logout, update, idle, etc. I believe this is where broadcasts make the most sense because any scope can listen for an event, without even injecting the service, and it doesn't need to evaluate any expressions or cache results to inspect for changes. It just fires and forgets (so make sure it's a fire-and-forget notification, not something that requires action)

.factory('UserService', [ '$rootScope', function($rootScope) {
   var service = <whatever you do for the object>

   service.save = function(data) {
     .. validate data and update model ..
     // notify listeners and provide the data that changed [optional]
     $rootScope.$broadcast('user:updated',data);
   }

   // alternatively, create a callback function and $broadcast from there if making an ajax call

   return service;
}]);

The service above would broadcast a message to every scope when the save() function completed and the data was valid. Alternatively, if it's a $resource or an ajax submission, move the broadcast call into the callback so it fires when the server has responded. Broadcasts suit that pattern particularly well because every listener just waits for the event without the need to inspect the scope on every single $digest. The listener would look like:

.controller('UserCtrl', [ 'UserService', '$scope', function(UserService, $scope) {

  var user = UserService.getUser();

  // if you don't want to expose the actual object in your scope you could expose just the values, or derive a value for your purposes
   $scope.name = user.firstname + ' ' +user.lastname;

   $scope.$on('user:updated', function(event,data) {
     // you could inspect the data to see if what you care about changed, or just update your own scope
     $scope.name = user.firstname + ' ' + user.lastname;
   });

   // different event names let you group your code and logic by what happened
   $scope.$on('user:logout', function(event,data) {
     .. do something differently entirely ..
   });

 }]);

One of the benefits of this is the elimination of multiple watches. If you were combining fields or deriving values like the example above, you'd have to watch both the firstname and lastname properties. Watching the getUser() function would only work if the user object was replaced on updates, it would not fire if the user object merely had its properties updated. In which case you'd have to do a deep watch and that is more intensive.

$broadcast sends the message from the scope it's called on down into any child scopes. So calling it from $rootScope will fire on every scope. If you were to $broadcast from your controller's scope, for example, it would fire only in the scopes that inherit from your controller scope. $emit goes the opposite direction and behaves similarly to a DOM event in that it bubbles up the scope chain.

Keep in mind that there are scenarios where $broadcast makes a lot of sense, and there are scenarios where $watch is a better option - especially if in an isolate scope with a very specific watch expression.

Controlling Spacing Between Table Cells

Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.

JSFiddle

Rails: Get Client IP address

For anyone interested and using a newer rails and the Devise gem: Devise's "trackable" option includes a column for current/last_sign_in_ip in the users table.

How do I test if a variable is a number in Bash?

  • variable to check

    number=12345 or number=-23234 or number=23.167 or number=-345.234

  • check numeric or non-numeric

    echo $number | grep -E '^-?[0-9]*\.?[0-9]*$' > /dev/null

  • decide on further actions based on the exit status of the above

    if [ $? -eq 0 ]; then echo "Numeric"; else echo "Non-Numeric"; fi

How do I specify the JDK for a GlassFish domain?

According to the GF Administration Guide:

For a valid JVM installation, locations are checked in the following order: a. domain.xml (java-home inside java-config) b. asenv.conf (setting AS_JAVA="path to java home")

I had to add both these settings to make it work. Otherwise 'asadmin stop-domain domain1' wouldn't work. I guess that GF uses a. and asadmin uses b.

(On Windows: b. asenv.bat)

psql: FATAL: Ident authentication failed for user "postgres"

I've spent more time solving this error that I care to admit.

The order of authentication configuration in pg_hba.conf is relevant in your case I think. The default configuration file includes several lines in a vanilla install. These defaults can match the conditions of your authentication attempts resulting in a failure to authenticate. It fails regardless of additional configuration added at the end of the .conf file.

To check which line of configuration is use make sure to look at the default log file for messages. You might see something like this

LOG:  could not connect to Ident server at address "127.0.0.1", port 113: Connection refused
FATAL:  Ident authentication failed for user "acme" 
DETAIL:  Connection matched pg_hba.conf line 82: "host     all             all             127.0.0.1/32            ident"

It turns out this default line is causing the rejection.

host    all             all             127.0.0.1/32            ident

try commenting it out.

How to view the dependency tree of a given npm module?

If you want to get the actually dependency path of specific package and want to know why you have it, you can simply ask yarn why <MODULE>. example:

    $> yarn why mime-db
    yarn why v1.5.1
    [1/4] Why do we have the module "mime-db"...?
    [2/4] Initialising dependency graph...
    [3/4] Finding dependency...
    [4/4] Calculating file sizes...
    => Found "[email protected]"
    info Reasons this module exists
       - "coveralls#request#mime-types" depends on it
       - Hoisted from "coveralls#request#mime-types#mime-db"
    info Disk size without dependencies: "196kB"
    info Disk size with unique dependencies: "196kB"
    info Disk size with transitive dependencies: "196kB"
    info Number of shared dependencies: 0
    Done in 0.65s.

Delete cookie by name?

I'm not really sure if that was the situation with Roundcube version from May '12, but for current one the answer is that you can't delete roundcube_sessauth cookie from JavaScript, as it is marked as HttpOnly. And this means it's not accessible from JS client side code and can be removed only by server side script or by direct user action (via some browser mechanics like integrated debugger or some plugin).

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

image processing to improve tesseract OCR accuracy

I did these to get good results out of an image which has not very small text.

  1. Apply blur to the original image.
  2. Apply Adaptive Threshold.
  3. Apply Sharpening effect.

And if the still not getting good results, scale the image to 150% or 200%.

Take multiple lists into dataframe

Just adding that using the first approach it can be done as -

pd.DataFrame(list(map(list, zip(lst1,lst2,lst3))))

How do I read all classes from a Java package in the classpath?

That functionality is still suspiciously missing from the Java reflection API as far as I know. You can get a package object by just doing this:

Package packageObj = Package.getPackage("my.package");

But as you probably noticed, that won't let you list the classes in that package. As of right now, you have to take sort of a more filesystem-oriented approach.

I found some sample implementations in this post

I'm not 100% sure these methods will work when your classes are buried in JAR files, but I hope one of those does it for you.

I agree with @skaffman...if you have another way of going about this, I'd recommend doing that instead.

How to convert string to XML using C#

string test = "<body><head>test header</head></body>";

XmlDocument xmltest = new XmlDocument();
xmltest.LoadXml(test);

XmlNodeList elemlist = xmltest.GetElementsByTagName("head");

string result = elemlist[0].InnerXml; 

//result -> "test header"

What is Vim recording and how can it be disabled?

It means you're in "record macro" mode. This mode is entered by typing q followed by a register name, and can be exited by typing q again.

Is it possible to use JavaScript to change the meta-tags of the page?

You can use more simpler and lighter solution:

document.head.querySelector('meta[name="description"]').content = _desc

Get current controller in view

Other way to get current Controller name in View

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

PHP - regex to allow letters and numbers only

1. Use PHP's inbuilt ctype_alnum

You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum which will do this for you, and execute faster:

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

2. Alternatively, use a regex

If you desperately want to use a regex, you have a few options.

Firstly:

preg_match('/^[\w]+$/', $string);

\w includes more than alphanumeric (it includes underscore), but includes all of \d.

Alternatively:

/^[a-zA-Z\d]+$/

Or even just:

/^[^\W_]+$/

Apache VirtualHost 403 Forbidden

If you did everything right, just give the permission home directory like:

sudo chmod o+x $HOME

then

sudo systemctl restart apache2

How do I pass multiple parameters into a function in PowerShell?

Function Test([string]$arg1, [string]$arg2)
{
    Write-Host "`$arg1 value: $arg1"
    Write-Host "`$arg2 value: $arg2"
}

Test "ABC" "DEF"

How to get docker-compose to always re-create containers from fresh images?

$docker-compose build

If there is something new it will be rebuilt.

How can I see the raw SQL queries Django is running?

Django-extensions have a command shell_plus with a parameter print-sql

./manage.py shell_plus --print-sql

In django-shell all executed queries will be printed

Ex.:

User.objects.get(pk=1)
SELECT "auth_user"."id",
       "auth_user"."password",
       "auth_user"."last_login",
       "auth_user"."is_superuser",
       "auth_user"."username",
       "auth_user"."first_name",
       "auth_user"."last_name",
       "auth_user"."email",
       "auth_user"."is_staff",
       "auth_user"."is_active",
       "auth_user"."date_joined"
FROM "auth_user"
WHERE "auth_user"."id" = 1

Execution time: 0.002466s [Database: default]

<User: username>

How do I find the length of an array?

Instead of using the built in array function aka:

 int x[3] = {0, 1, 2};

you should use the array class and the array template. Try:

#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};

So now if you want to find the length of the array, all you have to do is using the size function in the array class.

Name_of_Array.size();

and that should return the length of elements in the array.

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

For me the solution was to download the Android SDK and launch adb devices which started the adb daemon.

Restoring MySQL database from physical files

I once copied these files to the database storage folder for a mysql database which was working, started the db and waited for it to "repair" the files, then extracted them with mysqldump.

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

Or you can insert raw sql part to conditions so I have 'conditions'=>array('Member.id NOT IN (SELECT Membership.member_id FROM memberships AS Membership)')

In PHP, what is a closure and why does it use the "use" identifier?

Zupa did a great job explaining closures with 'use' and the difference between EarlyBinding and Referencing the variables that are 'used'.

So I made a code example with early binding of a variable (= copying):

<?php

$a = 1;
$b = 2;

$closureExampleEarlyBinding = function() use ($a, $b){
    $a++;
    $b++;
    echo "Inside \$closureExampleEarlyBinding() \$a = ".$a."<br />";
    echo "Inside \$closureExampleEarlyBinding() \$b = ".$b."<br />";    
};

echo "Before executing \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "Before executing \$closureExampleEarlyBinding() \$b = ".$b."<br />";  

$closureExampleEarlyBinding();

echo "After executing \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "After executing \$closureExampleEarlyBinding() \$b = ".$b."<br />";

/* this will output:
Before executing $closureExampleEarlyBinding() $a = 1
Before executing $closureExampleEarlyBinding() $b = 2
Inside $closureExampleEarlyBinding() $a = 2
Inside $closureExampleEarlyBinding() $b = 3
After executing $closureExampleEarlyBinding() $a = 1
After executing $closureExampleEarlyBinding() $b = 2
*/

?>

Example with referencing a variable (notice the '&' character before variable);

<?php

$a = 1;
$b = 2;

$closureExampleReferencing = function() use (&$a, &$b){
    $a++;
    $b++;
    echo "Inside \$closureExampleReferencing() \$a = ".$a."<br />";
    echo "Inside \$closureExampleReferencing() \$b = ".$b."<br />"; 
};

echo "Before executing \$closureExampleReferencing() \$a = ".$a."<br />";
echo "Before executing \$closureExampleReferencing() \$b = ".$b."<br />";   

$closureExampleReferencing();

echo "After executing \$closureExampleReferencing() \$a = ".$a."<br />";
echo "After executing \$closureExampleReferencing() \$b = ".$b."<br />";    

/* this will output:
Before executing $closureExampleReferencing() $a = 1
Before executing $closureExampleReferencing() $b = 2
Inside $closureExampleReferencing() $a = 2
Inside $closureExampleReferencing() $b = 3
After executing $closureExampleReferencing() $a = 2
After executing $closureExampleReferencing() $b = 3
*/

?>

Setting mime type for excel document

Waking up an old thread here I see, but I felt the urge to add the "new" .xlsx format.

According to http://filext.com/file-extension/XLSX the extension for .xlsx is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. It might be a good idea to include it when checking for mime types!

How do I remove time part from JavaScript date?

Split it by space and take first part like below. Hope this will help you.

var d = '12/12/1955 12:00:00 AM';
d = d.split(' ')[0];
console.log(d);

Setting Inheritance and Propagation flags with set-acl and powershell

Just because you're in PowerShell don't forgot about good ol' exes. Sometimes they can provide the easiest solution e.g.:

icacls.exe $folder /grant 'domain\user:(OI)(CI)(M)'

changing color of h2

Try CSS:

<h2 style="color:#069">Process Report</h2>

If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:

<style type="text/css">
h2 {
    color:#069;
}
</style>

How to empty a redis database?

tldr: flushdb clears one database and flushall clears all databases

Clear CURRENT

Delete default or currently selected database (usually `0) with

redis-cli flushdb

Clear SPECIFIC

Delete specific redis database with (e.g. 8 as my target database):

redis-cli -n 8 flushdb 

Clear ALL

Delete all redis databases with

redis-cli flushall

How to insert a string which contains an "&"

Stop using SQL/Plus, I highly recommend PL/SQL Developer it's much more than an SQL tool.

p.s. Some people prefer TOAD.

Android - Activity vs FragmentActivity?

If you use the Eclipse "New Android Project" wizard in a recent ADT bundle, you'll automatically get tabs implemented as a Fragments. This makes the conversion of your application to the tablet format much easier in the future.

For simple single screen layouts you may still use Activity.

Cygwin Make bash command not found

I faced the same problem too. Look up to the left side, and select (full). (Make), (gcc) and many others will appear. You will be able to chose the search bar to find them easily.

How to check if a string contains a substring in Bash

You should remember that shell scripting is less of a language and more of a collection of commands. Instinctively you think that this "language" requires you to follow an if with a [ or a [[. Both of those are just commands that return an exit status indicating success or failure (just like every other command). For that reason I'd use grep, and not the [ command.

Just do:

if grep -q foo <<<"$string"; then
    echo "It's there"
fi

Now that you are thinking of if as testing the exit status of the command that follows it (complete with semi-colon), why not reconsider the source of the string you are testing?

## Instead of this
filetype="$(file -b "$1")"
if grep -q "tar archive" <<<"$filetype"; then
#...

## Simply do this
if file -b "$1" | grep -q "tar archive"; then
#...

The -q option makes grep not output anything, as we only want the return code. <<< makes the shell expand the next word and use it as the input to the command, a one-line version of the << here document (I'm not sure whether this is standard or a Bashism).

How can I do DNS lookups in Python, including referring to /etc/hosts?

I found this way to expand a DNS RR hostname that expands into a list of IPs, into the list of member hostnames:

#!/usr/bin/python

def expand_dnsname(dnsname):
    from socket import getaddrinfo
    from dns import reversename, resolver
    namelist = [ ]
    # expand hostname into dict of ip addresses
    iplist = dict()
    for answer in getaddrinfo(dnsname, 80):
        ipa = str(answer[4][0])
        iplist[ipa] = 0
    # run through the list of IP addresses to get hostnames
    for ipaddr in sorted(iplist):
        rev_name = reversename.from_address(ipaddr)
        # run through all the hostnames returned, ignoring the dnsname
        for answer in resolver.query(rev_name, "PTR"):
            name = str(answer)
            if name != dnsname:
                # add it to the list of answers
                namelist.append(name)
                break
    # if no other choice, return the dnsname
    if len(namelist) == 0:
        namelist.append(dnsname)
    # return the sorted namelist
    namelist = sorted(namelist)
    return namelist

namelist = expand_dnsname('google.com.')
for name in namelist:
    print name

Which, when I run it, lists a few 1e100.net hostnames:

On Selenium WebDriver how to get Text from Span Tag

Your code should read -

String kk = wd.findElement(By.cssSelector("div[id^='customSelect'] span.selectLabel")).getText();

Use CSS. it's much cleaner and easier.. Let me know if that solves your issue.

Get webpage contents with Python?

Because you're using Python 3.1, you need to use the new Python 3.1 APIs.

Try:

urllib.request.urlopen('http://www.python.org/')

Alternately, it looks like you're working from Python 2 examples. Write it in Python 2, then use the 2to3 tool to convert it. On Windows, 2to3.py is in \python31\tools\scripts. Can someone else point out where to find 2to3.py on other platforms?

Edit

These days, I write Python 2 and 3 compatible code by using six.

from six.moves import urllib
urllib.request.urlopen('http://www.python.org')

Assuming you have six installed, that runs on both Python 2 and Python 3.

afxwin.h file is missing in VC++ Express Edition

I see the question is about Express Edition, but this topic is easy to pop up in Google Search, and doesn't have a solution for other editions.

So. If you run into this problem with any VS Edition except Express, you can rerun installation and include MFC files.

Best practices with STDIN in Ruby?

Something like this perhaps?

#/usr/bin/env ruby

if $stdin.tty?
  ARGV.each do |file|
    puts "do something with this file: #{file}"
  end
else
  $stdin.each_line do |line|
    puts "do something with this line: #{line}"
  end
end

Example:

> cat input.txt | ./myprog.rb
do something with this line: this
do something with this line: is
do something with this line: a
do something with this line: test
> ./myprog.rb < input.txt 
do something with this line: this
do something with this line: is
do something with this line: a
do something with this line: test
> ./myprog.rb arg1 arg2 arg3
do something with this file: arg1
do something with this file: arg2
do something with this file: arg3

how to sort an ArrayList in ascending order using Collections and Comparator

Sort By Value

  public Map sortByValue(Map map, final boolean ascending) {
            Map result = new LinkedHashMap();
            try {
                List list = new LinkedList(map.entrySet());

                Collections.sort(list, new Comparator() {
                    @Override
                    public int compare(Object object1, Object object2) {
                        if (ascending)
                            return ((Comparable) ((Map.Entry) (object1)).getValue())
                                    .compareTo(((Map.Entry) (object2)).getValue());
                        else
                            return ((Comparable) ((Map.Entry) (object2)).getValue())
                                    .compareTo(((Map.Entry) (object1)).getValue());

                    }
                });

                for (Iterator it = list.iterator(); it.hasNext();) {
                    Map.Entry entry = (Map.Entry) it.next();
                    result.put(entry.getKey(), entry.getValue());
                }

            } catch (Exception e) {
                Log.e("Error", e.getMessage());
            }

            return result;
        }

JFrame background image

I used a very similar method to @bott, but I modified it a little bit to make there be no need to resize the image:

BufferedImage img = null;
try {
    img = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}
Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));

Works every time. You can also get the width and height of the jFrame and use that in place of the 800 and 508 respectively.

With ng-bind-html-unsafe removed, how do I inject HTML?

You can use filter like this

angular.module('app').filter('trustAs', ['$sce', 
    function($sce) {
        return function (input, type) {
            if (typeof input === "string") {
                return $sce.trustAs(type || 'html', input);
            }
            console.log("trustAs filter. Error. input isn't a string");
            return "";
        };
    }
]);

usage

<div ng-bind-html="myData | trustAs"></div>

it can be used for other resource types, for example source link for iframes and other types declared here

What's the easy way to auto create non existing dir in ansible

AFAIK, the only way this could be done is by using the state=directory option. While template module supports most of copy options, which in turn supports most file options, you can not use something like state=directory with it. Moreover, it would be quite confusing (would it mean that {{project_root}}/conf/code.conf is a directory ? or would it mean that {{project_root}}/conf/ should be created first.

So I don't think this is possible right now without adding a previous file task.

- file: 
    path: "{{project_root}}/conf"
    state: directory
    recurse: yes

What is the best Java email address validation method?

What do you want to validate? The email address?

The email address can only be checked for its format conformance. See the standard: RFC2822. Best way to do that is a regular expression. You will never know if really exists without sending an email.

I checked the commons validator. It contains an org.apache.commons.validator.EmailValidator class. Seems to be a good starting point.

Angularjs checkbox checked by default on load and disables Select list when checked

You don't really need the directive, can achieve it by using the ng-init and ng-checked. below demo link shows how to set the initial value for checkbox in angularjs.

demo link:

<form>
    <div>
      Released<input type="checkbox" ng-model="Released" ng-bind-html="ACR.Released" ng-true-value="true" ng-false-value="false" ng-init='Released=true' ng-checked='true' /> 
      Inactivated<input type="checkbox" ng-model="Inactivated" ng-bind-html="Inactivated" ng-true-value="true" ng-false-value="false" ng-init='Inactivated=false' ng-checked='false' /> 
      Title Changed<input type="checkbox" ng-model="Title" ng-bind-html="Title" ng-true-value="true" ng-false-value="false" ng-init='Title=false' ng-checked='false' />
    </div>
    <br/>
    <div>Released value is  <b>{{Released}}</b></div>
    <br/>
    <div>Inactivated  value is  <b>{{Inactivated}}</b></div>
    <br/>
    <div>Title  value is  <b>{{Title}}</b></div>
    <br/>
  </form>

// Code goes here

  var app = angular.module("myApp", []);
        app.controller("myCtrl", function ($scope) {

         });    

Oracle: is there a tool to trace queries, like Profiler for sql server?

Seeing as I've just voted a recent question as a duplicate and pointed in this direction . . .

A couple more - in SQL*Plus - SET AUTOTRACE ON - will give explain plan and statistics for each statement executed.

TOAD also allows for client side profiling.

The disadvantage of both of these is that they only tell you the execution plan for the statement, but not how the optimiser arrived at that plan - for that you will need lower level server side tracing.

Another important one to understand is Statspack snapshots - they are a good way for looking at the performance of the database as a whole. Explain plan, etc, are good at finding individual SQL statements that are bottlenecks. Statspack is good at identifying the fact your problem is that a simple statement with a good execution plan is being called 1 million times in a minute.

month name to month number and vice versa in python

def month_num2abbr(month):
    month = int(month)
    import calendar
    months_abbr = {month: index for index, month in enumerate(calendar.month_abbr) if month}
    for abbr, month_num in months_abbr.items():
        if month_num==month:
            return abbr
    return False

print(month_num2abbr(7))

Tkinter scrollbar for frame

Please note that the proposed code is only valid with Python 2

Here is an example:

from Tkinter import *   # from x import * is bad practice
from ttk import *

# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!
    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling

    """
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)            

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)


if __name__ == "__main__":

    class SampleApp(Tk):
        def __init__(self, *args, **kwargs):
            root = Tk.__init__(self, *args, **kwargs)


            self.frame = VerticalScrolledFrame(root)
            self.frame.pack()
            self.label = Label(text="Shrink the window to activate the scrollbar.")
            self.label.pack()
            buttons = []
            for i in range(10):
                buttons.append(Button(self.frame.interior, text="Button " + str(i)))
                buttons[-1].pack()

    app = SampleApp()
    app.mainloop()

It does not yet have the mouse wheel bound to the scrollbar but it is possible. Scrolling with the wheel can get a bit bumpy, though.

edit:

to 1)
IMHO scrolling frames is somewhat tricky in Tkinter and does not seem to be done a lot. It seems there is no elegant way to do it.
One problem with your code is that you have to set the canvas size manually - that's what the example code I posted solves.

to 2)
You are talking about the data function? Place works for me, too. (In general I prefer grid).

to 3)
Well, it positions the window on the canvas.

One thing I noticed is that your example handles mouse wheel scrolling by default while the one I posted does not. Will have to look at that some time.

How to disable JavaScript in Chrome Developer Tools?

Official documentation: Disable JavaScript With Chrome DevTools

There's now a command menu built into DevTools that makes it easier to disable JavaScript. This has been around as of April 2016 or so.

  1. Open DevTools.
  2. Press Command+Shift+P (Mac) or Control+Shift+P (Windows, Linux) to open the Command Menu. Make sure that your cursor's focus is on the DevTools window, not your browser viewport.
  3. Type Disable JavaScript (or some version of that... it's a fuzzy search) and then press Enter.

Use the Enable JavaScript command when you want to turn it back on.

disabling js via command menu

How to enable Ad Hoc Distributed Queries

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO