Programs & Examples On #Svn reintegrate

0

Killing a process using Java

You can kill a (SIGTERM) a windows process that was started from Java by calling the destroy method on the Process object. You can also kill any child Processes (since Java 9).

The following code starts a batch file, waits for ten seconds then kills all sub-processes and finally kills the batch process itself.

ProcessBuilder pb = new ProcessBuilder("cmd /c my_script.bat"));
Process p = pb.start();
p.waitFor(10, TimeUnit.SECONDS);

p.descendants().forEach(ph -> {
    ph.destroy();
});

p.destroy();

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

TypeError: got multiple values for argument

This happens when a keyword argument is specified that overwrites a positional argument. For example, let's imagine a function that draws a colored box. The function selects the color to be used and delegates the drawing of the box to another function, relaying all extra arguments.

def color_box(color, *args, **kwargs):
    painter.select_color(color)
    painter.draw_box(*args, **kwargs)

Then the call

color_box("blellow", color="green", height=20, width=30)

will fail because two values are assigned to color: "blellow" as positional and "green" as keyword. (painter.draw_box is supposed to accept the height and width arguments).

This is easy to see in the example, but of course if one mixes up the arguments at call, it may not be easy to debug:

# misplaced height and width
color_box(20, 30, color="green")

Here, color is assigned 20, then args=[30] and color is again assigned "green".

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

how to add a day to a date using jquery datepicker

This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.


 $( "#date_start" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
         $("#date_end").datepicker("option","minDate", selected); //  mindate on the End datepicker cannot be less than start date already selected.
         var date = $(this).datepicker('getDate');
         var tempStartDate = new Date(date);
         var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
         $('#date_end').datepicker('setDate', default_end); // Set as default                           
   }

 });

 $( "#date_end" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
     $("#date_start").datepicker("option","maxDate", selected); //  maxdate on the Start datepicker cannot be more than end date selected.

  }

});

How to parse a CSV file using PHP

Handy one liner to parse a CSV file into an array

$csv = array_map('str_getcsv', file('data.csv'));

Why doesn't C++ have a garbage collector?

Stroustrup made some good comments on this at the 2013 Going Native conference.

Just skip to about 25m50s in this video. (I'd recommend watching the whole video actually, but this skips to the stuff about garbage collection.)

When you have a really great language that makes it easy (and safe, and predictable, and easy-to-read, and easy-to-teach) to deal with objects and values in a direct way, avoiding (explicit) use of the heap, then you don't even want garbage collection.

With modern C++, and the stuff we have in C++11, garbage collection is no longer desirable except in limited circumstances. In fact, even if a good garbage collector is built into one of the major C++ compilers, I think that it won't be used very often. It will be easier, not harder, to avoid the GC.

He shows this example:

void f(int n, int x) {
    Gadget *p = new Gadget{n};
    if(x<100) throw SomeException{};
    if(x<200) return;
    delete p;
}

This is unsafe in C++. But it's also unsafe in Java! In C++, if the function returns early, the delete will never be called. But if you had full garbage collection, such as in Java, you merely get a suggestion that the object will be destructed "at some point in the future" (Update: it's even worse that this. Java does not promise to call the finalizer ever - it maybe never be called). This isn't good enough if Gadget holds an open file handle, or a connection to a database, or data which you have buffered for write to a database at a later point. We want the Gadget to be destroyed as soon as it's finished, in order to free these resources as soon as possible. You don't want your database server struggling with thousands of database connections that are no longer needed - it doesn't know that your program is finished working.

So what's the solution? There are a few approaches. The obvious approach, which you'll use for the vast majority of your objects is:

void f(int n, int x) {
    Gadget p = {n};  // Just leave it on the stack (where it belongs!)
    if(x<100) throw SomeException{};
    if(x<200) return;
}

This takes fewer characters to type. It doesn't have new getting in the way. It doesn't require you to type Gadget twice. The object is destroyed at the end of the function. If this is what you want, this is very intuitive. Gadgets behave the same as int or double. Predictable, easy-to-read, easy-to-teach. Everything is a 'value'. Sometimes a big value, but values are easier to teach because you don't have this 'action at a distance' thing that you get with pointers (or references).

Most of the objects you make are for use only in the function that created them, and perhaps passed as inputs to child functions. The programmer shouldn't have to think about 'memory management' when returning objects, or otherwise sharing objects across widely separated parts of the software.

Scope and lifetime are important. Most of the time, it's easier if the lifetime is the same as the scope. It's easier to understand and easier to teach. When you want a different lifetime, it should be obvious reading the code that you're doing this, by use of shared_ptr for example. (Or returning (large) objects by value, leveraging move-semantics or unique_ptr.

This might seem like an efficiency problem. What if I want to return a Gadget from foo()? C++11's move semantics make it easier to return big objects. Just write Gadget foo() { ... } and it will just work, and work quickly. You don't need to mess with && yourself, just return things by value and the language will often be able to do the necessary optimizations. (Even before C++03, compilers did a remarkably good job at avoiding unnecessary copying.)

As Stroustrup said elsewhere in the video (paraphrasing): "Only a computer scientist would insist on copying an object, and then destroying the original. (audience laughs). Why not just move the object directly to the new location? This is what humans (not computer scientists) expect."

When you can guarantee only one copy of an object is needed, it's much easier to understand the lifetime of the object. You can pick what lifetime policy you want, and garbage collection is there if you want. But when you understand the benefits of the other approaches, you'll find that garbage collection is at the bottom of your list of preferences.

If that doesn't work for you, you can use unique_ptr, or failing that, shared_ptr. Well written C++11 is shorter, easier-to-read, and easier-to-teach than many other languages when it comes to memory management.

How to disable HTML links

You can use this to disabled the Hyperlink of asp.net or link buttons in html.

$("td > a").attr("disabled", "disabled").on("click", function() {
    return false; 
});

How to send a "multipart/form-data" with requests in python?

Since the previous answers were written, requests have changed. Have a look at the bug thread at Github for more detail and this comment for an example.

In short, the files parameter takes a dict with the key being the name of the form field and the value being either a string or a 2, 3 or 4-length tuple, as described in the section POST a Multipart-Encoded File in the requests quickstart:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

In the above, the tuple is composed as follows:

(filename, data, content_type, headers)

If the value is just a string, the filename will be the same as the key, as in the following:

>>> files = {'obvius_session_id': '72c2b6f406cdabd578c5fd7598557c52'}

Content-Disposition: form-data; name="obvius_session_id"; filename="obvius_session_id"
Content-Type: application/octet-stream

72c2b6f406cdabd578c5fd7598557c52

If the value is a tuple and the first entry is None the filename property will not be included:

>>> files = {'obvius_session_id': (None, '72c2b6f406cdabd578c5fd7598557c52')}

Content-Disposition: form-data; name="obvius_session_id"
Content-Type: application/octet-stream

72c2b6f406cdabd578c5fd7598557c52

What is the difference between required and ng-required?

I would like to make a addon for tiago's answer:

Suppose you're hiding element using ng-show and adding a required attribute on the same:

<div ng-show="false">
    <input required name="something" ng-model="name"/>
</div>

will throw an error something like :

An invalid form control with name='' is not focusable

This is because you just cannot impose required validation on hidden elements. Using ng-required makes it easier to conditionally apply required validation which is just awesome!!

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

Add a reference to 'Microsoft.VisualStudio.QualityTools.UnitTestFramework" NuGet packet and it should successfully build it.

Git for beginners: The definitive practical guide

GUIs for git


Git GUI

Included with git — Run git gui from the command line, and the Windows msysgit installer adds it to the Start menu.

Git GUI can do a majority of what you'd need to do with git. Including stage changes, configure git and repositories, push changes, create/checkout/delete branches, merge, and many other things.

One of my favourite features is the "stage line" and "stage hunk" shortcuts in the right-click menu, which lets you commit specific parts of a file. You can achieve the same via git add -i, but I find it easier to use.

It isn't the prettiest application, but it works on almost all platforms (being based upon Tcl/Tk)

Screenshots | a screencast


GitK

Also included with git. It is a git history viewer, and lets you visualise a repository's history (including branches, when they are created, and merged). You can view and search commits.

Goes together nicely with git-gui.


Gitnub

Mac OS X application. Mainly an equivalent of git log, but has some integration with github (like the "Network view").

Looks pretty, and fits with Mac OS X. You can search repositories. The biggest critisism of Gitnub is that it shows history in a linear fashion (a single branch at a time) - it doesn't visualise branching and merging, which can be important with git, although this is a planned improvement.

Download links, change log and screenshots | git repository


GitX

Intends to be a "gitk clone for OS X".

It can visualise non-linear branching history, perform commits, view and search commits, and it has some other nice features like being able to "Quicklook" any file in any revision (press space in the file-list view), export any file (via drag and drop).

It is far better integrated into OS X than git-gui/gitk, and is fast and stable even with exceptionally large repositories.

The original git repository pieter has not updated recently (over a year at time of writing). A more actively maintained branch is available at brotherbard/gitx - it adds "sidebar, fetch, pull, push, add remote, merge, cherry-pick, rebase, clone, clone to"

Download | Screenshots | git repository | brotherbard fork | laullon fork


SmartGit

From the homepage:

SmartGit is a front-end for the distributed version control system Git and runs on Windows, Mac OS X and Linux. SmartGit is intended for developers who prefer a graphical user interface over a command line client, to be even more productive with Git — the most powerful DVCS today.

You can download it from their website.

Download


TortoiseGit

TortoiseSVN Git version for Windows users.

It is porting TortoiseSVN to TortoiseGit The latest release 1.2.1.0 This release can complete regular task, such commit, show log, diff two version, create branch and tag, Create patch and so on. See ReleaseNotes for detail. Welcome to contribute this project.

Download


QGit

QGit is a git GUI viewer built on Qt/C++.

With qgit you will be able to browse revisions history, view patch content and changed files, graphically following different development branches.

Download


gitg

gitg is a git repository viewer targeting gtk+/GNOME. One of its main objectives is to provide a more unified user experience for git frontends across multiple desktops. It does this not be writing a cross-platform application, but by close collaboration with similar clients for other operating systems (like GitX for OS X).

Features

  • Browse revision history.
  • Handle large repositories (loads linux repository, 17000+ revisions, under 1 second).
  • Commit changes.
  • Stage/unstage individual hunks.
  • Revert changes.
  • Show colorized diff of changes in revisions.
  • Browse tree for a given revision.
  • Export parts of the tree of a given revision.
  • Supply any refspec which a command such as 'git log' can understand to built the history.
  • Show and switch between branches in the history view.

Download: releases or source


Gitbox

Gitbox is a Mac OS X graphical interface for Git version control system. In a single window you see branches, history and working directory status.

Everyday operations are easy: stage and unstage changes with a checkbox. Commit, pull, merge and push with a single click. Double-click a change to show a diff with FileMerge.app.

Download


Gity

The Gity website doesn't have much information, but from the screenshots on there it appears to be a feature rich open source OS X git gui.

Download or source


Meld

Meld is a visual diff and merge tool. You can compare two or three files and edit them in place (diffs update dynamically). You can compare two or three folders and launch file comparisons. You can browse and view a working copy from popular version control systems such such as CVS, Subversion, Bazaar-ng and Mercurial [and Git].

Downloads


Katana

A Git GUIfor OSX by Steve Dekorte.

At a glance, see which remote branches have changes to pull and local repos have changes to push. The git ops of add, commit, push, pull, tag and reset are supported as well as visual diffs and visual browsing of project hieracy that highlights local changes and additions.

Free for 1 repository, $25 for more.

Download


Sprout (formerly GitMac)

Focuses on making Git easy to use. Features a native Cocoa (mac-like) UI, fast repository browsing, cloning, push/pull, branching/merging, visual diff, remote branches, easy access to the Terminal, and more.

By making the most commonly used Git actions intuitive and easy to perform, Sprout (formerly GitMac) makes Git user-friendly. Compatible with most Git workflows, Sprout is great for designers and developers, team collaboration and advanced and novice users alike.

Download | Website


Tower

A feature-rich Git GUI for Mac OSX. 30-day free trial, $59USD for a single-user license.

Download | Website


EGit

EGit is an Eclipse Team provider for the Git version control system. Git is a distributed SCM, which means every developer has a full copy of all history of every revision of the code, making queries against the history very fast and versatile.

The EGit project is implementing Eclipse tooling on top of the JGit Java implementation of Git.

Download | Website


Git Extensions

Open Source for Windows - installs everything you need to work with Git in a single package, easy to use.

Git Extensions is a toolkit to make working with Git on Windows more intuitive. The shell extension will intergrate in Windows Explorer and presents a context menu on files and directories. There is also a Visual Studio plugin to use git from Visual Studio.

Download

Big thanks to dbr for elaborating on the git gui stuff.


SourceTree

SourceTree is a free Mac client for Git, Mercurial and SVN. Built by Atlassian, the folks behind BitBucket, it seems to work equally well with any VC system, which allows you to master a single tool for use with all of your projects, however they're version-controlled. Feature-packed, and FREE.

Expert-Ready & Feature-packed for both novice and advanced users:

Review outgoing and incoming changesets. Cherry-pick between branches. Patch handling, rebase, stash / shelve and much more.

Download | Website


Submitting a form on 'Enter' with jQuery?

In HTML codes:

<form action="POST" onsubmit="ajax_submit();return false;">
    <b>First Name:</b> <input type="text" name="firstname" id="firstname">
    <br>
    <b>Last Name:</b> <input type="text" name="lastname" id="lastname">
    <br>
    <input type="submit" name="send" onclick="ajax_submit();">
</form>

In Js codes:

function ajax_submit()
{
    $.ajax({
        url: "submit.php",
        type: "POST",
        data: {
            firstname: $("#firstname").val(),
            lastname: $("#lastname").val()
        },
        dataType: "JSON",
        success: function (jsonStr) {
            // another codes when result is success
        }
    });
}

Plotting two variables as lines using ggplot2 on the same graph

Using your data:

test_data <- data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
Dates = seq.Date(as.Date("2002-01-01"), by="1 month", length.out=100))

I create a stacked version which is what ggplot() would like to work with:

stacked <- with(test_data,
                data.frame(value = c(var0, var1),
                           variable = factor(rep(c("Var0","Var1"),
                                                 each = NROW(test_data))),
                           Dates = rep(Dates, 2)))

In this case producing stacked was quite easy as we only had to do a couple of manipulations, but reshape() and the reshape and reshape2 might be useful if you have a more complex real data set to manipulate.

Once the data are in this stacked form, it only requires a simple ggplot() call to produce the plot you wanted with all the extras (one reason why higher-level plotting packages like lattice and ggplot2 are so useful):

require(ggplot2)
p <- ggplot(stacked, aes(Dates, value, colour = variable))
p + geom_line()

I'll leave it to you to tidy up the axis labels, legend title etc.

HTH

How do I edit SSIS package files?

You need the Business Intelligence Studio ..I've checked and my version of VS2008 Pro doesn't have them installed.

Have a look at this link:

http://www.microsoft.com/downloads/details.aspx?familyid=3C856B93-369F-4C6F-9357-C35384179543&displaylang=en

Python Accessing Nested JSON Data

I'm using this lib to access nested dict keys

https://github.com/mewwts/addict

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number 

Updating an object with setState in React

Your second approach doesn't work because {name: 'someothername'} equals {name: 'someothername', age: undefined}, so theundefined would overwrite original age value.

When it comes to change state in nested objects, a good approach would be Immutable.js

this.state = {
  jasper: Record({name: 'jasper', age: 28})
}

const {jasper} = this.state
this.setState({jasper: jasper.set(name, 'someothername')})

SQL Server 2005 How Create a Unique Constraint?

In some situations, it could be desirable to ensure the Unique key does not exists before create it. In such cases, the script below might help:

IF Exists(SELECT * FROM sys.indexes WHERE name Like '<index_name>')
    ALTER TABLE dbo.<target_table_name> DROP CONSTRAINT <index_name> 
GO

ALTER TABLE dbo.<target_table_name> ADD CONSTRAINT <index_name> UNIQUE NONCLUSTERED (<col_1>, <col_2>, ..., <col_n>) 
GO

What's the difference between "2*2" and "2**2" in Python?

The top one is a "power" operator, so in this case it is the same as 2 * 2 equal to is 2 to the power of 2. If you put a 3 in the middle position, you will see a difference.

How to initialize an array in angular2 and typescript

I don't fully understand what you really mean by initializing an array?

Here's an example:

class Environment {

    // you can declare private, public and protected variables in constructor signature 
    constructor(
        private id: string,
        private name: string
    ) { 
        alert( this.id );
    }
}


let environments = new Environment('a','b');

// creating and initializing array of Environment objects
let envArr: Array<Environment> = [ 
        new Environment('c','v'), 
        new Environment('c','v'), 
        new Environment('g','g'), 
        new Environment('3','e') 
  ];

Try it here : https://www.typescriptlang.org/play/index.html

How to git-cherry-pick only changes to certain files?

For the sake of completness, what works best for me is:

git show YOURHASH --no-color -- file1.txt file2.txt dir3 dir4 | git apply -3 --index -

It does exactly what OP wants. It does conflict resolution when needed, similarly how merge does it. It does add but not commit your new changes, see with status.

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

I was having this issue for the following reason.

TLDR: Check if you are sending a GET request that should be sending the parameters on the url instead of on the NSURLRequest's HTTBody property.

==================================================

I had mounted a network abstraction on my app, and it was working pretty well for all my requests.

I added a new request to another web service (not my own) and it started throwing me this error.

I went to a playground and started from the ground up building a barebones request, and it worked. So I started moving closer to my abstraction until I found the cause.

My abstraction implementation had a bug: I was sending a request that was supposed to send parameters encoded in the url and I was also filling the NSURLRequest's HTTBody property with the query parameters as well. As soon as I removed the HTTPBody it worked.

PHP Function with Optional Parameters

To accomplish what you want, use an array Like Rabbot said (though this can become a pain to document/maintain if used excessively). Or just use the traditional optional args.

//My function with tons of optional params
function my_func($req_a, $req_b, $opt_a = NULL, $opt_b = NULL, $opt_c = NULL)
{
  //Do stuff
}
my_func('Hi', 'World', null, null, 'Red');

However, I usually find that when I start writing a function/method with that many arguments - more often than not it is a code smell, and can be re-factored/abstracted into something much cleaner.

//Specialization of my_func - assuming my_func itself cannot be refactored
function my_color_func($reg_a, $reg_b, $opt = 'Red')
{
  return my_func($reg_a, $reg_b, null, null, $opt);
}
my_color_func('Hi', 'World');
my_color_func('Hello', 'Universe', 'Green');

Large Numbers in Java

Depending on what you're doing you might like to take a look at GMP (gmplib.org) which is a high-performance multi-precision library. To use it in Java you need JNI wrappers around the binary library.

See some of the Alioth Shootout code for an example of using it instead of BigInteger to calculate Pi to an arbitrary number of digits.

https://benchmarksgame-team.pages.debian.net/benchmarksgame/program/pidigits-java-2.html

The import android.support cannot be resolved

Please follow these Steps:

For Eclipse:

  • Go to your Project's Properties
  • Navigate to the Java Build Path
  • Then go to the Libraries tab. There click the Add External JARs Button on the Right pane.
  • Select the android-support-v4.jar file, usually the path for the Jar file is :
    YOUR_DRIVE\android-sdks\extras\android\support\v4\android-support-v4.jar
  • After adding android-support-v4.jar Library, navigate to the Order and Export tab and put check mark on the android-support-v4 Library file.
  • After doing the above, Clean the Project and Build it.
  • Problem Solved.

For Android Studio:

Short Version:

  • Add the following line to your build.gradle file:
    implementation 'com.android.support:support-v4:YOUR_TARGET_VERSION'

Long Version:

  • Go to File -> Project Structure

  • Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency"

  • Select the support library "support-v4 (com.android.support:support-v4:YOUR_TARGET_VERSION)"

  • Navigate to your "build.gradle" inside your App Directory and double check if your desired Android Support Library has been added to your dependencies.

  • Rebuild your project and now everything should work.

Further reading regarding this Question:

  1. Support Library - Android Dev
  2. Recent Support Library Revisions
  3. Support Library Packages
  4. What is an Android Support Library?
  5. How Android Support Library work?

I hope this helps.

Proper MIME type for OTF fonts

As a specific instance of one of the two hard things in computing, it’s interesting to see how the answers to this question have changed since this question was originally posted. Thankfully, the powers that be have brought order to the chaos:


In February this year (2017), the W3C published the Standards Track RFC 8081: The "font" Top-Level Media Type which greatly simplifies the appropriate media types for font files:

This memo serves to register and document the "font" top-level media type, under which subtypes for representation formats for fonts may be registered. This document also serves as a registration application for a set of intended subtypes, which are representative of some existing subtypes already in use, and currently registered under the "application" tree by their separate registrations.

It’s quite a readable document and it describes the historical context (lack of “a registration of formats for font”) which gave rise to the confusing mix of media types and sub-types. With the (relatively) recent rise in popularity of downloadable web fonts, the W3C recognised the need for an “intuitive top-level font type”. What they came up with is … font.

Accordingly, the IANA have since updated their official list of Media types with the font media type and all its sub-types that they currently recognise:

collection  font/collection
otf     font/otf
sfnt    font/sfnt
ttf     font/ttf
woff    font/woff
woff2   font/woff2

Here’s hoping this is the last answer this question needs.

Default behavior of "git push" without a branch specified

You can push current branch with command

git push origin HEAD

(took from here)

How do I set browser width and height in Selenium WebDriver?

This works both with headless and non-headless, and will start the window with the specified size instead of setting it after:

from selenium.webdriver import Firefox, FirefoxOptions

opts = FirefoxOptions()
opts.add_argument("--width=2560")
opts.add_argument("--height=1440")

driver = Firefox(options=opts)

Excel: How to check if a cell is empty with VBA?

This site uses the method isEmpty().

Edit: content grabbed from site, before the url will going to be invalid.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop

In the first step the data in the first column from Sheet1 will be sort. In the second step, all rows with same data will be removed.

jQuery: enabling/disabling datepicker

   $("#datepicker").datepicker({
     dateFormat:'dd/M/yy',
     minDate: 'now',
     changeMonth:true,
     changeYear:true,
     showOn: "focus",
    // buttonImage: "YourImage",
     buttonImageOnly: true, 
     yearRange: "-100:+0",  
  }); 

  $( "#datepicker" ).datepicker( "option", "disabled", true ); //missing ID selector

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

How to define an empty object in PHP

If you don't want to do this:

$myObj = new stdClass();
$myObj->key_1 = 'Hello';
$myObj->key_2 = 'Dolly';

You can use one of the following:

PHP >=5.4

$myObj = (object) [
    'key_1' => 'Hello',
    'key_3' => 'Dolly',
];

PHP <5.4

$myObj = (object) array(
    'key_1' => 'Hello',
    'key_3' => 'Dolly',
);

How to escape the equals sign in properties files

You can look here Can the key in a Java property include a blank character?

for escape equal '=' \u003d

table.whereclause=where id=100

key:[table.whereclause] value:[where id=100]

table.whereclause\u003dwhere id=100

key:[table.whereclause=where] value:[id=100]

table.whereclause\u003dwhere\u0020id\u003d100

key:[table.whereclause=where id=100] value:[]

How to execute a command prompt command from python

It's very simple. You need just two lines of code with just using the built-in function and also it takes the input and runs forever until you stop it. Also that 'cmd' in quotes, leave it and don't change it. Here is the code:

import os
os.system('cmd')

Now just run this code and see the whole windows command prompt in your python project!

dataframe: how to groupBy/count then filter on count in Scala

When you pass a string to the filter function, the string is interpreted as SQL. Count is a SQL keyword and using count as a variable confuses the parser. This is a small bug (you can file a JIRA ticket if you want to).

You can easily avoid this by using a column expression instead of a String:

df.groupBy("x").count()
  .filter($"count" >= 2)
  .show()

How do I validate a date string format in python?

>>> import datetime
>>> def validate(date_text):
    try:
        datetime.datetime.strptime(date_text, '%Y-%m-%d')
    except ValueError:
        raise ValueError("Incorrect data format, should be YYYY-MM-DD")


>>> validate('2003-12-23')
>>> validate('2003-12-32')

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    validate('2003-12-32')
  File "<pyshell#18>", line 5, in validate
    raise ValueError("Incorrect data format, should be YYYY-MM-DD")
ValueError: Incorrect data format, should be YYYY-MM-DD

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

This can be resolved by specifying a primary key on the @new_super table, as follows:

DECLARE @new_super TABLE (
  row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
  super_id   int
);

This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

In terminal, log into MySQL as root. You may have created a root password when you installed MySQL for the first time or the password could be blank, in which case you can just press ENTER when prompted for a password.

 sudo mysql -p -u root

Now add a new MySQL user with the username of your choice. In this example we are calling it pmauser (for phpmyadmin user). Make sure to replace password_here with your own. You can generate a password here. The % symbol here tells MySQL to allow this user to log in from anywhere remotely. If you wanted heightened security, you could replace this with an IP address.

CREATE USER 'pmauser'@'%' IDENTIFIED BY 'password_here';

Now we will grant superuser privilege to our new user.

GRANT ALL PRIVILEGES ON *.* TO 'pmauser'@'%' WITH GRANT OPTION;

Then go to config.inc.php ( in ubuntu, /etc/phpmyadmin/config.inc.php )

/* User for advanced features */

$cfg['Servers'][$i]['controluser'] = 'pmauser'; 
$cfg['Servers'][$i]['controlpass'] = 'password_here';

C# Enum - How to Compare Value

You can use Enum.Parse like, if it is string

AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")

Sum values from an array of key-value pairs in JavaScript

where 0 is initial value

Array.reduce((currentValue, value) => currentValue +value,0)

or

Array.reduce((currentValue, value) =>{ return currentValue +value},0)

or

[1,3,4].reduce(function(currentValue, value) { return currentValue + value},0)

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

The most recent versions of hibernate JPA provider applies the bean validation constraints (JSR 303) like @NotNull to DDL by default (thanks to hibernate.validator.apply_to_ddl property defaults to true). But there is no guarantee that other JPA providers do or even have the ability to do that.

You should use bean validation annotations like @NotNull to ensure, that bean properties are set to a none-null value, when validating java beans in the JVM (this has nothing to do with database constraints, but in most situations should correspond to them).

You should additionally use the JPA annotation like @Column(nullable = false) to give the jpa provider hints to generate the right DDL for creating table columns with the database constraints you want. If you can or want to rely on a JPA provider like Hibernate, which applies the bean validation constraints to DDL by default, then you can omit them.

vertical-align: middle doesn't work

Vertical align doesn't quite work the way you want it to. See: http://phrogz.net/css/vertical-align/index.html

This isn't pretty, but it WILL do what you want: Vertical align behaves as expected only when used in a table cell.

http://jsfiddle.net/e8ESb/6/

There are other alternatives: You can declare things as tables or table cells within CSS to make them behave as desired, for example. Margins and positioning can sometimes be played with to get the same effect. None of the solutions are terrible pretty, though.

IIS7: Setup Integrated Windows Authentication like in IIS6

There's another thread elsewhere on Stack with a similar topic and the best solution I've come across is to use the free version of Helicon Ape

Once you've got that installed, follow the steps at the page Titled "HTTP Authentication and Authorization"

DataTable, How to conditionally delete rows

You could query the dataset and then loop the selected rows to set them as delete.

var rows = dt.Select("col1 > 5");
foreach (var row in rows)
    row.Delete();

... and you could also create some extension methods to make it easier ...

myTable.Delete("col1 > 5");

public static DataTable Delete(this DataTable table, string filter)
{
    table.Select(filter).Delete();
    return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
    foreach (var row in rows)
        row.Delete();
}

How can I let a user download multiple files when a button is clicked?

The best way to do this is to have your files zipped and link to that:

The other solution can be found here: How to make a link open multiple pages when clicked

Which states the following:

HTML:

<a href="#" class="yourlink">Download</a>

JS:

$('a.yourlink').click(function(e) {
    e.preventDefault();
    window.open('mysite.com/file1');
    window.open('mysite.com/file2');
    window.open('mysite.com/file3');
});

Having said this, I would still go with zipping the file, as this implementation requires JavaScript and can also sometimes be blocked as popups.

How to shut down the computer from C#

If you want to shut down computer remotely then you can use

Using System.Diagnostics;

on any button click

{
    Process.Start("Shutdown","-i");
}

How to enable Google Play App Signing

While Migrating Android application package file (APK) to Android App Bundle (AAB), publishing app into Play Store i faced this issue and got resolved like this below...

When building .aab file you get prompted for the location to store key export path as below:

enter image description here
enter image description here In second image you find Encrypted key export path Location where our .pepk will store in the specific folder while generating .aab file.

Once you log in to the Google Play Console with play store credential: select your project from left side choose App Signing option Release Management>>App Signing enter image description here

you will find the Google App Signing Certification window ACCEPT it.

After that you will find three radio button select **

Upload a key exported from Android Studio radio button

**, it will expand you APP SIGNING PRIVATE KEY button as below

enter image description here

click on the button and choose the .pepk file (We Stored while generating .aab file as above)

Read the all other option and submit.

Once Successfully you can go back to app release and browse the .aab file and complete RollOut...

@Ambilpura

Dump Mongo Collection into JSON format

Use mongoexport/mongoimport to dump/restore a collection:

Export JSON File:

mongoexport --db <database-name> --collection <collection-name> --out output.json

Import JSON File:

mongoimport --db <database-name> --collection <collection-name> --file input.json

WARNING mongoimport and mongoexport do not reliably preserve all rich BSON data types because JSON can only represent a subset of the types supported by BSON. As a result, data exported or imported with these tools may lose some measure of fidelity.

Also, http://bsonspec.org/

BSON is designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.

In addition to compactness, BSON adds additional data types unavailable in JSON, notably the BinData and Date data types.

Remove the first character of a string

python 2.x

s = ":dfa:sif:e"
print s[1:]

python 3.x

s = ":dfa:sif:e"
print(s[1:])

both prints

dfa:sif:e

In Visual Studio C++, what are the memory allocation representations?

This link has more information:

https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values

* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory
* 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers
* 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory
* 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger
* 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files
* 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory
* 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory
* 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory
* 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash.
* 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory
* 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

The error happens when you have compiled with higher version of Java and it is been tried to run with lower version of JRE. Even with minor version mismatch you would have this issue

I had issue compiling with JDK 1.8.0_31 and it was run with jdk1.8.0_25 and was displaying the same error. Once either the target is updated to higher version or compiled with same or lesser version would resolve the issue

Loading context in Spring using web.xml

You can also load the context while defining the servlet itself (WebApplicationContext)

  <servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                /WEB-INF/spring/*.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

rather than (ApplicationContext)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

or can do both together.

Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet etc)

Context loaded by ContextLoaderListener will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.

SQL Developer is returning only the date, not the time. How do I fix this?

To expand on some of the previous answers, I found that Oracle DATE objects behave different from Oracle TIMESTAMP objects. In particular, if you set your NLS_DATE_FORMAT to include fractional seconds, the entire time portion is omitted.

  • Format "YYYY-MM-DD HH24:MI:SS" works as expected, for DATE and TIMESTAMP
  • Format "YYYY-MM-DD HH24:MI:SSXFF" displays just the date portion for DATE, works as expected for TIMESTAMP

My personal preference is to set DATE to "YYYY-MM-DD HH24:MI:SS", and to set TIMESTAMP to "YYYY-MM-DD HH24:MI:SSXFF".

Using 'starts with' selector on individual class names

I'd recommend making "apple" its own class. You should avoid the starts-with/ends-with if you can because being able to select using div.apple would be a lot faster. That's the more elegant solution. Don't be afraid to split things out into separate classes if it makes the task simpler/faster.

Combining C++ and C - how does #ifdef __cplusplus work?

It's about the ABI, in order to let both C and C++ application use C interfaces without any issue.

Since C language is very easy, code generation was stable for many years for different compilers, such as GCC, Borland C\C++, MSVC etc.

While C++ becomes more and more popular, a lot things must be added into the new C++ domain (for example finally the Cfront was abandoned at AT&T because C could not cover all the features it needs). Such as template feature, and compilation-time code generation, from the past, the different compiler vendors actually did the actual implementation of C++ compiler and linker separately, the actual ABIs are not compatible at all to the C++ program at different platforms.

People might still like to implement the actual program in C++ but still keep the old C interface and ABI as usual, the header file has to declare extern "C" {}, it tells the compiler generate compatible/old/simple/easy C ABI for the interface functions if the compiler is C compiler not C++ compiler.

Count the number of occurrences of a character in a string in Javascript

The fastest method seems to be via the index operator:

_x000D_
_x000D_
function charOccurances (str, char)_x000D_
{_x000D_
  for (var c = 0, i = 0, len = str.length; i < len; ++i)_x000D_
  {_x000D_
    if (str[i] == char)_x000D_
    {_x000D_
      ++c;_x000D_
    }_x000D_
  }_x000D_
  return c;_x000D_
}_x000D_
_x000D_
console.log( charOccurances('example/path/script.js', '/') ); // 2
_x000D_
_x000D_
_x000D_

Or as a prototype function:

_x000D_
_x000D_
String.prototype.charOccurances = function (char)_x000D_
{_x000D_
  for (var c = 0, i = 0, len = this.length; i < len; ++i)_x000D_
  {_x000D_
    if (this[i] == char)_x000D_
    {_x000D_
      ++c;_x000D_
    }_x000D_
  }_x000D_
  return c;_x000D_
}_x000D_
_x000D_
console.log( 'example/path/script.js'.charOccurances('/') ); // 2
_x000D_
_x000D_
_x000D_

JPA - Returning an auto generated id after persist()

Another option compatible to 4.0:

Before committing the changes, you can recover the new CayenneDataObject object(s) from the collection associated to the context, like this:

CayenneDataObject dataObjectsCollection = (CayenneDataObject)cayenneContext.newObjects();

then access the ObjectId for each one in the collection, like:

ObjectId objectId = dataObject.getObjectId();

Finally you can iterate under the values, where usually the generated-id is going to be the first one of the values (for a single column key) in the Map returned by getIdSnapshot(), it contains also the column name(s) associated to the PK as key(s):

objectId.getIdSnapshot().values()

Enabling CORS in Cloud Functions for Firebase

If none of the other solutions work, you could try adding the below address at the beginning of the call to enable CORS - redirect:

https://cors-anywhere.herokuapp.com/

Sample code with JQuery AJAX request:

$.ajax({
   url: 'https://cors-anywhere.herokuapp.com/https://fir-agilan.web.app/[email protected],
   type: 'GET'
});

What is the simplest way to convert array to vector?

Pointers can be used like any other iterators:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + 3);
test(v)

Closing pyplot windows

plt.close() will close current instance.

plt.close(2) will close figure 2

plt.close(plot1) will close figure with instance plot1

plt.close('all') will close all fiures

Found here.

Remember that plt.show() is a blocking function, so in the example code you used above, plt.close() isn't being executed until the window is closed, which makes it redundant.

You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications.

EXAMPLE

After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.

Below I create a plot:

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')

In this case, ax above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax).

par_plot is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.

I can also create a slider widget by doing the following:

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

The first line creates a new axes for the slider (called axsliderA), the second line creates a slider instance sA which is placed in the axes, and the third line specifies a function to call when the slider value changes (update).

My update function could look something like this:

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()

The par_plot.set_ydata(y_data) changes the ydata property of the Line2D object with the handle par_plot.

The draw() function updates the current set of axes.

Putting it all together:

from pylab import *
import matplotlib.pyplot as plt
import numpy

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()


x_data = numpy.arange(-100,100,0.1);

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)

ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)

axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)

axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;

par_plot, = plot(x_data,y_data, lw=2, color='red')

show()

A note about the above: When I run the application, the code runs sequentially right through (it stores the update function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).

This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.

How do I use vim registers?

I think the secret guru register is the expression = register. It can be used for creative mappings.

:inoremap  \d The current date <c-r>=system("date")<cr>

You can use it in conjunction with your system as above or get responses from custom VimL functions etc.

or just ad hoc stuff like

<c-r>=35+7<cr>

SQL Call Stored Procedure for each Row without using a cursor

I had a situation where I needed to perform a series of operations on a result set (table). The operations are all set operations, so its not an issue, but... I needed to do this in multiple places. So putting the relevant pieces in a table type, then populating a table variable w/ each result set allows me to call the sp and repeat the operations each time i need to .

While this does not address the exact question he asks, it does address how to perform an operation on all rows of a table without using a cursor.

@Johannes offers no insight into his motivation , so this may or may not help him.

my research led me to this well written article which served as a basis for my solution https://codingsight.com/passing-data-table-as-parameter-to-stored-procedures/

Here is the setup

    drop type if exists cpRootMapType 
go 

create type cpRootMapType as Table(
    RootId1 int 
    , RootId2 int
)

go 
drop procedure if exists spMapRoot2toRoot1
go 
create procedure spMapRoot2toRoot1
(
@map cpRootMapType Readonly
)
as

update linkTable set root = root1  
from linktable  lt 
join @map m on lt.root = root2

update comments set root = root1 
from comments c 
join @map m on c.root = root2

--  ever growing list of places this map would need to be applied....
--  now consolidated into one place 

here is the implementation

... populate #matches

declare @map cpRootMapType 
insert @map select rootid1, rootid2 from #matches
exec spMapRoot2toRoot1 @map 

android on Text Change Listener

You can add a check to only clear when the text in the field is not empty (i.e when the length is different than 0).

field1.addTextChangedListener(new TextWatcher() {

   @Override
   public void afterTextChanged(Editable s) {}

   @Override    
   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   @Override    
   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
      if(s.length() != 0)
        field2.setText("");
   }
  });

field2.addTextChangedListener(new TextWatcher() {

   @Override
   public void afterTextChanged(Editable s) {}

   @Override
   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   @Override
   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
      if(s.length() != 0)
         field1.setText("");
   }
  });

Documentation for TextWatcher here.

Also please respect naming conventions.

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The min sdk version is the minimum version of the Android operating system required to run your application.

The target sdk version is the version of Android that your app was created to run on.

The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.

Usually the compile sdk version and the target sdk version are the same.

Create a rounded button / button with border-radius in Flutter

New Elevate Button-------->

    style --->
    
    customElevatedButton({radius, color}) => ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(radius == null ? 100 : radius),
          ),
          primary: color,
        );



icon--->

    Widget saveIcon() => iconsStyle1(
          Icons.save,
        );

//common icon style

    iconsStyle1(icon) => Icon(
          icon,
          color: white,
          size: 15,
        );

button use---> 
    ElevatedButton.icon(
                            icon: saveIcon(),
                            style:
                                customElevatedButton(color: Colors.green[700]),
                            label: Text('Save',
                                style: TextStyle(color: Colors.white)),
                            onPressed: () {
                            },
                          ),

How to redirect verbose garbage collection output to a file?

To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.

A brief excerpt:

The flag -XX:+PrintGC (or the alias -verbose:gc) activates the “simple” GC logging mode

By default the GC log is written to stdout. With -Xloggc:<file> we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC and -XX:+PrintGCTimeStamps as well.

If we use -XX:+PrintGCDetails instead of -XX:+PrintGC, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.

With -XX:+PrintGCTimeStamps a timestamp reflecting the real time passed in seconds since JVM start is added to every line.

If we specify -XX:+PrintGCDateStamps each line starts with the absolute date and time.

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

Issue related to git commands on Windows operating system:

$ git add --all

warning: LF will be replaced by CRLF in ...

The file will have its original line endings in your working directory.

Resolution:

$ git config --global core.autocrlf false     
$ git add --all 

No any warning messages come up.

How to call a function from a string stored in a variable?

I dont know why u have to use that, doesnt sound so good to me at all, but if there are only a small amount of functions, you could use a if/elseif construct. I dont know if a direct solution is possible.

something like $foo = "bar"; $test = "foo"; echo $$test;

should return bar, you can try around but i dont think this will work for functions

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

EDIT: The correct way to do this is in @LiviuT's answer!

You can always extend Angular's scope to allow you to remove such listeners like so:

//A little hack to add an $off() method to $scopes.
(function () {
  var injector = angular.injector(['ng']),
      rootScope = injector.get('$rootScope');
      rootScope.constructor.prototype.$off = function(eventName, fn) {
        if(this.$$listeners) {
          var eventArr = this.$$listeners[eventName];
          if(eventArr) {
            for(var i = 0; i < eventArr.length; i++) {
              if(eventArr[i] === fn) {
                eventArr.splice(i, 1);
              }
            }
          }
        }
      }
}());

And here's how it would work:

  function myEvent() {
    alert('test');
  }
  $scope.$on('test', myEvent);
  $scope.$broadcast('test');
  $scope.$off('test', myEvent);
  $scope.$broadcast('test');

And here's a plunker of it in action

else & elif statements not working in Python

Python can generate same 'invalid syntax' error even if ident for 'elif' block not matching to 'if' block ident (tabs for the first, spaces for second or vice versa).

calling another method from the main method in java

This is a fundamental understanding in Java, but can be a little tricky to new programmers. Do a little research on the difference between a static and instance method. The basic difference is the instance method do() is only accessible to a instance of the class foo.

You must instantiate (create an instance of) the class, creating an object, that you use to call the instance method.

I have included your example with a couple comments and example.

public class SomeName {

//this is a static method and cannot call an instance method without a object
public static void main(String[] args){

    // can't do this from this static method, no object reference
    // someMethod();

    //create instance of object
    SomeName thisObj = new SomeName();
    //call instance method using object
    thisObj.someMethod();
}

//instance method
public void someMethod(){
    System.out.print("some message...");
}

}// end class SomeName

Displaying the Error Messages in Laravel after being Redirected from controller

If you want to load the view from the same controller you are on:

if ($validator->fails()) {
    return self::index($request)->withErrors($validator->errors());
}

And if you want to quickly display all errors but have a bit more control:

 @if ($errors->any())
     @foreach ($errors->all() as $error)
         <div>{{$error}}</div>
     @endforeach
 @endif

How to convert unix timestamp to calendar date moment.js

$(document).ready(function() {
    var value = $("#unixtime").val(); //this retrieves the unix timestamp
    var dateString = moment(value, 'MM/DD/YYYY', false).calendar(); 
    alert(dateString);
});

There is a strict mode and a Forgiving mode.

While strict mode works better in most situations, forgiving mode can be very useful when the format of the string being passed to moment may vary.

In a later release, the parser will default to using strict mode. Strict mode requires the input to the moment to exactly match the specified format, including separators. Strict mode is set by passing true as the third parameter to the moment function.

A common scenario where forgiving mode is useful is in situations where a third party API is providing the date, and the date format for that API could change. Suppose that an API starts by sending dates in 'YYYY-MM-DD' format, and then later changes to 'MM/DD/YYYY' format.

In strict mode, the following code results in 'Invalid Date' being displayed:

moment('01/12/2016', 'YYYY-MM-DD', true).format()
"Invalid date"

In forgiving mode using a format string, you get a wrong date:

moment('01/12/2016', 'YYYY-MM-DD').format()
"2001-12-20T00:00:00-06:00"

another way would be

$(document).ready(function() {
    var value = $("#unixtime").val(); //this retrieves the unix timestamp
    var dateString = moment.unix(value).calendar(); 
    alert(dateString);
});

Get current date in DD-Mon-YYY format in JavaScript/Jquery

Can be done with toLocaleDateString

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

_x000D_
_x000D_
<script>_x000D_
const date = new Date();_x000D_
const formattedDate = date.toLocaleDateString('en-GB', {_x000D_
  day: '2-digit', month: 'short', year: 'numeric'_x000D_
}).replace(/ /g, '-');_x000D_
document.write(formattedDate);_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

Looks like the solution has been baked into Homebrew now:

$ brew info postgresql
...
==> Caveats
To migrate existing data from a previous major version of PostgreSQL run:
  brew postgresql-upgrade-database
....

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

Deleting an element from an array in PHP

<?php
    $stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
    $fruit = array_shift($stack);
    print_r($stack);

    echo $fruit;
?>

Output:

[
    [0] => fruit2
    [1] => fruit3
    [2] => fruit4
]

fruit1

Why is "throws Exception" necessary when calling a function?

Basically, if you are not handling the exception in the same place as you are throwing it, then you can use "throws exception" at the definition of the function.

ArrayAdapter in android to create simple listview

ArrayAdapter uses a TextView to display each item within it. Behind the scenes, it uses the toString() method of each object that it holds and displays this within the TextView. ArrayAdapter has a number of constructors that can be used and the one that you have used in your example is:

ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)

By default, ArrayAdapter uses the default TextView to display each item. But if you want, you could create your own TextView and implement any complex design you'd like by extending the TextView class. This would then have to go into the layout for your use. You could reference this in the textViewResourceId field to bind the objects to this view instead of the default.

For your use, I would suggest that you use the constructor:

ArrayAdapter(Context context, int resource, T[] objects). 

In your case, this would be:

ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values)

and it should be fine. This will bind each string to the default TextView display - plain and simple white background.

So to answer your question, you do not have to use the textViewResourceId.

Should I return EXIT_SUCCESS or 0 from main()?

It does not matter. Both are the same.

C++ Standard Quotes:

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

How to order events bound with jQuery

The order the bound callbacks are called in is managed by each jQuery object's event data. There aren't any functions (that I know of) that allow you to view and manipulate that data directly, you can only use bind() and unbind() (or any of the equivalent helper functions).

Dowski's method is best, you should modify the various bound callbacks to bind to an ordered sequence of custom events, with the "first" callback bound to the "real" event. That way, no matter in what order they are bound, the sequence will execute in the right way.

The only alternative I can see is something you really, really don't want to contemplate: if you know the binding syntax of the functions may have been bound before you, attempt to un-bind all of those functions and then re-bind them in the proper order yourself. That's just asking for trouble, because now you have duplicated code.

It would be cool if jQuery allowed you to simply change the order of the bound events in an object's event data, but without writing some code to hook into the jQuery core that doesn't seem possible. And there are probably implications of allowing this that I haven't thought of, so maybe it's an intentional omission.

Show Current Location and Update Location in MKMapView in Swift

You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last{
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        self.map.setRegion(region, animated: true)
    }
}

NOTE: If your target is iOS 8 or above, you must include the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key in your Info.plist to get the location services to work.

How Many Seconds Between Two Dates?

If one or both of your dates are in the future, then I'm afraid you're SOL if you want to-the-second accuracy. UTC time has leap seconds that aren't known until about 6 months before they happen, so any dates further out than that can be inaccurate by some number of seconds (and in practice, since people don't update their machines that often, you may find that any time in the future is off by some number of seconds).

This gives a good explanation of the theory of designing date/time libraries and why this is so: http://www.boost.org/doc/libs/1_41_0/doc/html/date_time/details.html#date_time.tradeoffs

Constant pointer vs Pointer to constant

const int* ptr; 

declares ptr a pointer to const int type. You can modify ptr itself but the object pointed to by ptr shall not be modified.

const int a = 10;
const int* ptr = &a;  
*ptr = 5; // wrong
ptr++;    // right  

While

int * const ptr;  

declares ptr a const pointer to int type. You are not allowed to modify ptr but the object pointed to by ptr can be modified.

int a = 10;
int *const ptr = &a;  
*ptr = 5; // right
ptr++;    // wrong

Generally I would prefer the declaration like this which make it easy to read and understand (read from right to left):

int const  *ptr; // ptr is a pointer to constant int 
int *const ptr;  // ptr is a constant pointer to int

Parse query string in JavaScript

I wanted a simple function that took a URL as an input and returned a map of the query params. If I were to improve this function, I would support the standard for array data in the URL, and or nested variables.

This should work back and for with the jQuery.param( qparams ) function.

function getQueryParams(url){
    var qparams = {},
        parts = (url||'').split('?'),
        qparts, qpart,
        i=0;

    if(parts.length <= 1 ){
        return qparams;
    }else{
        qparts = parts[1].split('&');
        for(i in qparts){

            qpart = qparts[i].split('=');
            qparams[decodeURIComponent(qpart[0])] = 
                           decodeURIComponent(qpart[1] || '');
        }
    }

    return qparams;
};

Error: «Could not load type MvcApplication»

My solution: Because I created the problem! I had changed the namespace in Global.asax.cs

You also need to change the Inherits attribute value in the Global.asax.

How do I auto size columns through the Excel interop objects?

This might be too late but if you add

 worksheet.Columns.AutoFit();

or

 worksheet.Rows.AutoFit();

it also works.

How to list the properties of a JavaScript object?

Object.getOwnPropertyNames(obj)

This function also shows non-enumerable properties in addition to those shown by Object.keys(obj).

In JS, every property has a few properties, including a boolean enumerable.

In general, non-enumerable properties are more "internalish" and less often used, but it is insightful to look into them sometimes to see what is really going on.

Example:

var o = Object.create({base:0})
Object.defineProperty(o, 'yes', {enumerable: true})
Object.defineProperty(o, 'not', {enumerable: false})

console.log(Object.getOwnPropertyNames(o))
// [ 'yes', 'not' ]

console.log(Object.keys(o))
// [ 'yes' ]

for (var x in o)
    console.log(x)
// yes, base

Also note how:

  • Object.getOwnPropertyNames and Object.keys don't go up the prototype chain to find base
  • for in does

More about the prototype chain here: https://stackoverflow.com/a/23877420/895245

How to write header row with csv.DictWriter?

Edit:
In 2.7 / 3.2 there is a new writeheader() method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader() method now available in 2.7 / 3.2:

from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
    dw.writeheader()
    # continue on to write data

Instantiating DictWriter requires a fieldnames argument.
From the documentation:

The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with statement was added in 2.6. If using 2.5: from __future__ import with_statement

with open(infile,'rb') as fin:
    dr = csv.DictReader(fin, delimiter='\t')

# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    headers = {} 
    for n in dw.fieldnames:
        headers[n] = n
    dw.writerow(headers)
    for row in dr:
        dw.writerow(row)

As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:

with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
    for row in dr:
        dw.writerow(row)

Disable elastic scrolling in Safari

I had solved it on iPad. Try, if it works also on OSX.

body, html { position: fixed; }

Works only if you have content smaller then screen or you are using some layout framework (Angular Material in my case).

In Angular Material it is great, that you will disable over-scroll effect of whole page, but inner sections <md-content> can be still scrollable.

PostgreSQL "DESCRIBE TABLE"

When your table is not part of the default schema, you should write:

\d+ schema_name.table_name

Otherwise, you would get the error saying that "the relation doesn not exist."

How to schedule a stored procedure in MySQL

In order to create a cronjob, follow these steps:

  1. run this command : SET GLOBAL event_scheduler = ON;

  2. If ERROR 1229 (HY000): Variable 'event_scheduler' is a GLOBAL variable and should be set with SET GLOBAL: mportant

It is possible to set the Event Scheduler to DISABLED only at server startup. If event_scheduler is ON or OFF, you cannot set it to DISABLED at runtime. Also, if the Event Scheduler is set to DISABLED at startup, you cannot change the value of event_scheduler at runtime.

To disable the event scheduler, use one of the following two methods:

  1. As a command-line option when starting the server:

    --event-scheduler=DISABLED
    
  2. In the server configuration file (my.cnf, or my.ini on Windows systems): include the line where it will be read by the server (for example, in a [mysqld] section):

    event_scheduler=DISABLED
    

    Read MySQL documentation for more information.

     DROP EVENT IF EXISTS EVENT_NAME;
      CREATE EVENT EVENT_NAME
     ON SCHEDULE EVERY 10 SECOND/minute/hour
     DO
     CALL PROCEDURE_NAME();
    

Get enum values as List of String in Java 8

You can do (pre-Java 8):

List<Enum> enumValues = Arrays.asList(Enum.values());

or

List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));

Using Java 8 features, you can map each constant to its name:

List<String> enumNames = Stream.of(Enum.values())
                               .map(Enum::name)
                               .collect(Collectors.toList());

How to use onClick with divs in React.js

I just needed a simple testing button for react.js. Here is what I did and it worked.

function Testing(){
 var f=function testing(){
         console.log("Testing Mode activated");
         UserData.authenticated=true;
         UserData.userId='123';
       };
 console.log("Testing Mode");

 return (<div><button onClick={f}>testing</button></div>);
}

Is there an easy way to convert Android Application to IPad, IPhone

I'm not sure how helpful this answer is for your current application, but it may prove helpful for the next applications that you will be developing.

As iOS does not use Java like Android, your options are quite limited:

1) if your application is written mostly in C/C++ using JNI, you can write a wrapper and interface it with the iOS (i.e. provide callbacks from iOS to your JNI written function). There may be frameworks out there that help you do this easier, but there's still the problem of integrating the application and adapting it to the framework (and of course the fact that the application has to be written in C/C++).

2) rewrite it for iOS. I don't know whether there are any good companies that do this for you. Also, due to the variety of applications that can be written which can use different services and API, there may not be any software that can port it for you (I guess this kind of software is like a gold mine heh) or do a very good job at that.

3) I think that there are Java->C/C++ converters, but there won't help you at all when it comes to API differences. Also, you may find yourself struggling more to get the converted code working on any of the platforms rather than rewriting your application from scratch for iOS.

The problem depends quite a bit on the services and APIs your application is using. I haven't really look this up, but there may be some APIs that provide certain functionality in Android that iOS doesn't provide.

Using C/C++ and natively compiling it for the desired platform looks like the way to go for Android-iOS-Win7Mobile cross-platform development. This gets you somewhat of an application core/kernel which you can use to do the actual application logic.

As for the OS specific parts (APIs) that your application is using, you'll have to set up communication interfaces between them and your application's core.

Convert string with commas to array

I remove the characters '[',']' and do an split with ','

let array = stringObject.replace('[','').replace(']','').split(",").map(String);

Object of class DateTime could not be converted to string

$Date = $row['Received_date']->format('d/m/Y');

then it cast date object from given in database

Can I define a class name on paragraph using Markdown?

It should also be mentioned that <span> tags allow inside them -- block-level items negate MD natively inside them unless you configure them not to do so, but in-line styles natively allow MD within them. As such, I often do something akin to...

This is a superfluous paragraph thing.

<span class="class-red">And thus I delve into my topic, Lorem ipsum lollipop bubblegum.</span>

And thus with that I conclude.

I am not 100% sure if this is universal but seems to be the case in all MD editors I've used.

C++ deprecated conversion from string constant to 'char*'

A reason for this problem (which is even harder to detect than the issue with char* str = "some string" - which others have explained) is when you are using constexpr.

constexpr char* str = "some string";

It seems that it would behave similar to const char* str, and so would not cause a warning, as it occurs before char*, but it instead behaves as char* const str.

Details

Constant pointer, and pointer to a constant. The difference between const char* str, and char* const str can be explained as follows.

  1. const char* str : Declare str to be a pointer to a const char. This means that the data to which this pointer is pointing to it constant. The pointer can be modified, but any attempt to modify the data would throw a compilation error.
    1. str++ ; : VALID. We are modifying the pointer, and not the data being pointed to.
    2. *str = 'a'; : INVALID. We are trying to modify the data being pointed to.
  2. char* const str : Declare str to be a const pointer to char. This means that point is now constant, but the data being pointed too is not. The pointer cannot be modified but we can modify the data using the pointer.
    1. str++ ; : INVALID. We are trying to modify the pointer variable, which is a constant.
    2. *str = 'a'; : VALID. We are trying to modify the data being pointed to. In our case this will not cause a compilation error, but will cause a runtime error, as the string will most probably will go into a read only section of the compiled binary. This statement would make sense if we had dynamically allocated memory, eg. char* const str = new char[5];.
  3. const char* const str : Declare str to be a const pointer to a const char. In this case we can neither modify the pointer, nor the data being pointed to.
    1. str++ ; : INVALID. We are trying to modify the pointer variable, which is a constant.
    2. *str = 'a'; : INVALID. We are trying to modify the data pointed by this pointer, which is also constant.

In my case the issue was that I was expecting constexpr char* str to behave as const char* str, and not char* const str, since visually it seems closer to the former.

Also, the warning generated for constexpr char* str = "some string" is slightly different from char* str = "some string".

  1. Compiler warning for constexpr char* str = "some string": ISO C++11 does not allow conversion from string literal to 'char *const'
  2. Compiler warning for char* str = "some string": ISO C++11 does not allow conversion from string literal to 'char *'.

Tip

You can use C gibberish ? English converter to convert C declarations to easily understandable English statements, and vice versa. This is a C only tool, and thus wont support things (like constexpr) which are exclusive to C++.

Python: find position of element in array

You should do:

try:
    value_index = my_list.index(value)
except:
    value_index = -1;

How to check edittext's text is email address or not?

Apache Commons Validator can be used as mentioned in the other answers.

Step:1)Download the jar file from here

Step:2)Add it into your project libs

The import:

import org.apache.commons.validator.routines.EmailValidator;

The code:

String email = "[email protected]";
boolean valid = EmailValidator.getInstance().isValid(email);

and to allow local addresses::

boolean allowLocal = true;
boolean valid = EmailValidator.getInstance(allowLocal).isValid(email);

Python list subtraction operation

The other solutions have one of a few problems:

  1. They don't preserve order, or
  2. They don't remove a precise count of elements, e.g. for x = [1, 2, 2, 2] and y = [2, 2] they convert y to a set, and either remove all matching elements (leaving [1] only) or remove one of each unique element (leaving [1, 2, 2]), when the proper behavior would be to remove 2 twice, leaving [1, 2], or
  3. They do O(m * n) work, where an optimal solution can do O(m + n) work

Alain was on the right track with Counter to solve #2 and #3, but that solution will lose ordering. The solution that preserves order (removing the first n copies of each value for n repetitions in the list of values to remove) is:

from collections import Counter

x = [1,2,3,4,3,2,1]  
y = [1,2,2]  
remaining = Counter(y)

out = []
for val in x:
    if remaining[val]:
        remaining[val] -= 1
    else:
        out.append(val)
# out is now [3, 4, 3, 1], having removed the first 1 and both 2s.

Try it online!

To make it remove the last copies of each element, just change the for loop to for val in reversed(x): and add out.reverse() immediately after exiting the for loop.

Constructing the Counter is O(n) in terms of y's length, iterating x is O(n) in terms of x's length, and Counter membership testing and mutation are O(1), while list.append is amortized O(1) (a given append can be O(n), but for many appends, the overall big-O averages O(1) since fewer and fewer of them require a reallocation), so the overall work done is O(m + n).

You can also test for to determine if there were any elements in y that were not removed from x by testing:

remaining = +remaining  # Removes all keys with zero counts from Counter
if remaining:
    # remaining contained elements with non-zero counts

HTML Upload MAX_FILE_SIZE does not appear to work

PHP.net explanation about MAX_FILE_SIZE hidden field.

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.

http://php.net/manual/en/features.file-upload.post-method.php

How to convert a command-line argument to int?

Note that your main arguments are not correct. The standard form should be:

int main(int argc, char *argv[])

or equivalently:

int main(int argc, char **argv)

There are many ways to achieve the conversion. This is one approach:

#include <sstream>

int main(int argc, char *argv[])
{
    if (argc >= 2)
    {
        std::istringstream iss( argv[1] );
        int val;

        if (iss >> val)
        {
            // Conversion successful
        }
    }

    return 0;
}

PHP code is not being executed, instead code shows on the page

This just happened to me again, along with the server downloading html files, rather than processing. I had not use the webserver apache for some time on the computer and meanwhile Ubuntu updated like two more versions from originally installed LTS. Now it is

$ cat /etc/issue
Ubuntu 16.04 LTS

So the php worked after like so:

$ sudo apt-get install lamp-server^
$ sudo a2enmod php7.0
$ sudo service apache2 restart 

The webserver was now parsing the php. Maybe now got to update some webs since php7.0 now running where as it was before running php5. Oh well.

Flexbox: 4 items per row

Hope it helps. for more detail you can follow this Link

_x000D_
_x000D_
.parent{ 
  display: flex; 
  flex-wrap: wrap; 
}

.parent .child{ 
  flex: 1 1 25%;
  /*Start Run Code Snippet output CSS*/
  padding: 5px; 
  box-sizing: border-box;
  text-align: center;
  border: 1px solid #000;
  /*End Run Code Snippet output CSS*/
}
_x000D_
<div class="parent">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
  <div class="child">5</div>
  <div class="child">6</div>
  <div class="child">7</div>
  <div class="child">8</div>
</div>
_x000D_
_x000D_
_x000D_

How to replace a char in string with an Empty character in C#.NET

It always bothered me that I can't use the String.Remove method to get rid of instances of a string or character in a string so I usually add theses extension methods to my code base:

public static class StringExtensions
{
    public static string Remove(this string str, string toBeRemoved)
    {
        return str.Replace(toBeRemoved, "");
    }

    public static string RemoveChar(this string str, char toBeRemoved)
    {
        return str.Replace(toBeRemoved.ToString(), "");

    }
}

The one taking char can't use overload semantics unfortunately since it will resolve to string.Remove(int startIndex) since it is "closer"

This is of course purely esthetics, but I like it...

JAVA_HOME does not point to the JDK

Execute:

$ export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-3.b16.el6_9.x86_64

and set operating system environment:

vi /etc/environment

Then follow these steps:

  1. Press i
  2. Paste

    JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-3.b16.el6_9.x86_64
    
  3. Press esc

  4. Press :wq

How do I use the Tensorboard callback of Keras?

Create the Tensorboard callback:

from keras.callbacks import TensorBoard
from datetime import datetime
logDir = "./Graph/" + datetime.now().strftime("%Y%m%d-%H%M%S") + "/"
tb = TensorBoard(log_dir=logDir, histogram_freq=2, write_graph=True, write_images=True, write_grads=True)

Pass the Tensorboard callback to the fit call:

history = model.fit(X_train, y_train, epochs=200, callbacks=[tb])

When running the model, if you get a Keras error of

"You must feed a value for placeholder tensor"

try reseting the Keras session before the model creation by doing:

import keras.backend as K
K.clear_session()

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

You can convert the value to a date using a formula like this, next to the cell:

=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))

Where A1 is the field you need to convert.

Alternatively, you could use this code in VBA:

Sub ConvertYYYYMMDDToDate()
   Dim c As Range
   For Each c In Selection.Cells
       c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
       'Following line added only to enforce the format.
       c.NumberFormat = "mm/dd/yyyy"
   Next
End Sub

Just highlight any cells you want fixed and run the code.

Note as RJohnson mentioned in the comments, this code will error if one of your selected cells is empty. You can add a condition on c.value to skip the update if it is blank.

What's your most controversial programming opinion?

New web projects should consider not using Java.

I've been using Java to do web development for over 10 years now. At first, it was a step in the right direction compared to the available alternatives. Now, there are better alternatives than Java.

This is really just a specific case of the magic hammer approach to problem solving, but it's one that's really painful.

How to save a spark DataFrame as csv on disk?

Apache Spark does not support native CSV output on disk.

You have four available solutions though:

  1. You can convert your Dataframe into an RDD :

    def convertToReadableString(r : Row) = ???
    df.rdd.map{ convertToReadableString }.saveAsTextFile(filepath)
    

    This will create a folder filepath. Under the file path, you'll find partitions files (e.g part-000*)

    What I usually do if I want to append all the partitions into a big CSV is

    cat filePath/part* > mycsvfile.csv
    

    Some will use coalesce(1,false) to create one partition from the RDD. It's usually a bad practice, since it may overwhelm the driver by pulling all the data you are collecting to it.

    Note that df.rdd will return an RDD[Row].

  2. With Spark <2, you can use databricks spark-csv library:

    • Spark 1.4+:

      df.write.format("com.databricks.spark.csv").save(filepath)
      
    • Spark 1.3:

      df.save(filepath,"com.databricks.spark.csv")
      
  3. With Spark 2.x the spark-csv package is not needed as it's included in Spark.

    df.write.format("csv").save(filepath)
    
  4. You can convert to local Pandas data frame and use to_csv method (PySpark only).

Note: Solutions 1, 2 and 3 will result in CSV format files (part-*) generated by the underlying Hadoop API that Spark calls when you invoke save. You will have one part- file per partition.

angular.service vs angular.factory

The clue is in the name

Services and factories are similar to one another. Both will yield a singleton object that can be injected into other objects, and so are often used interchangeably.

They are intended to be used semantically to implement different design patterns.

Services are for implementing a service pattern

A service pattern is one in which your application is broken into logically consistent units of functionality. An example might be an API accessor, or a set of business logic.

This is especially important in Angular because Angular models are typically just JSON objects pulled from a server, and so we need somewhere to put our business logic.

Here is a Github service for example. It knows how to talk to Github. It knows about urls and methods. We can inject it into a controller, and it will generate and return a promise.

(function() {
  var base = "https://api.github.com";

  angular.module('github', [])
    .service('githubService', function( $http ) {
      this.getEvents: function() {
        var url = [
          base,
          '/events',
          '?callback=JSON_CALLBACK'
        ].join('');
        return $http.jsonp(url);
      }
    });
  )();

Factories implement a factory pattern

Factories, on the other hand are intended to implement a factory pattern. A factory pattern in one in which we use a factory function to generate an object. Typically we might use this for building models. Here is a factory which returns an Author constructor:

angular.module('user', [])
  .factory('User', function($resource) {
    var url = 'http://simple-api.herokuapp.com/api/v1/authors/:id'
    return $resource(url);
  })

We would make use of this like so:

angular.module('app', ['user'])
  .controller('authorController', function($scope, User) {
    $scope.user = new User();
  })

Note that factories also return singletons.

Factories can return a constructor

Because a factory simply returns an object, it can return any type of object you like, including a constructor function, as we see above.

Factories return an object; services are newable

Another technical difference is in the way services and factories are composed. A service function will be newed to generate the object. A factory function will be called and will return the object.

  • Services are newable constructors.
  • Factories are simply called and return an object.

This means that in a service, we append to "this" which, in the context of a constructor, will point to the object under construction.

To illustrate this, here is the same simple object created using a service and a factory:

angular.module('app', [])
  .service('helloService', function() {
    this.sayHello = function() {
      return "Hello!";
    }
  })
  .factory('helloFactory', function() {
    return {
      sayHello: function() {
        return "Hello!";
      }
    }
  });

How can I create an observable with a delay

import * as Rx from 'rxjs/Rx';

We should add the above import to make the blow code to work

Let obs = Rx.Observable
    .interval(1000).take(3);

obs.subscribe(value => console.log('Subscriber: ' + value));

Dependency Injection vs Factory Pattern

i believe that DI is a way of configurings or instantianting a bean. The DI can be done in many ways like constructor, setter-getter etc.

Factory pattern is just another way of instantiating beans. this pattern will be used mainly when you have to create objects using factory design pattern,because while using this pattern you dont configure the properties of a bean, only instantiate the object.

Check this link :Dependency Injection

C++ IDE for Linux?

I really suggest codeblocks. It's not as heavy as Eclipse and it's got Visual Studio project support.

Is it possible to append Series to rows of DataFrame without making a list first?

Convert the series to a dataframe and transpose it, then append normally.

srs = srs.to_frame().T
df = df.append(srs)

One-liner if statements, how to convert this if-else-statement

return (expression) ? value1 : value2;

If value1 and value2 are actually true and false like in your example, you may as well just

return expression;

VBoxManage: error: Failed to create the host-only adapter

Sometimes this can be fixed by provisioning the box on vagrant up

vagrant up --provision

Determine device (iPhone, iPod Touch) with iOS

You can use the UIDevice class like this:

NSString *deviceType = [UIDevice currentDevice].model;

if([deviceType isEqualToString:@"iPhone"])
    // it's an iPhone

How to make a div have a fixed size?

<div class="ai">a b c d e f</div> // something like ~100px
<div class="ai">a b c d e</div> // ~80
<div class="ai">a b c d</div> // ~60 

<script>

function _reWidthAll_div(classname) {

var _maxwidth = 0;

    $(classname).each(function(){

    var _width = $(this).width();

    _maxwidth = (_width >= _maxwidth) ? _width : _maxwidth; // define max width
    });    

$(classname).width(_maxwidth); // return all div same width

}

_reWidthAll_div('.ai');

</script>

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

The storage engine (MyISAM) DOES support repair table. You should be able to repair it.

If the repair fails then it's a sign that the table is very corrupted, you have no choice but to restore it from backups.

If you have other systems (e.g. non-production with same software versions and schema) with an identical table then you might be able to fix it with some hackery (copying the frm an MYI files, followed by a repair).

In essence, the trick is to avoid getting broken tables in the first place. This means always shutting your db down cleanly, never having it crash and never having hardware or power problems. In practice this isn't very likely, so if durability matters you may want to consider a more crash-safe storage engine.

How to get character array from a string?

One possibility is the next:

console.log([1, 2, 3].map(e => Math.random().toString(36).slice(2)).join('').split('').map(e => Math.random() > 0.5 ? e.toUpperCase() : e).join(''));

How To Launch Git Bash from DOS Command Line?

I prefer, putting git in environment variable and just calling

c:\Users\[myname]>sh
or 
c:\Users\[myname]>bash

Steps to create Environment variable (Win7)

  • From the desktop, right click the Computer icon.
  • Choose Properties from the context menu.
  • Click the Advanced system settings link.
  • Click Environment Variables.
  • In the section User variables, hit button NEW, put variable name as GIT_HOME, value as (folder-where-you-installed-git).

    • for me it is was c:\tools\git, others maybe have C:\Program Files\Git
  • find the PATH environment variable and select it. Click Edit. (If the PATH environment variable does not exist, click New).

  • In the Edit window, add a new value %GIT_HOME% and %GIT_HOME%\bin. Click OK. Close all remaining windows by clicking OK.
  • [Make sure you close the CMD which you want use for git]
  • open new Command prompt, and just type sh or bash or git-bash

How to make asynchronous HTTP requests in PHP

If you control the target that you want to call asynchronously (e.g. your own "longtask.php"), you can close the connection from that end, and both scripts will run in parallel. It works like this:

  1. quick.php opens longtask.php via cURL (no magic here)
  2. longtask.php closes the connection and continues (magic!)
  3. cURL returns to quick.php when the connection is closed
  4. Both tasks continue in parallel

I have tried this, and it works just fine. But quick.php won't know anything about how longtask.php is doing, unless you create some means of communication between the processes.

Try this code in longtask.php, before you do anything else. It will close the connection, but still continue to run (and suppress any output):

while(ob_get_level()) ob_end_clean();
header('Connection: close');
ignore_user_abort();
ob_start();
echo('Connection Closed');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();

The code is copied from the PHP manual's user contributed notes and somewhat improved.

jQuery select element in parent window

I came across the same problem but, as stated above, the accepted solution did not work for me.

If you're inside a frame or iframe element, an alternative solution is to use

window.parent.$('#testdiv');

Here's a quick explanation of the differences between window.opener, window.parent and window.top:

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a frame or iframe element

String "true" and "false" to boolean

You could add to the String class to have the method of to_boolean. Then you could do 'true'.to_boolean or '1'.to_boolean

class String
  def to_boolean
    self == 'true' || self == '1'
  end
end

How do you detect the clearing of a "search" HTML5 input?

I know this is an old question, but I was looking for the similar thing. Determine when the 'X' was clicked to clear the search box. None of the answers here helped me at all. One was close but also affected when the user hit the 'enter' button, it would fire the same result as clicking the 'X'.

I found this answer on another post and it works perfect for me and only fires when the user clears the search box.

$("input").bind("mouseup", function(e){
   var $input = $(this),
   oldValue = $input.val();

   if (oldValue == "") return;

   // When this event is fired after clicking on the clear button
   // the value is not cleared yet. We have to wait for it.
   setTimeout(function(){
     var newValue = $input.val();

      if (newValue == ""){
         // capture the clear
         $input.trigger("cleared");
      }
    }, 1);
});

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

What is it exactly a BLOB in a DBMS context

They are binary large objects, you can use them to store binary data such as images or serialized objects among other things.

How can I show three columns per row?

This may be what you are looking for:

http://jsfiddle.net/L4L67/

_x000D_
_x000D_
body>div {_x000D_
  background: #aaa;_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
body>div>div {_x000D_
  flex-grow: 1;_x000D_
  width: 33%;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(even) {_x000D_
  background: #23a;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(odd) {_x000D_
  background: #49b;_x000D_
}
_x000D_
<div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to throw std::exceptions with variable messages?

The following class might come quite handy:

struct Error : std::exception
{
    char text[1000];

    Error(char const* fmt, ...) __attribute__((format(printf,2,3))) {
        va_list ap;
        va_start(ap, fmt);
        vsnprintf(text, sizeof text, fmt, ap);
        va_end(ap);
    }

    char const* what() const throw() { return text; }
};

Usage example:

throw Error("Could not load config file '%s'", configfile.c_str());

logout and redirecting session in php

The simplest way to log out and redirect back to the login or index:

<?php
    if (!isset($_SESSION)) { session_start(); }
    $_SESSION = array(); 
    session_destroy(); 
    header("Location: login.php"); // Or wherever you want to redirect
    exit();
?>

How do you import a large MS SQL .sql file?

Your question is quite similar to this one

You can save your file/script as .txt or .sql and run it from Sql Server Management Studio (I think the menu is Open/Query, then just run the query in the SSMS interface). You migh have to update the first line, indicating the database to be created or selected on your local machine.

If you have to do this data transfer very often, you could then go for replication. Depending on your needs, snapshot replication could be ok. If you have to synch the data between your two servers, you could go for a more complex model such as merge replication.

EDIT: I didn't notice that you had problems with SSMS linked to file size. Then you can go for command-line, as proposed by others, snapshot replication (publish on your main server, subscribe on your local one, replicate, then unsubscribe) or even backup/restore

Any way to select without causing locking in MySQL?

Depending on your table type, locking will perform differently, but so will a SELECT count. For MyISAM tables a simple SELECT count(*) FROM table should not lock the table since it accesses meta data to pull the record count. Innodb will take longer since it has to grab the table in a snapshot to count the records, but it shouldn't cause locking.

You should at least have concurrent_insert set to 1 (default). Then, if there are no "gaps" in the data file for the table to fill, inserts will be appended to the file and SELECT and INSERTs can happen simultaneously with MyISAM tables. Note that deleting a record puts a "gap" in the data file which will attempt to be filled with future inserts and updates.

If you rarely delete records, then you can set concurrent_insert equal to 2, and inserts will always be added to the end of the data file. Then selects and inserts can happen simultaneously, but your data file will never get smaller, no matter how many records you delete (except all records).

The bottom line, if you have a lot of updates, inserts and selects on a table, you should make it InnoDB. You can freely mix table types in a system though.

How to activate "Share" button in android app?

in kotlin :

val sharingIntent = Intent(android.content.Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
val shareBody = "Application Link : https://play.google.com/store/apps/details?id=${App.context.getPackageName()}"
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "App link")
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody)
startActivity(Intent.createChooser(sharingIntent, "Share App Link Via :"))

Regular expression to find URLs within a string

text = """The link of this question: https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string
Also there are some urls: www.google.com, facebook.com, http://test.com/method?param=wasd, http://test.com/method?param=wasd&params2=kjhdkjshd
The code below catches all urls in text and returns urls in list."""

urls = re.findall('(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-&?=%.]+', text)
print(urls)

Output:

[
    'https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string', 
    'www.google.com', 
    'facebook.com',
    'http://test.com/method?param=wasd',
    'http://test.com/method?param=wasd&params2=kjhdkjshd'
]

Is there any advantage of using map over unordered_map in case of trivial keys?

Significant differences that have not really been adequately mentioned here:

  • map keeps iterators to all elements stable, in C++17 you can even move elements from one map to the other without invalidating iterators to them (and if properly implemented without any potential allocation).
  • map timings for single operations are typically more consistent since they never need large allocations.
  • unordered_map using std::hash as implemented in the libstdc++ is vulnerable to DoS if fed with untrusted input (it uses MurmurHash2 with a constant seed - not that seeding would really help, see https://emboss.github.io/blog/2012/12/14/breaking-murmur-hash-flooding-dos-reloaded/).
  • Being ordered enables efficient range searches, e.g. iterate over all elements with key = 42.

setTimeout or setInterval?

The setInterval makes it easier to cancel future execution of your code. If you use setTimeout, you must keep track of the timer id in case you wish to cancel it later on.

var timerId = null;
function myTimeoutFunction()
{
    doStuff();
    timerId = setTimeout(myTimeoutFunction, 1000);
}

myTimeoutFunction();

// later on...
clearTimeout(timerId);

versus

function myTimeoutFunction()
{
    doStuff();
}

myTimeoutFunction();
var timerId = setInterval(myTimeoutFunction, 1000);

// later on...
clearInterval(timerId);

An error occurred while updating the entries. See the inner exception for details

Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.

enter image description here

Getting results between two dates in PostgreSQL

SELECT *
FROM ecs_table
WHERE (start_date, end_date) OVERLAPS ('2012-01-01'::DATE, '2012-04-12'::DATE + interval '1');

How to check type of object in Python?

use isinstance(v, type_name) or type(v) is type_name or type(v) == type_name,

where type_name can be one of the following:

  • None
  • bool
  • int
  • float
  • complex
  • str
  • list
  • tuple
  • set
  • dict

and, of course,

  • custom types (classes)

How to get the list of properties of a class?

public List<string> GetPropertiesNameOfClass(object pObject)
{
    List<string> propertyList = new List<string>();
    if (pObject != null)
    {
        foreach (var prop in pObject.GetType().GetProperties())
        {
            propertyList.Add(prop.Name);
        }
    }
    return propertyList;
}

This function is for getting list of Class Properties.

parent & child with position fixed, parent overflow:hidden bug

Fixed position elements are positioned relative to the browser window, so the parent element is basically irrelevant.

To get the effect you want, where the overflow on the parent clips the child, use position: absolute instead: http://jsfiddle.net/DBHUv/1/

How do you install Boost on MacOS?

Unless your compiler is different than the one supplied with the Mac XCode Dev tools, just follow the instructions in section 5.1 of Getting Started Guide for Unix Variants. The configuration and building of the latest source couldn't be easier, and it took all about about 1 minute to configure and 10 minutes to compile.

Const in JavaScript: when to use it and is it necessary?

You have great answers, but let's keep it simple.

const should be used when you have a defined constant (read as: it won't change during your program execution).

For example:

const pi = 3.1415926535

If you think that it is something that may be changed on later execution then use a var.

The practical difference, based on the example, is that with const you will always asume that pi will be 3.14[...], it's a fact.

If you define it as a var, it might be 3.14[...] or not.

For a more technical answer @Tibos is academically right.

how to prevent css inherit

lets say you have this:

<ul>
    <li></li>
    <li>
        <ul>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li></li>
<ul>

Now if you DONT need IE6 compatibility (reference at Quirksmode) you can have the following css

ul li { background:#fff; }
ul>li { background:#f0f; }

The > is a direct children operator, so in this case only the first level of lis will be purple.

Hope this helps

to remove first and last element in array

_x000D_
_x000D_
var fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
var newFruits = fruits.slice(1, -1);_x000D_
console.log(newFruits); //  ["Orange", "Apple"];
_x000D_
_x000D_
_x000D_

Here, -1 denotes the last element in an array and 1 denotes the second element.

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

How to debug in Django, the good way?

There are a bunch of ways to do it, but the most straightforward is to simply use the Python debugger. Just add following line in to a Django view function:

import pdb; pdb.set_trace()

or

breakpoint()  #from Python3.7

If you try to load that page in your browser, the browser will hang and you get a prompt to carry on debugging on actual executing code.

However there are other options (I am not recommending them):

* return HttpResponse({variable to inspect})

* print {variable to inspect}

* raise Exception({variable to inspect})

But the Python Debugger (pdb) is highly recommended for all types of Python code. If you are already into pdb, you'd also want to have a look at IPDB that uses ipython for debugging.

Some more useful extension to pdb are

pdb++, suggested by Antash.

pudb, suggested by PatDuJour.

Using the Python debugger in Django, suggested by Seafangs.

Excel plot time series frequency with continuous xaxis

I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog

Non-uniformly distributed data can be plotted in excel in

  • X Y (Scatter Plots)
  • Linear plots with Date axis
    • These don't take time into account, only days.
    • This method is quite cumbersome as it requires translating your time units to days, months, or years.. then change the axis labels... Not Recommended

Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.

1- Add the center point to your data series

+---------------+-------+------+
|    Time       | Time  | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 |  12  |
| 09:00 - 10:00 | 09:30 |  13  |
| 10:00 - 11:00 | 10:30 |  10  |
| 13:00 - 14:00 | 13:30 |   5  |
| 14:00 - 15:00 | 14:30 |  14  |
+---------------+-------+------+

2- Create a Scatter Plot

3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:

  • Minimum : Fix : 0.33333
  • Maximum : Fix : 0.625
  • Major unit : Fix : 0.041667

Line Scatter Plot


Alternative Display:

Make the points turn into columns:

To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.

1- You're going to need to add several rows where we draw the line and disjoint the data

+-------+------+
| Time  | Freq |
+-------+------+
| 08:30 |   0  |
| 08:30 |  12  |
|       |      |
| 09:30 |   0  |
| 09:30 |  13  |
|       |      |
| 10:30 |   0  |
| 10:30 |  10  |
|       |      |
| 13:30 |   0  |
| 13:30 |   5  |
|       |      |
| 14:30 |   0  |
| 14:30 |  14  |
+-------+------+

2- Plot an X Y (Scatter) Chart with Lines.

3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.

Bar-Line Scatter Plot

How can I hide a checkbox in html?

input may have a hidden attribute:

_x000D_
_x000D_
input:checked + span::before {
  content: 'un';
}
_x000D_
<label>
  <input type='checkbox' hidden/>
  <span>check</span>
<label>
_x000D_
_x000D_
_x000D_

Two column div layout with fluid left and fixed right column

CSS Solutuion

#left{
    float:right;
    width:200px;
    height:500px;
    background:red;   
}

#right{
    margin-right: 200px;
    height:500px;
    background:blue;
}

Check working example at http://jsfiddle.net/NP4vb/3/

jQuery Solution

var parentw = $('#parent').width();
var rightw = $('#right').width();
$('#left').width(parentw - rightw);

Check working example http://jsfiddle.net/NP4vb/

Changing the selected option of an HTML Select element

You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:

document.getElementById('sel').value = 'bike';??????????

DEMO

How to write file in UTF-8 format?

On Unix/Linux a simple shell command could be used alternatively to convert all files from a given directory:

 recode L1..UTF8 dir/*

Could be started via PHPs exec() as well.

Convert hex string to int in Python

Convert hex string to int in Python

I may have it as "0xffff" or just "ffff".

To convert a string to an int, pass the string to int along with the base you are converting from.

Both strings will suffice for conversion in this way:

>>> string_1 = "0xffff"
>>> string_2 = "ffff"
>>> int(string_1, 16)
65535
>>> int(string_2, 16)
65535

Letting int infer

If you pass 0 as the base, int will infer the base from the prefix in the string.

>>> int(string_1, 0)
65535

Without the hexadecimal prefix, 0x, int does not have enough information with which to guess:

>>> int(string_2, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: 'ffff'

literals:

If you're typing into source code or an interpreter, Python will make the conversion for you:

>>> integer = 0xffff
>>> integer
65535

This won't work with ffff because Python will think you're trying to write a legitimate Python name instead:

>>> integer = ffff
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ffff' is not defined

Python numbers start with a numeric character, while Python names cannot start with a numeric character.

Plotting a list of (x, y) coordinates in python matplotlib

If you have a numpy array you can do this:

import numpy as np
from matplotlib import pyplot as plt

data = np.array([
    [1, 2],
    [2, 3],
    [3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()

Background images: how to fill whole div if image is small and vice versa

To automatically enlarge the image and cover the entire div section without leaving any part of it unfilled, use:

background-size: cover;

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

How to set radio button selected value using jquery

  <asp:RadioButtonList ID="rblRequestType">
        <asp:ListItem Selected="True" Value="value1">Value1</asp:ListItem>
        <asp:ListItem Value="Value2">Value2</asp:ListItem>
  </asp:RadioButtonList>

You can set checked like this.

var radio0 = $("#rblRequestType_0");
var radio1 = $("#rblRequestType_1");

radio0.checked = true;
radio1.checked = true;

How to speed up insertion performance in PostgreSQL

If you happend to insert colums with UUIDs (which is not exactly your case) and to add to @Dennis answer (I can't comment yet), be advise than using gen_random_uuid() (requires PG 9.4 and pgcrypto module) is (a lot) faster than uuid_generate_v4()

=# explain analyze select uuid_generate_v4(),* from generate_series(1,10000);
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=11.674..10304.959 rows=10000 loops=1)
 Planning time: 0.157 ms
 Execution time: 13353.098 ms
(3 filas)

vs


=# explain analyze select gen_random_uuid(),* from generate_series(1,10000);
                                                        QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=252.274..418.137 rows=10000 loops=1)
 Planning time: 0.064 ms
 Execution time: 503.818 ms
(3 filas)

Also, it's the suggested official way to do it

Note

If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead.

This droped insert time from ~2 hours to ~10 minutes for 3.7M of rows.

ReadFile in Base64 Nodejs

I think that the following example demonstrates what you need:http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html

The essence of the article is this code part:

var fs = require('fs');

// function to encode file data to base64 encoded string
function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

// function to create file from base64 encoded string
function base64_decode(base64str, file) {
    // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
    var bitmap = new Buffer(base64str, 'base64');
    // write buffer to file
    fs.writeFileSync(file, bitmap);
    console.log('******** File created from base64 encoded string ********');
}

// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image 
base64_decode(base64str, 'copy.jpg');

Format certain floating dataframe columns into percentage in pandas

replace the values using the round function, and format the string representation of the percentage numbers:

df['var2'] = pd.Series([round(val, 2) for val in df['var2']], index = df.index)
df['var3'] = pd.Series(["{0:.2f}%".format(val * 100) for val in df['var3']], index = df.index)

The round function rounds a floating point number to the number of decimal places provided as second argument to the function.

String formatting allows you to represent the numbers as you wish. You can change the number of decimal places shown by changing the number before the f.

p.s. I was not sure if your 'percentage' numbers had already been multiplied by 100. If they have then clearly you will want to change the number of decimals displayed, and remove the hundred multiplication.

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

The simple thing you need to do is to close your Visual Studio environment and open it again by using 'Run as administrator'. It should now run successfully.

How do I correctly upgrade angular 2 (npm) to the latest version?

Best way to do is use the extension(pflannery.vscode-versionlens) in vscode.

this checks for all satisfy and checks for best fit.

i had lot of issues with updating and keeping my app functioining unitll i let verbose lense did the check and then i run

npm i

to install newly suggested dependencies.

In Node.js, how do I turn a string to a json?

use the JSON function >

JSON.parse(theString)

Is it possible to add dynamically named properties to JavaScript object?

Yes it is possible. Assuming:

var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};
var propertyName = "someProperty";
var propertyValue = "someValue";

Either:

data[propertyName] = propertyValue;

or

eval("data." + propertyName + " = '" + propertyValue + "'");

The first method is preferred. eval() has the obvious security concerns if you're using values supplied by the user so don't use it if you can avoid it but it's worth knowing it exists and what it can do.

You can reference this with:

alert(data.someProperty);

or

data(data["someProperty"]);

or

alert(data[propertyName]);

Understanding the map function

The map() function is there to apply the same procedure to every item in an iterable data structure, like lists, generators, strings, and other stuff.

Let's look at an example: map() can iterate over every item in a list and apply a function to each item, than it will return (give you back) the new list.

Imagine you have a function that takes a number, adds 1 to that number and returns it:

def add_one(num):
  new_num = num + 1
  return new_num

You also have a list of numbers:

my_list = [1, 3, 6, 7, 8, 10]

if you want to increment every number in the list, you can do the following:

>>> map(add_one, my_list)
[2, 4, 7, 8, 9, 11]

Note: At minimum map() needs two arguments. First a function name and second something like a list.

Let's see some other cool things map() can do. map() can take multiple iterables (lists, strings, etc.) and pass an element from each iterable to a function as an argument.

We have three lists:

list_one = [1, 2, 3, 4, 5]
list_two = [11, 12, 13, 14, 15]
list_three = [21, 22, 23, 24, 25]

map() can make you a new list that holds the addition of elements at a specific index.

Now remember map(), needs a function. This time we'll use the builtin sum() function. Running map() gives the following result:

>>> map(sum, list_one, list_two, list_three)
[33, 36, 39, 42, 45]

REMEMBER:
In Python 2 map(), will iterate (go through the elements of the lists) according to the longest list, and pass None to the function for the shorter lists, so your function should look for None and handle them, otherwise you will get errors. In Python 3 map() will stop after finishing with the shortest list. Also, in Python 3, map() returns an iterator, not a list.

TypeError: argument of type 'NoneType' is not iterable

If a function does not return anything, e.g.:

def test():
    pass

it has an implicit return value of None.

Thus, as your pick* methods do not return anything, e.g.:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")

the lines that call them, e.g.:

word = pickEasy()

set word to None, so wordInput in getInput is None. This means that:

if guess in wordInput:

is the equivalent of:

if guess in None:

and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

The fix is to add the return type:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

CSS force new line

Use <br /> OR <br> -

<li>Post by<br /><a>Author</a></li>

OR

<li>Post by<br><a>Author</a></li>

or

make the a element display:block;

<li>Post by <a style="display:block;">Author</a></li>

Try

Easy way to pull latest of all git submodules

From the top level in the repo:

git submodule foreach git checkout develop
git submodule foreach git pull

This will switch all branches to develop and pull latest

What is the difference between Jupyter Notebook and JupyterLab?

This answer shows the python perspective. Jupyter supports various languages besides python.

Both Jupyter Notebook and Jupyterlab are browser compatible interactive python (i.e. python ".ipynb" files) environments, where you can divide the various portions of the code into various individually executable cells for the sake of better readability. Both of these are popular in Data Science/Scientific Computing domain.

I'd suggest you to go with Jupyterlab for the advantages over Jupyter notebooks:

  1. In Jupyterlab, you can create ".py" files, ".ipynb" files, open terminal etc. Jupyter Notebook allows ".ipynb" files while providing you the choice to choose "python 2" or "python 3".
  2. Jupyterlab can open multiple ".ipynb" files inside a single browser tab. Whereas, Jupyter Notebook will create new tab to open new ".ipynb" files every time. Hovering between various tabs of browser is tedious, thus Jupyterlab is more helpful here.

I'd recommend using PIP to install Jupyterlab.

If you can't open a ".ipynb" file using Jupyterlab on Windows system, here are the steps:

  1. Go to the file --> Right click --> Open With --> Choose another app --> More Apps --> Look for another apps on this PC --> Click.
  2. This will open a file explorer window. Now go inside your Python installation folder. You should see Scripts folder. Go inside it.
  3. Once you find jupyter-lab.exe, select that and now it will open the .ipynb files by default on your PC.

Does bootstrap have builtin padding and margin classes?

Bootstrap 5 has changed the ml,mr,pl,pr classes, which no longer work if you're upgrading from a lower version. The l and r have now been replaced with s(...which is confusing) and e(east?) respectively.

From bootstrap website:

Where property is one of:

  • m - for classes that set margin
  • p - for classes that set padding

Where sides is one of:

  • t - for classes that set margin-top or padding-top
  • b - for classes that set margin-bottom or padding-bottom
  • s - for classes that set margin-left or padding-left in LTR, margin-right or padding-right in RTL
  • e - for classes that set margin-right or padding-right in LTR, margin-left or padding-left in RTL
  • x - for classes that set both *-left and *-right
  • y - for classes that set both *-top and *-bottom blank - for classes that set a margin or padding on all 4 sides of the element Where size is one of:

0 - for classes that eliminate the margin or padding by setting it to 0 1 - (by default) for classes that set the margin or padding to $spacer * .25 2 - (by default) for classes that set the margin or padding to $spacer * .5 3 - (by default) for classes that set the margin or padding to $spacer 4 - (by default) for classes that set the margin or padding to $spacer * 1.5 5 - (by default) for classes that set the margin or padding to $spacer * 3 auto - for classes that set the margin to auto (You can add more sizes by adding entries to the $spacers Sass map variable.)

Datepicker: How to popup datepicker when click on edittext

Using DataBinding:

<EditText
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:focusable="false"
  android:onClick="@{() -> viewModel.onDateEditTextClicked()}"
  android:hint="@string/hint_date"
  android:imeOptions="actionDone"
  android:inputType="none"
  android:maxLines="1"
  android:text="@={viewModel.filterDate}" />

(see focusable, inputType and onClick)

Inside ViewModel:

public void onDateEditTextClicked() {
    // do something
}

Eclipse IDE: How to zoom in on text?

Here's a quicker way than multi-layer menus without resorting to plug-ins:

Use the Quick Access tool at the upper left corner.

Type in "font", then, from the list that drops down, click on the link for "Preferences->Colors and Fonts->General->Appearance".

One click replaces the 4 needed to get there through menus. I do it so often, my Quick Access tool pulls it up as a previous choice right at the top of the list so I can just type "font" with a tap on the enter key and Boom!, I'm there.

If you want a keyboard shortcut, Ctrl+3 sets the focus to the Quick Access tool. Better yet, this even automatically brings up a list with your previous choices. The last one you chose will be on top, in which case a simple Ctrl+3 followed by enter would bring you straight there! I use this all the time to make it bigger during long typing or reading sessions to ease eye strain, or to make it smaller if I need more text on the screen at one time to make it easier to find something.

It's not quite as nice as zooming with the scroll wheel, but it's a lot better than navigating through the menus every time!

jQuery delete all table rows except first

To Remove all rows, except the first one (except header), use the below code:

$("#dataTable tr:gt(1)").remove();

How to print variables in Perl

How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids, but Perl complains.

Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open returned an error, and make sure you are using use strict; use warnings;.

my ($ids, $nIds) is a list, right? With two elements?

It's a (very special) function call. $ids,$nIds is a list with two elements.

What is a magic number, and why is it bad?

A magic number is a direct usage of a number in the code.

For example, if you have (in Java):

public class Foo {
    public void setPassword(String password) {
         // don't do this
         if (password.length() > 7) {
              throw new InvalidArgumentException("password");
         }
    }
}

This should be refactored to:

public class Foo {
    public static final int MAX_PASSWORD_SIZE = 7;

    public void setPassword(String password) {
         if (password.length() > MAX_PASSWORD_SIZE) {
              throw new InvalidArgumentException("password");
         }
    }
}

It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.

The JDK is full of examples like in Integer, Character and Math classes.

PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.

Android splash screen image sizes to fit all devices

Based off this answer from Lucas Cerro I calculated the dimensions using the ratios in the Android docs, using the baseline in the answer. I hope this helps someone else coming to this post!

  • xxxlarge (xxxhdpi): 1280x1920 (4.0x)
  • xxlarge (xxhdpi): 960x1440 (3.0x)
  • xlarge (xhdpi): 640x960 (2.0x)
  • large (hdpi): 480x800 (1.5x)
  • medium (mdpi): 320x480 (1.0x baseline)
  • small (ldpi): 240x320 (0.75x) 

T-SQL Subquery Max(Date) and Joins

Join on the prices table, and then select the entry for the last day:

select pa.partid, pa.Partnumber, max(pr.price)
from myparts pa
inner join myprices pr on pr.partid = pa.partid
where pr.PriceDate = (
    select max(PriceDate) 
    from myprices 
    where partid = pa.partid
)

The max() is in case there are multiple prices per day; I'm assuming you'd like to display the highest one. If your price table has an id column, you can avoid the max() and simplify like:

select pa.partid, pa.Partnumber, pr.price
from myparts pa
inner join myprices pr on pr.partid = pa.partid
where pr.priceid = (
    select max(priceid)
    from myprices 
    where partid = pa.partid
)

P.S. Use wcm's solution instead!

Shortcut for creating single item list in C#

For a single item enumerable in java it would be Collections.singleton("string");

In c# this is going to be more efficient than a new List:

public class SingleEnumerator<T> : IEnumerable<T>
{
    private readonly T m_Value;

    public SingleEnumerator(T value)
    {
        m_Value = value;
    }

    public IEnumerator<T> GetEnumerator()
    {
        yield return m_Value;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        yield return m_Value;
    }
}

but is there a simpler way using the framework?

JavaScript equivalent of PHP’s die

You can simply use the return; example

$(document).ready(function () {
        alert(1);
        return;
        alert(2);
        alert(3);
        alert(4);
});

The return will return to the main caller function test1(); and continue from there to test3();

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type="text/javascript">
function test1(){
    test2();
    test3();
}

function test2(){
    alert(2);
    return;
    test4();
    test5();
}

function test3(){
    alert(3);
}

function test4(){
    alert(4);
}

function test5(){
    alert(5);
}
test1();

</script>
</body>
</html>

but if you just add throw ''; this will completely stop the execution without causing any errors.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type="text/javascript">
function test1(){
    test2();
    test3();
}

function test2(){
    alert(2);
    throw '';   
    test4();
    test5();
}

function test3(){
    alert(3);
}

function test4(){
    alert(4);
}

function test5(){
    alert(5);
}
test1();

</script>
</body>
</html>

This is tested with firefox and chrome. I don't know how this is handled by IE or Safari

IE11 prevents ActiveX from running

In my IE11, works normally. Version: 11.306.10586.0

We can test if ActiveX works at IE, in this site: http://www.pcpitstop.com/testax.asp

Switch firefox to use a different DNS than what is in the windows.host file

I wonder if you could write a custom rule for Fiddler to do what you want? IE uses no proxy, Firefox points to Fiddler, Fiddler uses custom rule to direct requests to the dev server...

http://www.fiddlertool.com/fiddler/

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

How can I increment a char?

"bad enough not having a traditional for(;;) looper"?? What?

Are you trying to do

import string
for c in string.lowercase:
    ...do something with c...

Or perhaps you're using string.uppercase or string.letters?

Python doesn't have for(;;) because there are often better ways to do it. It also doesn't have character math because it's not necessary, either.

Connecting to TCP Socket from browser using javascript

As for your problem, currently you will have to depend on XHR or websockets for this.

Currently no popular browser has implemented any such raw sockets api for javascript that lets you create and access raw sockets, but a draft for the implementation of raw sockets api in JavaScript is under-way. Have a look at these links:
http://www.w3.org/TR/raw-sockets/
https://developer.mozilla.org/en-US/docs/Web/API/TCPSocket

Chrome now has support for raw TCP and UDP sockets in its ‘experimental’ APIs. These features are only available for extensions and, although documented, are hidden for the moment. Having said that, some developers are already creating interesting projects using it, such as this IRC client.

To access this API, you’ll need to enable the experimental flag in your extension’s manifest. Using sockets is pretty straightforward, for example:

chrome.experimental.socket.create('tcp', '127.0.0.1', 8080, function(socketInfo) {
  chrome.experimental.socket.connect(socketInfo.socketId, function (result) {
        chrome.experimental.socket.write(socketInfo.socketId, "Hello, world!");         
    });
});

Eclipse - Failed to create the java virtual machine

Change target to specific installation file
like below
Target: D:\SoftWares\oepe-12.1.3.1-luna-maf-distro-win32-x86_64old\eclipse.exe -vm D:\delete\jdk1.7.0_67\bin\javaw.exe

Ansible: Set variable to file content

You can use fetch module to copy files from remote hosts to local, and lookup module to read the content of fetched files.

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Last Key in Python Dictionary

You can do a function like this:

def getLastItem(dictionary):
    last_keyval = dictionary.popitem()
    dictionary.update({last_keyval[0]:last_keyval[1]})
    return {last_keyval[0]:last_keyval[1]}

This not change the original dictionary! This happen because the popitem() function returns a tuple and we can utilize this for us favor!!

In Firebase, is there a way to get the number of children of a node without loading all the node data?

This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.

This hinges on the fact that the Firebase REST API offers a shallow=true parameter.

Assume you have a post object and each one can have a number of comments:

{
 "posts": {
  "$postKey": {
   "comments": {
     ...  
   }
  }
 }
}

You obviously don't want to fetch all of the comments, just the number of comments.

Assuming you have the key for a post, you can send a GET request to https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true.

This will return an object of key-value pairs, where each key is the key of a comment and its value is true:

{
 "comment1key": true,
 "comment2key": true,
 ...,
 "comment9999key": true
}

The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length).

This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

Make sure you installed the nuget package Microsoft.AspNet.Identity.Owin. Then add System.Net.Http namespace.

What is the first character in the sort order used by Windows Explorer?

The first visible character is '!' according to ASCII table.And the last one is '~' So "!file.doc" or "~file.doc' will be the top one depending your ranking order. You can check the ascii table here: http://www.asciitable.com/

Edit: This answer is based on the opinion of the author and not facts.

How to get the latest tag name in current branch in Git?

You can execute: git describe --tags $(git rev-list --tags --max-count=1) talked here: How to get latest tag name?

C - Convert an uppercase letter to lowercase

One way to make sure it is correct is by using character instead of ascii code.

if ((a >= 65) && (a <= 90))

what you want is to lower a case. it's better to use something like if (a >= 'A' && a <= 'Z') . You don't have to remind all ascii code :)

jquery can't get data attribute value

Use plain javascript methods

$x10Device = this.dataset("x10");