Programs & Examples On #Database agnostic

This tag specifies that the question is independent of any particular database and the sql should work in any rdbms.

Insert into ... values ( SELECT ... FROM ... )

To add something in the first answer, when we want only few records from another table (in this example only one):

INSERT INTO TABLE1
(COLUMN1, COLUMN2, COLUMN3, COLUMN4) 
VALUES (value1, value2, 
(SELECT COLUMN_TABLE2 
FROM TABLE2
WHERE COLUMN_TABLE2 like "blabla"),
value4);

Function that creates a timestamp in c#

You could use the DateTime.Ticks property, which is a long and universal storable, always increasing and usable on the compact framework as well. Just make sure your code isn't used after December 31st 9999 ;)

Database cluster and load balancing

Clustering uses shared storage of some kind (a drive cage or a SAN, for example), and puts two database front-ends on it. The front end servers share an IP address and cluster network name that clients use to connect, and they decide between themselves who is currently in charge of serving client requests.

If you're asking about a particular database server, add that to your question and we can add details on their implementation, but at its core, that's what clustering is.

Char array in a struct - incompatible assignment?

sara is the struct itself, not a pointer (i.e. the variable representing location on the stack where actual struct data is stored). Therefore, *sara is meaningless and won't compile.

SQL: IF clause within WHERE clause

You should be able to do this without any IF or CASE

 WHERE 
   (IsNumeric(@OrderNumber) AND
      (CAST OrderNumber AS VARCHAR) = (CAST @OrderNumber AS VARCHAR)
 OR
   (NOT IsNumeric(@OrderNumber) AND
       OrderNumber LIKE ('%' + @OrderNumber))

Depending on the flavour of SQL you may need to tweak the casts on the order number to an INT or VARCHAR depending on whether implicit casts are supported.

This is a very common technique in a WHERE clause. If you want to apply some "IF" logic in the WHERE clause all you need to do is add the extra condition with an boolean AND to the section where it needs to be applied.

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

Please Try This for Getting column Index

Private Sub lvDetail_MouseMove(sender As Object, e As MouseEventArgs) Handles lvDetail.MouseClick

    Dim info As ListViewHitTestInfo = lvDetail.HitTest(e.X, e.Y)
    Dim rowIndex As Integer = lvDetail.FocusedItem.Index
    lvDetail.Items(rowIndex).Selected = True
    Dim xTxt = info.SubItem.Text
    For i = 0 To lvDetail.Columns.Count - 1
        If lvDetail.SelectedItems(0).SubItems(i).Text = xTxt Then
            MsgBox(i)
        End If
    Next
End Sub

How to make MySQL handle UTF-8 properly

Was able to find a solution. Ran the following as specified at http://technoguider.com/2015/05/utf8-set-up-in-mysql/

SET NAMES UTF8;
set collation_server = utf8_general_ci;
set default-character-set = utf8;
set init_connect = ’SET NAMES utf8';
set character_set_server = utf8;
set character_set_client = utf8;

Where does Anaconda Python install on Windows?

With Anaconda prompt python is available, but on any other command window, python is an unknown program. Apparently Anaconda installation does not update the path for python executable.

Which version of Python do I have installed?

On Windows 10 with Python 3.9.1, using the command line:

    py -V

Python 3.9.1

    py --version

Python 3.9.1

Check whether a string matches a regex in JS

please try this flower:

/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('[email protected]');

true

Apply vs transform on a group object

you can use zscore to analyze the data in column C and D for outliers, where zscore is the series - series.mean / series.std(). Use apply too create a user defined function for difference between C and D creating a new resulting dataframe. Apply uses the group result set.

from scipy.stats import zscore

columns = ['A', 'B', 'C', 'D']
records = [
['foo', 'one', 0.162003, 0.087469],
['bar', 'one', -1.156319, -1.5262719999999999],
['foo', 'two', 0.833892, -1.666304],     
['bar', 'three', -2.026673, -0.32205700000000004],
['foo', 'two', 0.41145200000000004, -0.9543709999999999],
['bar', 'two', 0.765878, -0.095968],
['foo', 'one', -0.65489, 0.678091],
['foo', 'three', -1.789842, -1.130922]
]
df = pd.DataFrame.from_records(records, columns=columns)
print(df)

standardize=df.groupby('A')['C','D'].transform(zscore)
print(standardize)
outliersC= (standardize['C'] <-1.1) | (standardize['C']>1.1)
outliersD= (standardize['D'] <-1.1) | (standardize['D']>1.1)

results=df[outliersC | outliersD]
print(results)

   #Dataframe results
   A      B         C         D
   0  foo    one  0.162003  0.087469
   1  bar    one -1.156319 -1.526272
   2  foo    two  0.833892 -1.666304
   3  bar  three -2.026673 -0.322057
   4  foo    two  0.411452 -0.954371
   5  bar    two  0.765878 -0.095968
   6  foo    one -0.654890  0.678091
   7  foo  three -1.789842 -1.130922
 #C and D transformed Z score
           C         D
 0  0.398046  0.801292
 1 -0.300518 -1.398845
 2  1.121882 -1.251188
 3 -1.046514  0.519353
 4  0.666781 -0.417997
 5  1.347032  0.879491
 6 -0.482004  1.492511
 7 -1.704704 -0.624618

 #filtering using arbitrary ranges -1 and 1 for the z-score
      A      B         C         D
 1  bar    one -1.156319 -1.526272
 2  foo    two  0.833892 -1.666304
 5  bar    two  0.765878 -0.095968
 6  foo    one -0.654890  0.678091
 7  foo  three -1.789842 -1.130922


 >>>>>>>>>>>>> Part 2

 splitting = df.groupby('A')

 #look at how the data is grouped
 for group_name, group in splitting:
     print(group_name)

 def column_difference(gr):
      return gr['C']-gr['D']

 grouped=splitting.apply(column_difference)
 print(grouped)

 A     
 bar  1    0.369953
      3   -1.704616
      5    0.861846
 foo  0    0.074534
      2    2.500196
      4    1.365823
      6   -1.332981
      7   -0.658920

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

AngularJS ng-if with multiple conditions

HTML code

<div ng-app>
<div ng-controller='ctrl'>
    <div ng-class='whatClassIsIt(call.state[0])'>{{call.state[0]}}</div>
    <div ng-class='whatClassIsIt(call.state[1])'>{{call.state[1]}}</div>
    <div ng-class='whatClassIsIt(call.state[2])'>{{call.state[2]}}</div>
    <div ng-class='whatClassIsIt(call.state[3])'>{{call.state[3]}}</div>
    <div ng-class='whatClassIsIt(call.state[4])'>{{call.state[4]}}</div>
    <div ng-class='whatClassIsIt(call.state[5])'>{{call.state[5]}}</div>
    <div ng-class='whatClassIsIt(call.state[6])'>{{call.state[6]}}</div>
    <div ng-class='whatClassIsIt(call.state[7])'>{{call.state[7]}}</div>
</div>

JavaScript Code

function ctrl($scope){
$scope.call={state:['second','first','nothing','Never', 'Gonna', 'Give', 'You', 'Up']}


$scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
    else
         return "ClassC";
}
}

pandas GroupBy columns with NaN (missing) values

This is mentioned in the Missing Data section of the docs:

NA groups in GroupBy are automatically excluded. This behavior is consistent with R

One workaround is to use a placeholder before doing the groupby (e.g. -1):

In [11]: df.fillna(-1)
Out[11]: 
   a   b
0  1   4
1  2  -1
2  3   6

In [12]: df.fillna(-1).groupby('b').sum()
Out[12]: 
    a
b    
-1  2
4   1
6   3

That said, this feels pretty awful hack... perhaps there should be an option to include NaN in groupby (see this github issue - which uses the same placeholder hack).

However, as described in another answer, "from pandas 1.1 you have better control over this behavior, NA values are now allowed in the grouper using dropna=False"

How to sort Map values by key in Java?

If you already have a map and would like to sort it on keys, simply use :

Map<String, String> treeMap = new TreeMap<String, String>(yourMap);

A complete working example :

import java.util.HashMap;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;

class SortOnKey {

public static void main(String[] args) {
   HashMap<String,String> hm = new HashMap<String,String>();
   hm.put("3","three");
   hm.put("1","one");
   hm.put("4","four");
   hm.put("2","two");
   printMap(hm);
   Map<String, String> treeMap = new TreeMap<String, String>(hm);
   printMap(treeMap);
}//main

public static void printMap(Map<String,String> map) {
    Set s = map.entrySet();
    Iterator it = s.iterator();
    while ( it.hasNext() ) {
       Map.Entry entry = (Map.Entry) it.next();
       String key = (String) entry.getKey();
       String value = (String) entry.getValue();
       System.out.println(key + " => " + value);
    }//while
    System.out.println("========================");
}//printMap

}//class

Invalid length for a Base-64 char array

My initial guess without knowing the data would be that the UserNameToVerify is not a multiple of 4 in length. Check out the FromBase64String on msdn.

// Ok
byte[] b1 = Convert.FromBase64String("CoolDude");
// Exception
byte[] b2 = Convert.FromBase64String("MyMan");

Enable/disable buttons with Angular

Set a property for the current lesson: currentLesson. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on. Each button now can be disabled with [disabled] attribute, if it the currentLesson is not the same as it's order.

HTML

  <button  (click)="currentLesson = '1'"
         [disabled]="currentLesson !== '1'" class="primair">
           Start lesson</button>
  <button (click)="currentLesson = '2'"
         [disabled]="currentLesson !== '2'" class="primair">
           Start lesson</button>
 .....//so on

Typescript

currentLesson:string;

  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]

constructor(){
  this.currentLesson=this.classes[0].currentLesson
}

DEMO

Putting everything in a loop:

HTML

<div *ngFor="let class of classes; let i = index">
   <button [disabled]="currentLesson !== i + 1" class="primair">
           Start lesson {{i +  1}}</button>
</div>

Typescript

currentLesson:string;

classes = [
{
  name: 'Lesson1',
  level: 1,
  code: 1,
},{
  name: 'Lesson2',
  level: 1,
  code: 2,
},
{
  name: 'Lesson3',
  level: 2,
  code: 3,
}]

DEMO

Import Certificate to Trusted Root but not to Personal [Command Line]

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx this works but still a password is needed to be typed in manually for private key. Including -p and "password" cause error too many arguments for certutil on XP

Invalid syntax when using "print"?

The syntax is changed in new 3.x releases rather than old 2.x releases: for example in python 2.x you can write: print "Hi new world" but in the new 3.x release you need to use the new syntax and write it like this: print("Hi new world")

check the documentation: http://docs.python.org/3.3/library/functions.html?highlight=print#print

Convert an image to grayscale in HTML/CSS

Maybe this way help you

img {
    -webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
    filter: grayscale(100%);
}

w3schools.org

How to delete cookies on an ASP.NET website

Taking the OP's Question title as deleting all cookies - "Delete Cookies in website"

I came across code from Dave Domagala on the web somewhere. I edited Dave's to allow for Google Analytics cookies too - which looped through all cookies found on the website and deleted them all. (From a developer angle - updating new code into an existing site, is a nice touch to avoid problems with users revisiting the site).

I use the below code in tandem with reading the cookies first, holding any required data - then resetting the cookies after washing everything clean with the below loop.

The code:

int limit = Request.Cookies.Count; //Get the number of cookies and 
                                   //use that as the limit.
HttpCookie aCookie;   //Instantiate a cookie placeholder
string cookieName;   

//Loop through the cookies
for(int i = 0; i < limit; i++)
{
 cookieName = Request.Cookies[i].Name;    //get the name of the current cookie
 aCookie = new HttpCookie(cookieName);    //create a new cookie with the same
                                          // name as the one you're deleting
 aCookie.Value = "";    //set a blank value to the cookie 
 aCookie.Expires = DateTime.Now.AddDays(-1);    //Setting the expiration date
                                                //in the past deletes the cookie

 Response.Cookies.Add(aCookie);    //Set the cookie to delete it.
}

Addition: If You Use Google Analytics

The above loop/delete will delete ALL cookies for the site, so if you use Google Analytics - it would probably be useful to hold onto the __utmz cookie as this one keeps track of where the visitor came from, what search engine was used, what link was clicked on, what keyword was used, and where they were in the world when your website was accessed.

So to keep it, wrap a simple if statement once the cookie name is known:

... 
aCookie = new HttpCookie(cookieName);    
if (aCookie.Name != "__utmz")
{
    aCookie.Value = "";    //set a blank value to the cookie 
    aCookie.Expires = DateTime.Now.AddDays(-1);   

    HttpContext.Current.Response.Cookies.Add(aCookie);    
}

How to convert Map keys to array?

You can use the spread operator to convert Map.keys() iterator in an Array.

_x000D_
_x000D_
let myMap = new Map().set('a', 1).set('b', 2).set(983, true)_x000D_
let keys = [...myMap.keys()]_x000D_
console.log(keys)
_x000D_
_x000D_
_x000D_

Add more than one parameter in Twig path

You can pass as many arguments as you want, separating them by commas:

{{ path('_files_manage', {project: project.id, user: user.id}) }}

Tips for debugging .htaccess rewrite rules

Some mistakes I observed happens when writing .htaccess

Using of ^(.*)$ repetitively in multiple rules, using ^(.*)$ causes other rules to be impotent in most cases, because it matches all of the url in single hit.

So, if we are using rule for this url sapmle/url it will also consume this url sapmle/url/string.


[L] flag should be used to ensure our rule has done processing.


Should know about:

Difference in %n and $n

%n is matched during %{RewriteCond} part and $n is matches on %{RewriteRule} part.

Working of RewriteBase

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.

This directive is required when you use a relative path in a substitution in per-directory (htaccess) context unless any of the following conditions are true:

The original request, and the substitution, are underneath the DocumentRoot (as opposed to reachable by other means, such as Alias). The filesystem path to the directory containing the RewriteRule, suffixed by the relative substitution is also valid as a URL path on the server (this is rare). In Apache HTTP Server 2.4.16 and later, this directive may be omitted when the request is mapped via Alias or mod_userdir.

Connect Bluestacks to Android Studio

Steps to connect Blue Stack with Android Studio

  1. Close Android Studio.
  2. Go to adb.exe location (default location: %LocalAppData%\Android\sdk\platform-tools)
  3. Run adb connect localhost:5555 from this location.
  4. Start Android Studio and you will get Blue Stack as emulator when you run your app.

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

What is a blob URL and why it is used?

I have modified working solution to handle both the case.. when video is uploaded and when image is uploaded .. hope it will help some.

HTML

<input type="file" id="fileInput">
<div> duration: <span id='sp'></span><div>

Javascript

var fileEl = document.querySelector("input");

fileEl.onchange = function(e) {


    var file = e.target.files[0]; // selected file

    if (!file) {
        console.log("nothing here");
        return;
    }

    console.log(file);
    console.log('file.size-' + file.size);
    console.log('file.type-' + file.type);
    console.log('file.acutalName-' + file.name);

    let start = performance.now();

    var mime = file.type, // store mime for later
        rd = new FileReader(); // create a FileReader

    if (/video/.test(mime)) {

        rd.onload = function(e) { // when file has read:


            var blob = new Blob([e.target.result], {
                    type: mime
                }), // create a blob of buffer
                url = (URL || webkitURL).createObjectURL(blob), // create o-URL of blob
                video = document.createElement("video"); // create video element
            //console.log(blob);
            video.preload = "metadata"; // preload setting

            video.addEventListener("loadedmetadata", function() { // when enough data loads
                console.log('video.duration-' + video.duration);
                console.log('video.videoHeight-' + video.videoHeight);
                console.log('video.videoWidth-' + video.videoWidth);
                //document.querySelector("div")
                //  .innerHTML = "Duration: " + video.duration + "s" + " <br>Height: " + video.videoHeight; // show duration
                (URL || webkitURL).revokeObjectURL(url); // clean up

                console.log(start - performance.now());
                // ... continue from here ...

            });
            video.src = url; // start video load
        };
    } else if (/image/.test(mime)) {
        rd.onload = function(e) {

            var blob = new Blob([e.target.result], {
                    type: mime
                }),
                url = URL.createObjectURL(blob),
                img = new Image();

            img.onload = function() {
                console.log('iamge');
                console.dir('this.height-' + this.height);
                console.dir('this.width-' + this.width);
                URL.revokeObjectURL(this.src); // clean-up memory
                console.log(start - performance.now()); // add image to DOM
            }

            img.src = url;

        };
    }

    var chunk = file.slice(0, 1024 * 1024 * 10); // .5MB
    rd.readAsArrayBuffer(chunk); // read file object

};

jsFiddle Url

https://jsfiddle.net/PratapDessai/0sp3b159/

how to check if List<T> element contains an item with a Particular Property Value

var item = pricePublicList.FirstOrDefault(x => x.Size == 200);
if (item != null) {
   // There exists one with size 200 and is stored in item now
}
else {
  // There is no PricePublicModel with size 200
}

Using HTML5 file uploads with AJAX and jQuery

With jQuery (and without FormData API) you can use something like this:

function readFile(file){
   var loader = new FileReader();
   var def = $.Deferred(), promise = def.promise();

   //--- provide classic deferred interface
   loader.onload = function (e) { def.resolve(e.target.result); };
   loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
   loader.onerror = loader.onabort = function (e) { def.reject(e); };
   promise.abort = function () { return loader.abort.apply(loader, arguments); };

   loader.readAsBinaryString(file);

   return promise;
}

function upload(url, data){
    var def = $.Deferred(), promise = def.promise();
    var mul = buildMultipart(data);
    var req = $.ajax({
        url: url,
        data: mul.data,
        processData: false,
        type: "post",
        async: true,
        contentType: "multipart/form-data; boundary="+mul.bound,
        xhr: function() {
            var xhr = jQuery.ajaxSettings.xhr();
            if (xhr.upload) {

                xhr.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position; /*event.position is deprecated*/
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                        def.notify(percent);
                    }                    
                }, false);
            }
            return xhr;
        }
    });
    req.done(function(){ def.resolve.apply(def, arguments); })
       .fail(function(){ def.reject.apply(def, arguments); });

    promise.abort = function(){ return req.abort.apply(req, arguments); }

    return promise;
}

var buildMultipart = function(data){
    var key, crunks = [], bound = false;
    while (!bound) {
        bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
        for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
    }

    for (var key = 0, l = data.length; key < l; key++){
        if (typeof(data[key].value) !== "string") {
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
                "Content-Type: application/octet-stream\r\n"+
                "Content-Transfer-Encoding: binary\r\n\r\n"+
                data[key].value[0]);
        }else{
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
                data[key].value);
        }
    }

    return {
        bound: bound,
        data: crunks.join("\r\n")+"\r\n--"+bound+"--"
    };
};

//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
   var formData = form.find(":input:not('#file')").serializeArray();
   formData.file = [fileData, $file[0].files[0].name];
   upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});

With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})

Link to a section of a webpage

Simple:

Use <section>.

and use <a href="page.html#tips">Visit the Useful Tips Section</a>

w3school.com/html_links

Synchronization vs Lock

Lock and synchronize block both serves the same purpose but it depends on the usage. Consider the below part

void randomFunction(){
.
.
.
synchronize(this){
//do some functionality
}

.
.
.
synchronize(this)
{
// do some functionality
}


} // end of randomFunction

In the above case , if a thread enters the synchronize block, the other block is also locked. If there are multiple such synchronize block on the same object, all the blocks are locked. In such situations , java.util.concurrent.Lock can be used to prevent unwanted locking of blocks

Setting default values for columns in JPA

another approach is using javax.persistence.PrePersist

@PrePersist
void preInsert() {
   if (this.createdTime == null)
       this.createdTime = new Date();
}

JTable won't show column headers

The main difference between this answer and the accepted answer is the use of setViewportView() instead of add().

How to put JTable in JScrollPane using Eclipse IDE:

  1. Create JScrollPane container via Design tab.
  2. Stretch JScrollPane to desired size (applies to Absolute Layout).
  3. Drag and drop JTable component on top of JScrollPane (Viewport area).

In Structure > Components, table should be a child of scrollPane. enter image description here

The generated code would be something like this:

JScrollPane scrollPane = new JScrollPane();
...

JTable table = new JTable();
scrollPane.setViewportView(table);

Which comes first in a 2D array, rows or columns?

Java is considered "row major", meaning that it does rows first. This is because a 2D array is an "array of arrays".

For example:

int[ ][ ] a = new int[2][4];  // Two rows and four columns.

a[0][0] a[0][1] a[0][2] a[0][3]

a[1][0] a[1][1] a[1][2] a[1][3]

It can also be visualized more like this:

a[0] ->  [0] [1] [2] [3]
a[1] ->  [0] [1] [2] [3]

The second illustration shows the "array of arrays" aspect. The first array contains {a[0] and a[1]}, and each of those is an array containing four elements, {[0][1][2][3]}.

TL;DR summary:

Array[number of arrays][how many elements in each of those arrays]

For more explanations, see also Arrays - 2-dimensional.

using awk with column value conditions

This method uses regexp, it should work:

awk '$2 ~ /findtext/ {print $3}' <infile>

Select data from date range between two dates

This working on SQL_Server_2008 R2

Select * 
from Product_sales
where From_date 
between '2013-01-03' and '2013-01-09'

How do I run SSH commands on remote system using Java?

Have a look at Runtime.exec() Javadoc

Process p = Runtime.getRuntime().exec("ssh myhost");
PrintStream out = new PrintStream(p.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

out.println("ls -l /home/me");
while (in.ready()) {
  String s = in.readLine();
  System.out.println(s);
}
out.println("exit");

p.waitFor();

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

Most concise way to convert a Set<T> to a List<T>

If you are using Guava, you statically import newArrayList method from Lists class:

List<String> l = newArrayList(setOfAuthors);

jQuery return ajax result into outside variable

I solved it by doing like that:

var return_first = (function () {
        var tmp = $.ajax({
            'type': "POST",
            'dataType': 'html',
            'url': "ajax.php?first",
            'data': { 'request': "", 'target': arrange_url, 'method': 
                    method_target },
            'success': function (data) {
                tmp = data;
            }
        }).done(function(data){
                return data;
        });
      return tmp;
    });
  • Be careful 'async':fale javascript will be asynchronous.

How can I create a progress bar in Excel VBA?

You can create a form in VBA, with code to increase the width of a label control as your code progresses. You can use the width property of a label control to resize it. You can set the background colour property of the label to any colour you choose. This will let you create your own progress bar.

The label control that resizes is a quick solution. However, most people end up creating individual forms for each of their macros. I use the DoEvents function and a modeless form to use a single form for all your macros.

Here is a blog post I wrote about it: http://strugglingtoexcel.wordpress.com/2014/03/27/progress-bar-excel-vba/

All you have to do is import the form and a module into your projects, and call the progress bar with: Call modProgress.ShowProgress(ActionIndex, TotalActions, Title.....)

I hope this helps.

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

Download the oracle ojdbc driver from Oracle official website.

Install/Add Oracle driver to the local maven repository mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc7 -Dpackaging=jar -Dversion=12.1.0.1 -Dfile=ojdbc7.jar -DgeneratePom=true

Specify the downloaded file location via -Dfile=

Add the following dependency in your pom file

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.1</version>
</dependency>

Use the same groupId/artifactId as specified in your mvn install command. Finally clean your project.

PyCharm shows unresolved references error for valid code

I closed all the other projects and run my required project in isolation in Pycharm. I created a separate virtualenv from pycharm and added all the required modules in it by using pip. I added this virtual environment in project's interpreter. This solved my problem.

What is the 'realtime' process priority setting for?

Real-time is the highest priority class available to a process. Therefore, it is different from 'High' in that it's one step greater, and 'Above Normal' in that it's two steps greater.

Similarly, real-time is also a thread priority level.

The process priority class raises or lowers all effective thread priorities in the process and is therefore considered the 'base priority'.

So, a process has a:

  1. Base process priority class.
  2. Individual thread priorities, offsets of the base priority class.

Since real-time is supposed to be reserved for applications that absolutely must pre-empt other running processes, there is a special security privilege to protect against haphazard use of it. This is defined by the security policy.

In NT6+ (Vista+), use of the Vista Multimedia Class Scheduler is the proper way to achieve real-time operations in what is not a real-time OS. It works, for the most part, though is not perfect since the OS isn't designed for real-time operations.

Microsoft considers this priority very dangerous, rightly so. No application should use it except in very specialized circumstances, and even then try to limit its use to temporary needs.

How do I make a "div" button submit the form its sitting in?

onClick="javascript:this.form.submit();">

this in div onclick don't have attribute form, you may try this.parentNode.submit() or document.forms[0].submit() will do

Also, onClick, should be onclick, some browsers don't work with onClick

Python: avoid new line with print command

If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try

from __future__ import print_function

print("abcd", end='')
print("efg")

results in

abcdefg

For those using 3.x, this is already built-in.

Android: Share plain text using intent (to all messaging apps)

New way of doing this would be using ShareCompat.IntentBuilder like so:

// Create and fire off our Intent in one fell swoop
ShareCompat.IntentBuilder
        // getActivity() or activity field if within Fragment
        .from(this) 
        // The text that will be shared
        .setText(textToShare)
        // most general text sharing MIME type
        .setType("text/plain") 
        .setStream(uriToContentThatMatchesTheArgumentOfSetType)
        /*
         * [OPTIONAL] Designate a URI to share. Your type that 
         * is set above will have to match the type of data
         * that your designating with this URI. Not sure
         * exactly what happens if you don't do that, but 
         * let's not find out.
         * 
         * For example, to share an image, you'd do the following:
         *     File imageFile = ...;
         *     Uri uriToImage = ...; // Convert the File to URI
         *     Intent shareImage = ShareCompat.IntentBuilder.from(activity)
         *       .setType("image/png")
         *       .setStream(uriToImage)
         *       .getIntent();
         */
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email recipients as an array
         * of Strings or a single String
         */ 
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email addresses that will be 
         * BCC'd on an email as an array of Strings or a single String
         */ 
        .addEmailBcc(arrayOfStringEmailAddresses)
        .addEmailBcc(singleStringEmailAddress)
        /* 
         * The title of the chooser that the system will show
         * to allow the user to select an app
         */
        .setChooserTitle(yourChooserTitle)
        .startChooser();

If you have any more questions about using ShareCompat, I highly recommend this great article from Ian Lake, an Android Developer Advocate at Google, for a more complete breakdown of the API. As you'll notice, I borrowed some of this example from that article.

If that article doesn't answer all of your questions, there is always the Javadoc itself for ShareCompat.IntentBuilder on the Android Developers website. I added more to this example of the API's usage on the basis of clemantiano's comment.

How to deal with the URISyntaxException

A general solution requires parsing the URL into a RFC 2396 compliant URI (note that this is an old version of the URI standard, which java.net.URI uses).

I have written a Java URL parsing library that makes this possible: galimatias. With this library, you can achieve your desired behaviour with this code:

String urlString = //...
URLParsingSettings settings = URLParsingSettings.create()
  .withStandard(URLParsingSettings.Standard.RFC_2396);
URL url = URL.parse(settings, urlString);

Note that galimatias is in a very early stage and some features are experimental, but it is already quite solid for this use case.

How can I create an object and add attributes to it?

as docs say:

Note: object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.

You could just use dummy-class instance.

How to negate the whole regex?

Apply this if you use laravel.

Laravel has a not_regex where field under validation must not match the given regular expression; uses the PHP preg_match function internally.

'email' => 'not_regex:/^.+$/i'

When should I use cross apply over inner join?

It seems to me that CROSS APPLY can fill a certain gap when working with calculated fields in complex/nested queries, and make them simpler and more readable.

Simple example: you have a DoB and you want to present multiple age-related fields that will also rely on other data sources (such as employment), like Age, AgeGroup, AgeAtHiring, MinimumRetirementDate, etc. for use in your end-user application (Excel PivotTables, for example).

Options are limited and rarely elegant:

  • JOIN subqueries cannot introduce new values in the dataset based on data in the parent query (it must stand on its own).

  • UDFs are neat, but slow as they tend to prevent parallel operations. And being a separate entity can be a good (less code) or a bad (where is the code) thing.

  • Junction tables. Sometimes they can work, but soon enough you're joining subqueries with tons of UNIONs. Big mess.

  • Create yet another single-purpose view, assuming your calculations don't require data obtained mid-way through your main query.

  • Intermediary tables. Yes... that usually works, and often a good option as they can be indexed and fast, but performance can also drop due to to UPDATE statements not being parallel and not allowing to cascade formulas (reuse results) to update several fields within the same statement. And sometimes you'd just prefer to do things in one pass.

  • Nesting queries. Yes at any point you can put parenthesis on your entire query and use it as a subquery upon which you can manipulate source data and calculated fields alike. But you can only do this so much before it gets ugly. Very ugly.

  • Repeating code. What is the greatest value of 3 long (CASE...ELSE...END) statements? That's gonna be readable!

    • Tell your clients to calculate the damn things themselves.

Did I miss something? Probably, so feel free to comment. But hey, CROSS APPLY is like a godsend in such situations: you just add a simple CROSS APPLY (select tbl.value + 1 as someFormula) as crossTbl and voilà! Your new field is now ready for use practically like it had always been there in your source data.

Values introduced through CROSS APPLY can...

  • be used to create one or multiple calculated fields without adding performance, complexity or readability issues to the mix
  • like with JOINs, several subsequent CROSS APPLY statements can refer to themselves: CROSS APPLY (select crossTbl.someFormula + 1 as someMoreFormula) as crossTbl2
  • you can use values introduced by a CROSS APPLY in subsequent JOIN conditions
  • As a bonus, there's the Table-valued function aspect

Dang, there's nothing they can't do!

jQuery UI autocomplete with item and id

Assuming the objects in your source array have an id property...

var $local_source = [
    { id: 1, value: "c++" },
    { id: 2, value: "java" },
    { id: 3, value: "php" },
    { id: 4, value: "coldfusion" },
    { id: 5, value: "javascript" },
    { id: 6, value: "asp" },
    { id: 7, value: "ruby" }];

Getting hold of the current instance and inspecting its selectedItem property will allow you to retrieve the properties of the currently selceted item. In this case alerting the id of the selected item.

$('#button').click(function() {
    alert($("#txtAllowSearch").autocomplete("instance").selectedItem.id;
});

String to Binary in C#

Here's an extension function:

        public static string ToBinary(this string data, bool formatBits = false)
        {
            char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))];
            int index = 0;
            for (int i = 0; i < data.Length; i++)
            {
                string binary = Convert.ToString(data[i], 2).PadLeft(8, '0');
                for (int j = 0; j < 8; j++)
                {
                    buffer[index] = binary[j];
                    index++;
                }
                if (formatBits && i < (data.Length - 1))
                {
                    buffer[index] = ' ';
                    index++;
                }
            }
            return new string(buffer);
        }

You can use it like:

Console.WriteLine("Testing".ToBinary());

and if you add 'true' as a parameter, it will automatically separate each binary sequence.

How to do Select All(*) in linq to sql

I often need to retrieve 'all' columns, except a few. so Select(x => x) does not work for me.

LINQPad's editor can auto-expand * to all columns.

enter image description here

after select '* all', LINQPad expands *, then I can remove not-needed columns.

enter image description here

:before and background-image... should it work?

you can set an image URL for the content prop instead of the background-image.

content: url(/img/border-left3.png);

How can I trigger an onchange event manually?

For those using jQuery there's a convenient method: http://api.jquery.com/change/

MySQL JOIN the most recent row only?

It's a good idea that logging actual data into "customer_data" table. With this data you can select all data from "customer_data" table as you wish.

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

So, it turns out that X11 wasn't actually installed on the centOS. There didn't seem to be any indication anywhere of it not being installed. I did the following command and now firefox opens:

yum groupinstall 'X Window System' 

Hope this answer will help others that are confused :)

How to access array elements in a Django template?

You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.

how to set the background color of the whole page in css

Looks to me like you need to set the yellow on #doc3 and then get rid of the white that is called out on the #yui-main (which is covering up the color of the #doc3). This gets you yellow between header and footer.

When to use 'raise NotImplementedError'?

As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.

There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.

Here's a Python 3 example:

class C(abc.ABC):
    @abc.abstractmethod
    def my_abstract_method(self, ...):
        ...

When instantiating C, you'll get an error because my_abstract_method is abstract. You need to implement it in a child class.

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

Subclass C and implement my_abstract_method.

class D(C):
    def my_abstract_method(self, ...):
        ...

Now you can instantiate D.

C.my_abstract_method does not have to be empty. It can be called from D using super().

An advantage of this over NotImplementedError is that you get an explicit Exception at instantiation time, not at method call time.

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

I know it's quite an old question, but since this is one of top results in google... I had to somehow cancel scroll bubbling without jQuery and this code works for me:

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
    e.preventDefault();
  e.returnValue = false;  
}

document.getElementById('a').onmousewheel = function(e) { 
  document.getElementById('a').scrollTop -= e. wheelDeltaY; 
  preventDefault(e);
}

equivalent of rm and mv in windows .cmd

move in windows is equivalent of mv command in Linux

del in windows is equivalent of rm command in Linux

how to open a page in new tab on button click in asp.net?

add target='_blank' after check validation :

_x000D_
_x000D_
    <asp:button id="_ButPrint"  ValidationGroup="print" OnClientClick="if (Page_ClientValidate()){$('form').attr('target','_blank');}"  runat="server" onclick="ButPrint_Click" Text="print" />
                                                                 
_x000D_
_x000D_
_x000D_

How to replace an entire line in a text file by line number

On mac I used

sed -i '' -e 's/text-on-line-to-be-changed.*/text-to-replace-the=whole-line/' file-name

Where is Java's Array indexOf?

Arrays themselves do not have that method. A List, however, does: indexOf

Netbeans installation doesn't find JDK

I also had the same problem. So I tried by installing a lesser version say jdk1.5 and running the netbeans installation from command prompt as: Linux: netbeans-5_5-linux.bin -is:javahome /usr/jdk/jdk1.5.0_06 Windows: netbeans-5_5-windows.exe -is:javahome "C:\Program Files\Java\jdk1.5.0_06"

Hope it helps

Pandas left outer join multiple dataframes on multiple columns

One can also do this with a compact version of @TomAugspurger's answer, like so:

df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])

How do you count the lines of code in a Visual Studio solution?

You could use:

How do I avoid the specification of the username and password at every git push?

If your PC is secure or you don't care about password security, this can be achieved very simply. Assuming that the remote repository is on GitHub and origin is your local name for the remote repository, use this command

git remote set-url --push origin https://<username>:<password>@github.com/<repo>

The --push flag ensures this changes the URL of the repository for the git push command only. (The question asked in the original post is about git push command only. Requiring a username+password only for push operations is the normal setup for public repositories on GitHub . Note that private repositories on GitHub would also require a username+password for pull and fetch operations, so for a private repository you would not want to use the --push flag ...)

WARNING: This is inherently unsecure because:

  1. your ISP, or anyone logging your network accesses, can easily see the password in plain text in the URL;

  2. anyone who gains access to your PC can view your password using git remote show origin.

That's why using an SSH key is the accepted answer.

Even an SSH key is not totally secure. Anyone who gains access to your PC can still, for example, make pushes which wreck your repository or - worse - push commits making subtle changes to your code. (All pushed commits are obviously highly visible on GitHub. But if someone wanted to change your code surreptitiously, they could --amend a previous commit without changing the commit message, and then force push it. That would be stealthy and quite hard to notice in practice.)

But revealing your password is worse. If an attacker gains knowledge of your username+password, they can do things like lock you out of your own account, delete your account, permanently delete the repository, etc.


Alternatively - for simplicity and security - you can supply only your username in the URL, so that you will have to type your password every time you git push but you will not have to give your username each time. (I quite like this approach, having to type the password gives me a pause to think each time I git push, so I cannot git push by accident.)

git remote set-url --push origin https://<username>@github.com/<repo>

How to populate a sub-document in mongoose after creating it?

I faced the same problem,but after hours of efforts i find the solution.It can be without using any external plugin:)

applicantListToExport: function (query, callback) {
  this
   .find(query).select({'advtId': 0})
   .populate({
      path: 'influId',
      model: 'influencer',
      select: { '_id': 1,'user':1},
      populate: {
        path: 'userid',
        model: 'User'
      }
   })
 .populate('campaignId',{'campaignTitle':1})
 .exec(callback);
}

How to convert nanoseconds to seconds using the TimeUnit enum?

This will convert a time to seconds in a double format, which is more precise than an integer value:

double elapsedTimeInSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS) / 1000.0;

What is ViewModel in MVC?

A view model is a conceptual model of data. Its use is to for example either get a subset or combine data from different tables.

You might only want specific properties, so this allows you to only load those and not additional unneccesary properties

How to iterate over a column vector in Matlab?

If you just want to apply a function to each element and put the results in an output array, you can use arrayfun.

As others have pointed out, for most operations, it's best to avoid loops in MATLAB and vectorise your code instead.

MS-DOS Batch file pause with enter key

There's a pause command that does just that, though it's not specifically the enter key.

If you really want to wait for only the enter key, you can use the set command to ask for user input with a dummy variable, something like:

set /p DUMMY=Hit ENTER to continue...

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

  • if you unable to find assembly reference from when (Right click on reference ->add required assembly)

try this Package manager console
Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3 and then add by using add reference .

Check if a number is int or float

It's easier to ask forgiveness than ask permission. Simply perform the operation. If it works, the object was of an acceptable, suitable, proper type. If the operation doesn't work, the object was not of a suitable type. Knowing the type rarely helps.

Simply attempt the operation and see if it works.

inNumber = somenumber
try:
    inNumberint = int(inNumber)
    print "this number is an int"
except ValueError:
    pass
try:
    inNumberfloat = float(inNumber)
    print "this number is a float"
except ValueError:
    pass

Why do we need virtual functions in C++?

The virtual keyword forces the compiler to pick the method implementation defined in the object's class rather than in the pointer's class.

Shape *shape = new Triangle(); 
cout << shape->getName();

In the above example, Shape::getName will be called by default, unless the getName() is defined as virtual in the Base class Shape. This forces the compiler to look for the getName() implementation in the Triangle class rather than in the Shape class.

The virtual table is the mechanism in which the compiler keeps track of the various virtual-method implementations of the subclasses. This is also called dynamic dispatch, and there is some overhead associated with it.

Finally, why is virtual even needed in C++, why not make it the default behavior like in Java?

  1. C++ is based on the principles of "Zero Overhead" and "Pay for what you use". So it doesn't try to perform dynamic dispatch for you, unless you need it.
  2. To provide more control to the interface. By making a function non-virtual, the interface/abstract class can control the behavior in all its implementations.

How to use in jQuery :not and hasClass() to get a specific element without a class

It's much easier to do like this:

if(!$('#foo').hasClass('bar')) { 
  ...
}

The ! in front of the criteria means false, works in most programming languages.

Youtube - downloading a playlist - youtube-dl

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

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

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

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

Video Selection:

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

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

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

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

How to get the background color of an HTML element?

This worked for me:

var backgroundColor = window.getComputedStyle ? window.getComputedStyle(myDiv, null).getPropertyValue("background-color") : myDiv.style.backgroundColor;

And, even better:

var getStyle = function(element, property) {
    return window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(property) : element.style[property.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); })];
};
var backgroundColor = getStyle(myDiv, "background-color");

RegEx match open tags except XHTML self-contained tags

While the answers that you can't parse HTML with regexes are correct, they don't apply here. The OP just wants to parse one HTML tag with regexes, and that is something that can be done with a regular expression.

The suggested regex is wrong, though:

<([a-z]+) *[^/]*?>

If you add something to the regex, by backtracking it can be forced to match silly things like <a >>, [^/] is too permissive. Also note that <space>*[^/]* is redundant, because the [^/]* can also match spaces.

My suggestion would be

<([a-z]+)[^>]*(?<!/)>

Where (?<! ... ) is (in Perl regexes) the negative look-behind. It reads "a <, then a word, then anything that's not a >, the last of which may not be a /, followed by >".

Note that this allows things like <a/ > (just like the original regex), so if you want something more restrictive, you need to build a regex to match attribute pairs separated by spaces.

Python: CSV write by column rather than row

Let's assume that (1) you don't have a large memory (2) you have row headings in a list (3) all the data values are floats; if they're all integers up to 32- or 64-bits worth, that's even better.

On a 32-bit Python, storing a float in a list takes 16 bytes for the float object and 4 bytes for a pointer in the list; total 20. Storing a float in an array.array('d') takes only 8 bytes. Increasingly spectacular savings are available if all your data are int (any negatives?) that will fit in 8, 4, 2 or 1 byte(s) -- especially on a recent Python where all ints are longs.

The following pseudocode assumes floats stored in array.array('d'). In case you don't really have a memory problem, you can still use this method; I've put in comments to indicate the changes needed if you want to use a list.

# Preliminary:
import array # list: delete
hlist = []
dlist = []
for each row: 
    hlist.append(some_heading_string)
    dlist.append(array.array('d')) # list: dlist.append([])
# generate data
col_index = -1
for each column:
    col_index += 1
    for row_index in xrange(len(hlist)):
        v = calculated_data_value(row_index, colindex)
        dlist[row_index].append(v)
# write to csv file
for row_index in xrange(len(hlist)):
    row = [hlist[row_index]]
    row.extend(dlist[row_index])
    csv_writer.writerow(row)

Python: converting a list of dictionaries to json

To convert it to a single dictionary with some decided keys value, you can use the code below.

data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
    ListOfDictAsDict[PrecedingText + str(i)] = data[i]

Check if a number has a decimal place/is a whole number

Using modulus will work:

num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5

Note that this is based on the numerical value of the number, regardless of format. It treats numerical strings containing whole numbers with a fixed decimal point the same as integers:

'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5

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

There's a really good article on wiki.wxpython.org entitled Working With Images. The article mentions the possiblity of using wxWidgets (wxImage), PIL or PythonMagick. Personally, I've used PIL and wxWidgets and both make image manipulation fairly easy.

How to add a "confirm delete" option in ASP.Net Gridview?

Try this:

I used for Update and Delete buttons. It doesn't touch Edit button. You can use auto generated buttons.

  protected void gvOperators_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType != DataControlRowType.DataRow) return;
        var updateButton = (LinkButton)e.Row.Cells[0].Controls[0];
        if (updateButton.Text == "Update")
        {
            updateButton.OnClientClick = "return confirm('Do you really want to update?');";
        }
        var deleteButton = (LinkButton)e.Row.Cells[0].Controls[2];
        if (deleteButton.Text == "Delete")
        {
            deleteButton.OnClientClick = "return confirm('Do you really want to delete?');";
        }

    }

clear data inside text file in c++

Deleting the file will also remove the content. See remove file.

The Use of Multiple JFrames: Good or Bad Practice?

It's been a while since the last time i touch swing but in general is a bad practice to do this. Some of the main disadvantages that comes to mind:

  • It's more expensive: you will have to allocate way more resources to draw a JFrame that other kind of window container, such as Dialog or JInternalFrame.

  • Not user friendly: It is not easy to navigate into a bunch of JFrame stuck together, it will look like your application is a set of applications inconsistent and poorly design.

  • It's easy to use JInternalFrame This is kind of retorical, now it's way easier and other people smarter ( or with more spare time) than us have already think through the Desktop and JInternalFrame pattern, so I would recommend to use it.

Android - Get value from HashMap

this work for me:

HashMap<String, String> meMap=new HashMap<String, String>();
meMap.put("Color1","Red");
meMap.put("Color2","Blue");
meMap.put("Color3","Green");
meMap.put("Color4","White");

Iterator iterator = meMap.keySet().iterator();
while( iterator. hasNext() )
{
    Toast.makeText(getBaseContext(), meMap.get(iterator.next().toString()), 
    Toast.LENGTH_SHORT).show();
}

Difference between hamiltonian path and euler path

Euler Path - An Euler path is a path in which each edge is traversed exactly once.

Hamiltonian Path - An Hamiltonian path is path in which each vertex is traversed exactly once.

If you have ever confusion remember E - Euler E - Edge.

What is the default value for enum variable?

I think it's quite dangerous to rely on the order of the values in a enum and to assume that the first is always the default. This would be good practice if you are concerned about protecting the default value.

enum E
{
    Foo = 0, Bar, Baz, Quux
}

Otherwise, all it takes is a careless refactor of the order and you've got a completely different default.

How to resize a custom view programmatically?

Here's a more generic version of the solution above from @herbertD :

private void resizeView(View view, int newWidth, int newHeight) { 
    try { 
        Constructor<? extends LayoutParams> ctor = view.getLayoutParams().getClass().getDeclaredConstructor(int.class, int.class); 
        view.setLayoutParams(ctor.newInstance(newWidth, newHeight));   
    } catch (Exception e) { 
        e.printStackTrace(); 
    }
}

What causes this error? "Runtime error 380: Invalid property value"

I think, basically the problem lies in the fact, as to under what version of the O/S has the programme been compiled and under what version of the O/S are you running the programme. I have seen a lot of updated dll and ocx files causing similar errors, especially when the programme has been compiled under older version of the dll and ocx files and during set up the latest dll and ocx files are retained.

For loop example in MySQL

You can exchange this local variable for a global, it would be easier.

DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      SET @a = 0;
      simple_loop: LOOP
         SET @a=@a+1;
         select @a;
         IF @a=5 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

Get folder name of the file in Python

you can use pathlib

from pathlib import Path
Path(r"C:\folder1\folder2\filename.xml").parts[-2]

The output of the above was this:

'folder2'

Laravel Password & Password_Confirmation Validation

try confirmed and without password_confirmation rule:

$this->validate($request, [
        'name' => 'required|min:3|max:50',
        'email' => 'email',
        'vat_number' => 'max:13',
        'password' => 'confirmed|min:6',
    ]);

Hiding user input on terminal in Linux script

Get Username and password

Make it more clear to read but put it on a better position over the screen

#!/bin/bash
clear
echo 
echo 
echo
counter=0
unset username
prompt="  Enter Username:"
while IFS= read -p "$prompt" -r -s -n 1 char
do
    if [[ $char == $'\0' ]]; then
        break
    elif [ $char == $'\x08' ] && [ $counter -gt 0 ]; then
        prompt=$'\b \b'
        username="${username%?}"
        counter=$((counter-1))
    elif [ $char == $'\x08' ] && [ $counter -lt 1 ]; then
        prompt=''
        continue
    else
        counter=$((counter+1))
        prompt="$char"
        username+="$char"
    fi
done
echo
unset password
prompt="  Enter Password:"
while IFS= read -p "$prompt" -r -s -n 1 char
do
    if [[ $char == $'\0' ]]; then
        break
    elif [ $char == $'\x08' ] && [ $counter -gt 0 ]; then
        prompt=$'\b \b'
        password="${password%?}"
        counter=$((counter-1))
    elif [ $char == $'\x08' ] && [ $counter -lt 1 ]; then
        echo
        prompt="  Enter Password:"
        continue
    else
        counter=$((counter+1))
        prompt='*'
        password+="$char"
    fi
done

Normalize columns of pandas data frame

You can use the package sklearn and its associated preprocessing utilities to normalize the data.

import pandas as pd
from sklearn import preprocessing

x = df.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
df = pd.DataFrame(x_scaled)

For more information look at the scikit-learn documentation on preprocessing data: scaling features to a range.

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

well, this using lodash or vanilla javascript it depends on the situation.

but for just return the array that contains the duplicates it can be achieved by the following, offcourse it was taken from @1983

var result = result1.filter(function (o1) {
    return result2.some(function (o2) {
        return o1.id === o2.id; // return the ones with equal id
   });
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

How to create an array of 20 random bytes?

If you want a cryptographically strong random number generator (also thread safe) without using a third party API, you can use SecureRandom.

Java 6 & 7:

SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);

Java 8 (even more secure):

byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);

Pass Array Parameter in SqlCommand

If you can use a tool like "dapper", this can be simply:

int[] ages = { 20, 21, 22 }; // could be any common list-like type
var rows = connection.Query<YourType>("SELECT * from TableA WHERE Age IN @ages",
          new { ages }).ToList();

Dapper will handle unwrapping this to individual parameters for you.

How to pass data from child component to its parent in ReactJS?

Pass data from child to parent Component using Callback

You need to pass from parent to child callback function, and then call it in the child.

Parent Component:-TimeModal

  handleTimeValue = (timeValue) => {
      this.setState({pouringDiff: timeValue});
  }

  <TimeSelection 
        prePourPreHours={prePourPreHours}
        setPourTime={this.setPourTime}
        isPrePour={isPrePour}
        isResident={isResident}
        isMilitaryFormatTime={isMilitaryFormatTime}
        communityDateTime={moment(communityDT).format("MM/DD/YYYY hh:mm A")}
        onSelectPouringTimeDiff={this.handleTimeValue}
     />

Note:- onSelectPouringTimeDiff={this.handleTimeValue}

In the Child Component call props when required

 componentDidMount():void{
      // Todo use this as per your scenrio
       this.props.onSelectPouringTimeDiff(pouringDiff);  
  }

IE prompts to open or save json result from server

In my case, IE11 seems to behave that way when there is some JS syntax error in the console (doesn't matter where exactly) and dataType: 'json' has no effect at all.

passing JSON data to a Spring MVC controller

You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.

In the Controller, you can use the javax.json to convert and manipulate this.

Download and add the .jar to the project libs and import the JsonObject.

To create an json object, you can use

JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();

To read it from String, you can use

JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();

Android: ScrollView force to bottom

scroll.fullScroll(View.FOCUS_DOWN) also should work.

Put this in a scroll.Post(Runnable run)

Kotlin Code

scrollView.post {
   scrollView.fullScroll(View.FOCUS_DOWN)
}

Reduce left and right margins in matplotlib plot

inspired by Sammys answer above:

margins = {  #     vvv margin in inches
    "left"   :     1.5 / figsize[0],
    "bottom" :     0.8 / figsize[1],
    "right"  : 1 - 0.3 / figsize[0],
    "top"    : 1 - 1   / figsize[1]
}
fig.subplots_adjust(**margins)

Where figsize is the tuple that you used in fig = pyplot.figure(figsize=...)

How to get a value inside an ArrayList java

Assuming your Car class has a getter method for price, you can simply use

System.out.println (car.get(i).getPrice());

where i is the index of the element.

You can also use

Car c = car.get(i);
System.out.println (c.getPrice());

You also need to return totalprice from your function if you need to store it

main

public static void processCar(ArrayList<Car> cars){
    int totalAmount=0;
    for (int i=0; i<cars.size(); i++){
        int totalprice= cars.get(i).computeCars ();
        totalAmount=+ totalprice; 
    }
}

And change the return type of your function

public int computeCars (){
    int  totalprice= price+tax;
    System.out.println (name + "\t" +totalprice+"\t"+year );
    return  totalprice; 
 }

How to compare two object variables in EL expression language?

In Expression Language you can just use the == or eq operator to compare object values. Behind the scenes they will actually use the Object#equals(). This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).

So the particular line

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))

If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals("en")

Django request.GET

since your form has a field called 'q', leaving it blank still sends an empty string.

try

if 'q' in request.GET and request.GET['q'] != "" :
     message
else
     error message

Add row to query result using select

You use it like this:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

Use UNION ALL to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION.

import an array in python

In Python, Storing a bare python list as a numpy.array and then saving it out to file, then loading it back, and converting it back to a list takes some conversion tricks. The confusion is because python lists are not at all the same thing as numpy.arrays:

import numpy as np
foods = ['grape', 'cherry', 'mango']
filename = "./outfile.dat.npy"
np.save(filename, np.array(foods))
z = np.load(filename).tolist()
print("z is: " + str(z))

This prints:

z is: ['grape', 'cherry', 'mango']

Which is stored on disk as the filename: outfile.dat.npy

The important methods here are the tolist() and np.array(...) conversion functions.

MIN and MAX in C

@David Titarenco nailed it here, but let me at least clean it up a bit to make it look nice, and show both min() and max() together to make copying and pasting from here easier. :)

Update 25 Apr. 2020: I've also added a Section 3 to show how this would be done with C++ templates too, as a valuable comparison for those learning both C and C++, or transitioning from one to the other. I've done my best to be thorough and factual and correct to make this answer a canonical reference I can come back to again and again, and I hope you find it as useful as I do.

1. The old C macro way:

This technique is commonly used, well-respected by those who know how to use it properly, the "de facto" way of doing things, and fine to use if used properly, but buggy (think: double-evaluation side effect) if you ever pass expressions including variable assignment in to compare:

#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))

2. The new and improved gcc "statement expression" way:

This technique avoids the above "double-evaluation" side effects and bugs, and is therefore considered the superior, safer, and "more modern" GCC C way to do this. Expect it to work with both the gcc and clang compilers, since clang is, by design, gcc-compatible (see the clang note at the bottom of this answer).

BUT: DO watch out for "variable shadowing" effects still, as statement expressions are apparently inlined and therefore do NOT have their own local variable scope!

#define max(a,b)             \
({                           \
    __typeof__ (a) _a = (a); \
    __typeof__ (b) _b = (b); \
    _a > _b ? _a : _b;       \
})

#define min(a,b)             \
({                           \
    __typeof__ (a) _a = (a); \
    __typeof__ (b) _b = (b); \
    _a < _b ? _a : _b;       \
})

Note that in gcc statement expressions, the last expression in the code block is what is "returned" from the expression, as though it was returned from a function. GCC's documentation says it this way:

The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct. (If you use some other kind of statement last within the braces, the construct has type void, and thus effectively no value.)

3. The C++ template way:

C++ Note: if using C++, templates are probably recommended for this type of construct instead, but I personally dislike templates and would probably use one of the above constructs in C++ anyway, as I frequently use and prefer C styles in embedded C++ as well.

This section added 25 Apr. 2020:

I've been doing a ton of C++ the past few months, and the pressure to prefer templates over macros, where able, in the C++ community is quite strong. As a result, I've been getting better at using templates, and want to put in the C++ template versions here for completeness and to make this a more canonical and thorough answer.

Here's what basic function template versions of max() and min() might look like in C++:

template <typename T>
T max(T a, T b)
{
    return a > b ? a : b;
}

template <typename T>
T min(T a, T b)
{
    return a < b ? a : b;
}

Do additional reading about C++ templates here: Wikipedia: Template (C++).

However, both max() and min() are already part of the C++ standard library, in the <algorithm> header (#include <algorithm>). In the C++ standard library they are defined slightly differently than I have them above. The default prototypes for std::max<>() and std::min<>(), for instance, in C++14, looking at their prototypes in the cplusplus.com links just above, are:

template <class T> 
constexpr const T& max(const T& a, const T& b);

template <class T> 
constexpr const T& min(const T& a, const T& b);

Note that the keyword typename is an alias to class (so their usage is identical whether you say <typename T> or <class T>), since it was later acknowledged after the invention of C++ templates, that the template type might be a regular type (int, float, etc.) instead of only a class type.

Here you can see that both of the input types, as well as the return type, are const T&, which means "constant reference to type T". This means the input parameters and return value are passed by reference instead of passed by value. This is like passing by pointers, and is more efficient for large types, such as class objects. The constexpr part of the function modifies the function itself and indicates that the function must be capable of being evaluated at compile-time (at least if provided constexpr input parameters), but if it cannot be evaluated at compile-time, then it defaults back to a run-time evaluation, like any other normal function.

The compile-time aspect of a constexpr C++ function makes it kind-of C-macro-like, in that if compile-time evaluation is possible for a constexpr function, it will be done at compile-time, same as a MIN() or MAX() macro substitution could possibly be fully evaluated at compile-time in C or C++ too. For additional references for this C++ template info, see below.

References:

  1. https://gcc.gnu.org/onlinedocs/gcc/Typeof.html#Typeof
  2. https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html#Statement-Exprs
  3. MIN and MAX in C
  4. Additional C++ template references added Apr. 2020:
    1. *****Wikipedia: Template (C++) <-- GREAT additional info about C++ templates!
    2. (My own question & answer): Why is `constexpr` part of the C++14 template prototype for `std::max()`?
    3. Difference between `constexpr` and `const`

Clang note from Wikipedia:

[Clang] is designed to act as a drop-in replacement for the GNU Compiler Collection (GCC), supporting most of its compilation flags and unofficial language extensions.

How to host a Node.Js application in shared hosting

Connect with SSH and follow these instructions to install Node on a shared hosting

In short you first install NVM, then you install the Node version of your choice with NVM.

wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash

Your restart your shell (close and reopen your sessions). Then you

nvm install stable

to install the latest stable version for example. You can install any version of your choice. Check node --version for the node version you are currently using and nvm list to see what you've installed.

In bonus you can switch version very easily (nvm use <version>)

There's no need of PHP or whichever tricky workaround if you have SSH.

Error after upgrading pip: cannot import name 'main'

I used the following code to load a module that might need install, thus avoiding this error (which I also got) - using the latest Python and latest pip with no problem

try
  from colorama import Fore, Back, Style
except:
  !pip install colorama
  from colorama import Fore, Back, Style

Test if a vector contains a given element

You can use the %in% operator:

vec <- c(1, 2, 3, 4, 5)
1 %in% vec # true
10 %in% vec # false

How to rebase local branch onto remote master

Note: If you have broad knowledge already about rebase then use below one liner for fast rebase. Solution: Assuming you are on your working branch and you are the only person working on it.

git fetch && git rebase origin/master

Resolve any conflicts, test your code, commit and push new changes to remote branch.

                            ~:   For noobs   :~

The following steps might help anyone who are new to git rebase and wanted to do it without hassle

Step 1: Assuming that there are no commits and changes to be made on YourBranch at this point. We are visiting YourBranch.

git checkout YourBranch
git pull --rebase

What happened? Pulls all changes made by other developers working on your branch and rebases your changes on top of it.

Step 2: Resolve any conflicts that presents.

Step 3:

git checkout master
git pull --rebase

What happened? Pulls all the latest changes from remote master and rebases local master on remote master. I always keep remote master clean and release ready! And, prefer only to work on master or branches locally. I recommend in doing this until you gets a hand on git changes or commits. Note: This step is not needed if you are not maintaining local master, instead you can do a fetch and rebase remote master directly on local branch directly. As I mentioned in single step in the start.

Step 4: Resolve any conflicts that presents.

Step 5:

git checkout YourBranch
git rebase master

What happened? Rebase on master happens

Step 6: Resolve any conflicts, if there are conflicts. Use git rebase --continue to continue rebase after adding the resolved conflicts. At any time you can use git rebase --abort to abort the rebase.

Step 7:

git push --force-with-lease 

What happened? Pushing changes to your remote YourBranch. --force-with-lease will make sure whether there are any other incoming changes for YourBranch from other developers while you rebasing. This is super useful rather than force push. In case any incoming changes then fetch them to update your local YourBranch before pushing changes.

Why do I need to push changes? To rewrite the commit message in remote YourBranch after proper rebase or If there are any conflicts resolved? Then you need to push the changes you resolved in local repo to the remote repo of YourBranch

Yahoooo...! You are succesfully done with rebasing.

You might also be looking into doing:

git checkout master
git merge YourBranch

When and Why? Merge your branch into master if done with changes by you and other co-developers. Which makes YourBranch up-to-date with master when you wanted to work on same branch later.

                            ~:   (?o 3 o)? rebase   :~

Printing all properties in a Javascript Object

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}

How to programmatically set drawableLeft on Android button?

Simply you can try this also

txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

Java Interfaces/Implementation naming convention

The standard C# convention, which works well enough in Java too, is to prefix all interfaces with an I - so your file handler interface will be IFileHandler and your truck interface will be ITruck. It's consistent, and makes it easy to tell interfaces from classes.

GitHub Error Message - Permission denied (publickey)

Using Https is fine, run git config --global credential.helper wincred to create a Github credential helper that stores your credentials for you. If this doesn't work, then you need to edit your config file in your .git directory and update the origin to the https url.

See this link for the github docs.

Fundamental difference between Hashing and Encryption algorithms

Cryptography deals with numbers and strings. Basically every digital thing in the entire universe are numbers. When I say numbers, its 0 & 1. You know what they are, binary. The images you see on screen, the music that you listen through your earphone, everything are binaries. But our ears and eyes will not understand binaries right? Only brain could understand that, and even if it could understand binaries, it can’t enjoy binaries. So we convert the binaries to human understandable formats such as mp3,jpg,etc. Let’s term the process as Encoding. It’s two way process and can be easily decoded back to its original form.

Hashing

Hashing is another cryptography technique in which a data once converted to some other form can never be recovered back. In Layman’s term, there is no process called de-hashing. There are many hash functions to do the job such as sha-512, md5 and so on.

If the original value cannot be recovered, then where do we use this? Passwords! When you set up a password for your mobile or PC, a hash of your password is created and stored in a secure place. When you make a login attempt next time, the entered string is again hashed with the same algorithm (hash function) and the output is matched with the stored value. If it’s the same, you get logged in. Otherwise you are thrown out.

Credits: wikimedia By applying hash to the password, we can ensure that an attacker will never get our password even if he steal the stored password file. The attacker will have the hash of the password. He can probably find a list of most commonly used passwords and apply sha-512 to each of it and compare it with the value in his hand. It is called the dictionary attack. But how long would he do this? If your password is random enough, do you think this method of cracking would work? All the passwords in the databases of Facebook, Google and Amazon are hashed, or at least they are supposed to be hashed.

Then there is Encryption

Encryption lies in between hashing and encoding. Encoding is a two way process and should not be used to provide security. Encryption is also a two way process, but original data can be retrieved if and only if the encryption key is known. If you don’t know how encryption works, don’t worry, we will discuss the basics here. That would be enough to understand the basics of SSL. So, there are two types of Encryption namely Symmetric and Asymmetric encryption.

Symmetric Key Encryption

I am trying to keep things as simple as I could. So, let’s understand the symmetric encryption by means of a shift algorithm. This algorithm is used to encrypt alphabets by shifting the letters to either left or right. Let’s take a string CRYPTO and consider a number +3. Then, the encrypted format of CRYPTO will be FUBSWR. That means each letter is shifted to right by 3 places. Here, the word CRYPTO is called Plaintext, the output FUBSWR is called the Ciphertext, the value +3 is called the Encryption key (symmetric key) and the whole process is a cipher. This is one of the oldest and basic symmetric key encryption algorithm and its first usage was reported during the time of Julius Caesar. So, it was named after him and it is the famous Caesar Cipher. Anyone who knows the encryption key and can apply the reverse of Caesar’s algorithm and retrieve the original Plaintext. Hence it is called a Symmetric Encryption.

Asymmetric Key Encryption

We know that, in Symmetric encryption same key is used for both encryption and decryption. Once that key is stolen, all the data is gone. That’s a huge risk and we need more complex technique. In 1976, Whitfield Diffie and Martin Hellman first published the concept of Asymmetric encryption and the algorithm was known as Diffie–Hellman key exchange. Then in 1978, Ron Rivest, Adi Shamir and Leonard Adleman of MIT published the RSA algorithm. These can be considered as the foundation of Asymmetric cryptography.

As compared to Symmetric encryption, in Asymmetric encryption, there will be two keys instead of one. One is called the Public key, and the other one is the Private key. Theoretically, during initiation we can generate the Public-Private key pair to our machine. Private key should be kept in a safe place and it should never be shared with anyone. Public key, as the name indicates, can be shared with anyone who wish to send encrypted text to you. Now, those who have your public key can encrypt the secret data with it. If the key pair were generated using RSA algorithm, then they should use the same algorithm while encrypting the data. Usually the algorithm will be specified in the public key. The encrypted data can only be decrypted with the private key which is owned by you.

Source: SSL/TLS for dummies part 1 : Ciphersuite, Hashing,Encryption | WST (https://www.wst.space/ssl-part1-ciphersuite-hashing-encryption/)

LINQ with groupby and count

After calling GroupBy, you get a series of groups IEnumerable<Grouping>, where each Grouping itself exposes the Key used to create the group and also is an IEnumerable<T> of whatever items are in your original data set. You just have to call Count() on that Grouping to get the subtotal.

foreach(var line in data.GroupBy(info => info.metric)
                        .Select(group => new { 
                             Metric = group.Key, 
                             Count = group.Count() 
                        })
                        .OrderBy(x => x.Metric))
{
     Console.WriteLine("{0} {1}", line.Metric, line.Count);
}

> This was a brilliantly quick reply but I'm having a bit of an issue with the first line, specifically "data.groupby(info=>info.metric)"

I'm assuming you already have a list/array of some class that looks like

class UserInfo {
    string name;
    int metric;
    ..etc..
} 
...
List<UserInfo> data = ..... ;

When you do data.GroupBy(x => x.metric), it means "for each element x in the IEnumerable defined by data, calculate it's .metric, then group all the elements with the same metric into a Grouping and return an IEnumerable of all the resulting groups. Given your example data set of

    <DATA>           | Grouping Key (x=>x.metric) |
joe  1 01/01/2011 5  | 1
jane 0 01/02/2011 9  | 0
john 2 01/03/2011 0  | 2
jim  3 01/04/2011 1  | 3
jean 1 01/05/2011 3  | 1
jill 2 01/06/2011 5  | 2
jeb  0 01/07/2011 3  | 0
jenn 0 01/08/2011 7  | 0

it would result in the following result after the groupby:

(Group 1): [joe  1 01/01/2011 5, jean 1 01/05/2011 3]
(Group 0): [jane 0 01/02/2011 9, jeb  0 01/07/2011 3, jenn 0 01/08/2011 7]
(Group 2): [john 2 01/03/2011 0, jill 2 01/06/2011 5]
(Group 3): [jim  3 01/04/2011 1]

How can I send an Ajax Request on button click from a form with 2 buttons?

Given that the only logical difference between the handlers is the value of the button clicked, you can use the this keyword to refer to the element which raised the event and get the val() from that. Try this:

$("button").click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/pages/test/",
        data: { 
            id: $(this).val(), // < note use of 'this' here
            access_token: $("#access_token").val() 
        },
        success: function(result) {
            alert('ok');
        },
        error: function(result) {
            alert('error');
        }
    });
});

Command to run a .bat file

Can refer to here: https://ss64.com/nt/start.html

start "" /D F:\- Big Packets -\kitterengine\Common\ /W Template.bat

writing to serial port from linux command line

echo '\x12\x02'

will not be interpreted, and will literally write the string \x12\x02 (and append a newline) to the specified serial port. Instead use

echo -n ^R^B

which you can construct on the command line by typing CtrlVCtrlR and CtrlVCtrlB. Or it is easier to use an editor to type into a script file.

The stty command should work, unless another program is interfering. A common culprit is gpsd which looks for GPS devices being plugged in.

Example of SOAP request authenticated with WS-UsernameToken

The core thing is to define prefixes for namespaces and use them to fortify each and every tag - you are mixing 3 namespaces and that just doesn't fly by trying to hack defaults. It's also good to use exactly the prefixes used in the standard doc - just in case that the other side get a little sloppy.

Last but not least, it's much better to use default types for fields whenever you can - so for password you have to list the type, for the Nonce it's already Base64.

Make sure that you check that the generated token is correct before you send it via XML and don't forget that the content of wsse:Password is Base64( SHA-1 (nonce + created + password) ) and date-time in wsu:Created can easily mess you up. So once you fix prefixes and namespaces and verify that yout SHA-1 work fine without XML (just imagine you are validating the request and do the server side of SHA-1 calculation) you can also do a truial wihtout Created and even without Nonce. Oh and Nonce can have different encodings so if you really want to force another encoding you'll have to look further into wsu namespace.

<S11:Envelope xmlns:S11="..." xmlns:wsse="..." xmlns:wsu= "...">
  <S11:Header>
  ...
    <wsse:Security>
      <wsse:UsernameToken>
        <wsse:Username>NNK</wsse:Username>
        <wsse:Password Type="...#PasswordDigest">weYI3nXd8LjMNVksCKFV8t3rgHh3Rw==</wsse:Password>
        <wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce>
        <wsu:Created>2003-07-16T01:24:32</wsu:Created>
      </wsse:UsernameToken>
    </wsse:Security>
  ...
  </S11:Header>
...
</S11:Envelope>

Angular 2 - View not updating after model changes

It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:

import {Component, OnInit, NgZone} from 'angular2/core';

export class RecentDetectionComponent implements OnInit {

    recentDetections: Array<RecentDetection>;

    constructor(private zone:NgZone, // <== added
        private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();
    }

    getRecentDetections(): void {
        this.recentDetectionService.getJsonFromApi()
            .subscribe(recent => { 
                 this.zone.run(() => { // <== added
                     this.recentDetections = recent;
                     console.log(this.recentDetections[0].macAddress) 
                 });
        });
    }

    ngOnInit() {
        this.getRecentDetections();
        let timer = Observable.timer(2000, 5000);
        timer.subscribe(() => this.getRecentDetections());
    }
}

For other ways to invoke change detection see Triggering change detection manually in Angular

Alternative ways to invoke change detection are

ChangeDetectorRef.detectChanges()

to immediately run change detection for the current component and its children

ChangeDetectorRef.markForCheck()

to include the current component the next time Angular runs change detection

ApplicationRef.tick()

to run change detection for the whole application

How to check the maximum number of allowed connections to an Oracle database?

Note: this only answers part of the question.

If you just want to know the maximum number of sessions allowed, then you can execute in sqlplus, as sysdba:

SQL> show parameter sessions

This gives you an output like:

    NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
java_max_sessionspace_size           integer     0
java_soft_sessionspace_limit         integer     0
license_max_sessions                 integer     0
license_sessions_warning             integer     0
sessions                             integer     248
shared_server_sessions               integer

The sessions parameter is the one what you want.

Blur the edges of an image or background image with CSS

I'm not entirely sure what visual end result you're after, but here's an easy way to blur an image's edge: place a div with the image inside another div with the blurred image.

Working example here: http://jsfiddle.net/ZY5hn/1/

Screenshot

HTML:

<div class="placeholder">
     <!-- blurred background image for blurred edge -->
     <div class="bg-image-blur"></div>
     <!-- same image, no blur -->
     <div class="bg-image"></div>
     <!-- content -->
     <div class="content">Blurred Image Edges</div>
</div>

CSS:

.placeholder {
    margin-right: auto;
    margin-left:auto;
    margin-top: 20px;
    width: 200px;
    height: 200px;
    position: relative;
    /* this is the only relevant part for the example */
}
/* both DIVs have the same image */
 .bg-image-blur, .bg-image {
    background-image: url('http://lorempixel.com/200/200/city/9');
    position:absolute;
    top:0;
    left:0;
    width: 100%;
    height:100%;
}
/* blur the background, to make blurred edges that overflow the unblurred image that is on top */
 .bg-image-blur {
    -webkit-filter: blur(20px);
    -moz-filter: blur(20px);
    -o-filter: blur(20px);
    -ms-filter: blur(20px);
    filter: blur(20px);
}
/* I added this DIV in case you need to place content inside */
 .content {
    position: absolute;
    top:0;
    left:0;
    width: 100%;
    height: 100%;
    color: #fff;
    text-shadow: 0 0 3px #000;
    text-align: center;
    font-size: 30px;
}

Notice the blurred effect is using the image, so it changes with the image color.

I hope this helps.

How to represent empty char in Java Character class

An empty String is a wrapper on a char[] with no elements. You can have an empty char[]. But you cannot have an "empty" char. Like other primitives, a char has to have a value.

You say you want to "replace a character without leaving a space".

If you are dealing with a char[], then you would create a new char[] with that element removed.

If you are dealing with a String, then you would create a new String (String is immutable) with the character removed.

Here are some samples of how you could remove a char:

public static void main(String[] args) throws Exception {

    String s = "abcdefg";
    int index = s.indexOf('d');

    // delete a char from a char[]
    char[] array = s.toCharArray();
    char[] tmp = new char[array.length-1];
    System.arraycopy(array, 0, tmp, 0, index);
    System.arraycopy(array, index+1, tmp, index, tmp.length-index);
    System.err.println(new String(tmp));

    // delete a char from a String using replace
    String s1 = s.replace("d", "");
    System.err.println(s1);

    // delete a char from a String using StringBuilder
    StringBuilder sb = new StringBuilder(s);
    sb.deleteCharAt(index);
    s1 = sb.toString();
    System.err.println(s1);

}

Regex replace (in Python) - a simpler way?

The short version is that you cannot use variable-width patterns in lookbehinds using Python's re module. There is no way to change this:

>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    re.sub("(?<=fo+)bar(?=baz)", "quux", string)
  File "C:\Development\Python25\lib\re.py", line 150, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "C:\Development\Python25\lib\re.py", line 241, in _compile
    raise error, v # invalid expression
error: look-behind requires fixed-width pattern

This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:

>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
        return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)

This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.

How to align td elements in center

margin:auto; text-align, if this won't work - try adding display:block; and set there width:200px; (in case your TD is too small).

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

There is no standard format for the readable 8601 format. You can use a custom format:

theDate.ToString("yyyy-MM-dd HH':'mm':'ss")

(The standard format "s" will give you a "T" between the date and the time, not a space.)

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

go to the directory of .Net framework and register their the respective dll with Regsvr32.exe white space dll path.

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

I uninstalled gradle and reinstalled it and then created a new wrapper.

$ sudo apt remove gradle
$ sudo apt-get install gradle
$ gradle wrapper

How can I use UserDefaults in Swift?

UserDefault+Helper.swift

import UIKit

private enum Defaults: String {
   case countryCode = "countryCode"
   case userloginId   = "userloginid"
}

final class UserDefaultHelper {

static var countryCode: String? {
    set{
        _set(value: newValue, key: .countryCode)
    } get {
        return _get(valueForKay: .countryCode) as? String ?? ""
    }
}

static var userloginId: String? {
    set{
        _set(value: newValue, key: .userloginId)
    } get {
        return _get(valueForKay: .userloginId) as? String ?? ""
    }
}

private static func _set(value: Any?, key: Defaults) {
    UserDefaults.standard.set(value, forKey: key.rawValue)
}

private static func _get(valueForKay key: Defaults)-> Any? {
    return UserDefaults.standard.value(forKey: key.rawValue)
}

static func deleteCountryCode() {
    UserDefaults.standard.removeObject(forKey: Defaults.countryCode.rawValue)
 }

static func deleteUserLoginId() {
    UserDefaults.standard.removeObject(forKey: Defaults.userloginId.rawValue)
 }
}

Usage:

Save Value:

UserDefaultHelper.userloginId = data["user_id"] as? String

Fetch Value:

let userloginid = UserDefaultHelper.userloginId

Delete Value:

UserDefaultHelper.deleteUserLoginId()

What is the purpose of a plus symbol before a variable?

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

Triggering a checkbox value changed event in DataGridView

Try hooking into the CellContentClick event. The DataGridViewCellEventArgs will have a ColumnIndex and a RowIndex so you can know if a ChecboxCell was in fact clicked. The good thing about this event is that it will only fire if the actual checkbox itself was clicked. If you click on the white area of the cell around the checkbox, it won't fire. This way, you're pretty much guaranteed that the checkbox value was changed when this event fires. You can then call Invalidate() to trigger your drawing event, as well as a call to EndEdit() to trigger the end of the row's editing if you need that.

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

How to turn off the Eclipse code formatter for certain sections of Java code?

End each of the lines with a double slash "//". That will keep eclipse from moving them all onto the same line.

tsql returning a table from a function or store procedure

You can't access Temporary Tables from within a SQL Function. You will need to use table variables so essentially:

ALTER FUNCTION FnGetCompanyIdWithCategories()
RETURNS  @rtnTable TABLE 
(
    -- columns returned by the function
    ID UNIQUEIDENTIFIER NOT NULL,
    Name nvarchar(255) NOT NULL
)
AS
BEGIN
DECLARE @TempTable table (id uniqueidentifier, name nvarchar(255)....)

insert into @myTable 
select from your stuff

--This select returns data
insert into @rtnTable
SELECT ID, name FROM @mytable 
return
END

Edit

Based on comments to this question here is my recommendation. You want to join the results of either a procedure or table-valued function in another query. I will show you how you can do it then you pick the one you prefer. I am going to be using sample code from one of my schemas, but you should be able to adapt it. Both are viable solutions first with a stored procedure.

declare @table as table (id int, name nvarchar(50),templateid int,account nvarchar(50))

insert into @table
execute industry_getall

select * 
from @table 
inner join [user] 
    on account=[user].loginname

In this case, you have to declare a temporary table or table variable to store the results of the procedure. Now Let's look at how you would do this if you were using a UDF

select *
from fn_Industry_GetAll()
inner join [user] 
    on account=[user].loginname

As you can see the UDF is a lot more concise easier to read, and probably performs a little bit better since you're not using the secondary temporary table (performance is a complete guess on my part).

If you're going to be reusing your function/procedure in lots of other places, I think the UDF is your best choice. The only catch is you will have to stop using #Temp tables and use table variables. Unless you're indexing your temp table, there should be no issue, and you will be using the tempDb less since table variables are kept in memory.

Python Image Library fails with message "decoder JPEG not available" - PIL

libjpeg-dev is required to be able to process jpegs with pillow (or PIL), so you need to install it and then recompile pillow. It also seems that libjpeg8-dev is needed on Ubuntu 14.04

If you're still using PIL then you should really be using pillow these days though, so first pip uninstall PIL before following these instructions to switch, or if you have a good reason for sticking with PIL then replace "pillow" with "PIL" in the below).

On Ubuntu:

# install libjpeg-dev with apt
sudo apt-get install libjpeg-dev
# if you're on Ubuntu 14.04, also install this
sudo apt-get install libjpeg8-dev

# reinstall pillow
pip install --no-cache-dir -I pillow

If that doesn't work, try one of the below, depending on whether you are on 64bit or 32bit Ubuntu.

For Ubuntu x64:

sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib

Or for Ubuntu 32bit:

sudo ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libfreetype.so.6 /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/

Then reinstall pillow:

pip install --no-cache-dir -I pillow

(Edits to include feedback from comments. Thanks Charles Offenbacher for pointing out this differs for 32bit, and t-mart for suggesting use of --no-cache-dir).

Sending intent to BroadcastReceiver from adb

I've found that the command was wrong, correct command contains "broadcast" instead of "start":

adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test from adb" -n com.whereismywifeserver/.IntentReceiver

Why am I getting string does not name a type Error?

You can overcome this error in two simple ways

First way

using namespace std;
include <string>
// then you can use string class the normal way

Second way

// after including the class string in your cpp file as follows
include <string>
/*Now when you are using a string class you have to put **std::** before you write 
string as follows*/
std::string name; // a string declaration

What is the best way to extract the first word from a string in Java?

String anotherPalindrome = "Niagara. O roar again!"; 
String roar = anotherPalindrome.substring(11, 15); 

You can also do like these

How to pick a new color for each plotted line within a figure in matplotlib?

As Ciro's answer notes, you can use prop_cycle to set a list of colors for matplotlib to cycle through. But how many colors? What if you want to use the same color cycle for lots of plots, with different numbers of lines?

One tactic would be to use a formula like the one from https://gamedev.stackexchange.com/a/46469/22397, to generate an infinite sequence of colors where each color tries to be significantly different from all those that preceded it.

Unfortunately, prop_cycle won't accept infinite sequences - it will hang forever if you pass it one. But we can take, say, the first 1000 colors generated from such a sequence, and set it as the color cycle. That way, for plots with any sane number of lines, you should get distinguishable colors.

Example:

from matplotlib import pyplot as plt
from matplotlib.colors import hsv_to_rgb
from cycler import cycler

# 1000 distinct colors:
colors = [hsv_to_rgb([(i * 0.618033988749895) % 1.0, 1, 1])
          for i in range(1000)]
plt.rc('axes', prop_cycle=(cycler('color', colors)))

for i in range(20):
    plt.plot([1, 0], [i, i])

plt.show()

Output:

Graph output by the code above

Now, all the colors are different - although I admit that I struggle to distinguish a few of them!

How to get PHP $_GET array?

You could make id a series of comma-seperated values, like this:

index.php?id=1,2,3&name=john

Then, within your PHP code, explode it into an array:

$values = explode(",", $_GET["id"]);
print count($values) . " values passed.";

This will maintain brevity. The other (more commonly used with $_POST) method is to use array-style square-brackets:

index.php?id[]=1&id[]=2&id[]=3&name=john

But that clearly would be much more verbose.

Java Date cut off time information

With Joda you can easily get the expected date.

As of version 2.7 (maybe since some previous version greater than 2.2), as a commenter notes, toDateMidnight has been deprecated in favor or the aptly named withTimeAtStartOfDay(), making the convenient

DateTime.now().withTimeAtStartOfDay()

possible.

Benefit added of a way nicer API.

With older versions, you can do

new DateTime(new Date()).toDateMidnight().toDate()

Proxy setting for R

On Windows 7 I solved this by going into my environment settings (try this link for how) and adding user variables http_proxy and https_proxy with my proxy details.

Maintain the aspect ratio of a div with CSS

lets say you have 2 divs the outher div is a container and the inner could be any element that you need to keep its ratio (img or an youtube iframe or whatever )

html looks like this :

<div class='container'>
  <div class='element'>
  </div><!-- end of element -->
<div><!-- end of container -->

lets say you need to keep the ratio of the "element" ratio => 4 to 1 or 2 to 1 ...

css looks like this

.container{
  position: relative;
  height: 0
  padding-bottom : 75% /* for 4 to 3 ratio */ 25% /* for 4 to 1 ratio ..*/
  
}

.element{
  width : 100%;
  height: 100%;
  position: absolute; 
  top : 0 ;
  bottom : 0 ;
  background : red; /* just for illustration */
}

padding when specified in % it is calculated based on width not height. .. so basically you it doesn't matter what your width it height will always be calculated based of that . which will keep the ratio .

How to have the cp command create any necessary folders for copying a file to a destination

 mkdir -p `dirname /nosuchdirectory/hi.txt` && cp -r urls-resume /nosuchdirectory/hi.txt

Center a button in a Linear layout

complete and working sample from my machine...

_x000D_
_x000D_
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
    xmlns:tools="http://schemas.android.com/tools"_x000D_
    android:layout_width="fill_parent"_x000D_
    android:layout_height="fill_parent"_x000D_
    android:paddingLeft="@dimen/activity_horizontal_margin"_x000D_
    android:paddingRight="@dimen/activity_horizontal_margin"_x000D_
    android:paddingTop="@dimen/activity_vertical_margin"_x000D_
    android:paddingBottom="@dimen/activity_vertical_margin"_x000D_
    android:orientation="vertical"_x000D_
    tools:context=".MainActivity"_x000D_
    android:gravity="center"_x000D_
    android:textAlignment="center">_x000D_
_x000D_
_x000D_
    <TextView_x000D_
        android:layout_width="fill_parent"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:textAppearance="?android:attr/textAppearanceLarge"_x000D_
        android:text="My Apps!"_x000D_
        android:id="@+id/textView"_x000D_
        android:gravity="center"_x000D_
        android:layout_marginBottom="20dp"_x000D_
     />_x000D_
_x000D_
    <Button_x000D_
        android:layout_width="220dp"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:text="SPOTIFY STREAMER"_x000D_
        android:id="@+id/button_spotify"_x000D_
        android:gravity="center"_x000D_
        android:layout_below="@+id/textView"_x000D_
        android:padding="20dp"_x000D_
        />_x000D_
_x000D_
    <Button_x000D_
        android:layout_width="220dp"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:text="SCORES"_x000D_
        android:id="@+id/button_scores"_x000D_
        android:gravity="center"_x000D_
        android:layout_below="@+id/textView"_x000D_
        android:padding="20dp"_x000D_
        />_x000D_
_x000D_
_x000D_
    <Button_x000D_
        android:layout_width="220dp"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:layout_centerInParent="true"_x000D_
        android:text="LIBRARY APP"_x000D_
        android:id="@+id/button_library"_x000D_
        android:gravity="center"_x000D_
        android:layout_below="@+id/textView"_x000D_
        android:padding="20dp"_x000D_
        />_x000D_
_x000D_
    <Button_x000D_
        android:layout_width="220dp"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:layout_centerInParent="true"_x000D_
        android:text="BUILD IT BIGGER"_x000D_
        android:id="@+id/button_buildit"_x000D_
        android:gravity="center"_x000D_
        android:layout_below="@+id/textView"_x000D_
        android:padding="20dp"_x000D_
        />_x000D_
_x000D_
    <Button_x000D_
        android:layout_width="220dp"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:layout_centerInParent="true"_x000D_
        android:text="BACON READER"_x000D_
        android:id="@+id/button_bacon"_x000D_
        android:gravity="center"_x000D_
        android:layout_below="@+id/textView"_x000D_
        android:padding="20dp"_x000D_
        />_x000D_
_x000D_
    <Button_x000D_
        android:layout_width="220dp"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:layout_centerInParent="true"_x000D_
        android:text="CAPSTONE: MY OWN APP"_x000D_
        android:id="@+id/button_capstone"_x000D_
        android:gravity="center"_x000D_
        android:layout_below="@+id/textView"_x000D_
        android:padding="20dp"_x000D_
        />_x000D_
_x000D_
</LinearLayout>
_x000D_
_x000D_
_x000D_

How to bind Events on Ajax loaded Content?

Important step for Event binding on Ajax loading content...

01. First of all unbind or off the event on selector

$(".SELECTOR").off();

02. Add event listener on document level

$(document).on("EVENT", '.SELECTOR', function(event) { 
    console.log("Selector event occurred");
});

Make one div visible and another invisible

I don't think that you really want an iframe, do you?

Unless you're doing something weird, you should be getting your results back as JSON or (in the worst case) XML, right?

For your white box / extra space issue, try

style="display: none;"

instead of

style="visibility: hidden;"

Row count where data exists

This works for me. Returns the number that Excel displays in the bottom status line when a pivot column is filtered and I need the count of the visible cells.

Global Const DashBoardSheet = "DashBoard"
Global Const ProfileColRng = "$L:$L"
.
.
.
Sub MySub()
Dim myreccnt as long
.
.
.
myreccnt = GetFilteredPivotRowCount(DashBoardSheet, ProfileColRng)
.
.
.
End Sub

Function GetFilteredPivotRowCount(sheetname As String, cntrange As String) As long

Dim reccnt As Long

reccnt = Sheets(sheetname).Range(cntrange).SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count - 1

GetFilteredPivotRowCount = reccnt

End Function

How to set web.config file to show full error message

If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

Is there functionality to generate a random character in Java?

There are many ways to do this, but yes, it involves generating a random int (using e.g. java.util.Random.nextInt) and then using that to map to a char. If you have a specific alphabet, then something like this is nifty:

    import java.util.Random;

    //...

    Random r = new Random();

    String alphabet = "123xyz";
    for (int i = 0; i < 50; i++) {
        System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
    } // prints 50 random characters from alphabet

Do note that java.util.Random is actually a pseudo-random number generator based on the rather weak linear congruence formula. You mentioned the need for cryptography; you may want to investigate the use of a much stronger cryptographically secure pseudorandom number generator in that case (e.g. java.security.SecureRandom).

What's the difference between size_t and int in C++?

From the friendly Wikipedia:

The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.

The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.

Also, check Why size_t matters

How to delete duplicate rows in SQL Server?

It can be done by many ways in sql server the most simplest way to do so is: Insert the distinct rows from the duplicate rows table to new temporary table. Then delete all the data from duplicate rows table then insert all data from temporary table which has no duplicates as shown below.

select distinct * into #tmp From table
   delete from table
   insert into table
   select * from #tmp drop table #tmp

   select * from table

Delete duplicate rows using Common Table Expression(CTE)

With CTE_Duplicates as 
(select id,name , row_number() 
over(partition by id,name order by id,name ) rownumber  from table  ) 
delete from CTE_Duplicates where rownumber!=1

Change status bar text color to light in iOS 9 with Objective-C

Using a UINavigationController and setting its navigation bar's barStyle to .Black. past this line in your AppDelegate.m file.

navigationController.navigationBar.barStyle = UIBarStyleBlack;

If you are not using UINavigationController then add following code in your ViewController.m file.

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

And call the method to this line :

[self setNeedsStatusBarAppearanceUpdate];

Angularjs: Get element in controller

I dont know what do you exactly mean but hope it help you.
by this directive you can access the DOM element inside controller
this is sample that help you to focus element inside controller

.directive('scopeElement', function () {
    return {
        restrict:"A", // E-Element A-Attribute C-Class M-Comments
        replace: false,
        link: function($scope, elem, attrs) {
            $scope[attrs.scopeElement] = elem[0];
        }
    };
})

now, inside HTML

<input scope-element="txtMessage" >

then, inside controller :

.controller('messageController', ['$scope', function ($scope) {
    $scope.txtMessage.focus();
}])

receiver type *** for instance message is a forward declaration

There are two related error messages that may tell you something is wrong with declarations and/or imports.

The first is the one you are referring to, which can be generated by NOT putting an #import in your .m (or .pch file) while declaring an @class in your .h.

The second you might see, if you had a method in your States class like:

- (void)logout:(NSTimer *)timer

after adding the #import is this:

No visible @interface for "States" declares the selector 'logout:'

If you see this, you need to check and see if you declared your "logout" method (in this instance) in the .h file of the class you're importing or forwarding.

So in your case, you would need a:

- (void)logout:(NSTimer *)timer;

in your States class's .h to make one or both of these related errors disappear.

Case Insensitive String comp in C

As others have stated, there is no portable function that works on all systems. You can partially circumvent this with simple ifdef:

#include <stdio.h>

#ifdef _WIN32
#include <string.h>
#define strcasecmp _stricmp
#else // assuming POSIX or BSD compliant system
#include <strings.h>
#endif

int main() {
    printf("%d", strcasecmp("teSt", "TEst"));
}

How to remove the last character from a bash grep output

you can strip the beginnings and ends of a string by N characters using this bash construct, as someone said already

$ fred=abcdefg.rpm
$ echo ${fred:1:-4}
bcdefg

HOWEVER, this is not supported in older versions of bash.. as I discovered just now writing a script for a Red hat EL6 install process. This is the sole reason for posting here. A hacky way to achieve this is to use sed with extended regex like this:

$ fred=abcdefg.rpm
$ echo $fred | sed -re 's/^.(.*)....$/\1/g'
bcdefg

Why am I getting "void value not ignored as it ought to be"?

srand doesn't return anything so you can't initialize a with its return value because, well, because it doesn't return a value. Did you mean to call rand as well?

combining results of two select statements

While it is possible to combine the results, I would advise against doing so.

You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

In hadoop1.0:

hadoop fs -rmr /PATH/ON/HDFS

In hadoop2.0:

hdfs dfs -rm -R /PATH/ON/HDFS

Use \ to escape , in path

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

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

The classical answer that works in almost every environment is

SELECT ID, Name, blah, blah
FROM TableB TB
LEFT JOIN TableA TA
ON TB.ID=TA.ID
WHERE TA.ID IS NULL

sometimes NOT EXISTS may be not implemented (not working).

Python math module

import math as m
a=int(input("Enter the no"))
print(m.sqrt(a))

from math import sqrt
print(sqrt(25))

from math import sqrt as s
print(s(25))

from math import *
print(sqrt(25))

All works.

How do I move focus to next input with jQuery?

Use eq to get to specific element.

Documentation about index

_x000D_
_x000D_
$("input").keyup(function () {_x000D_
   var index = $(this).index("input");    _x000D_
   $("input:eq(" + (index +1) + ")").focus(); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />
_x000D_
_x000D_
_x000D_

.NET: Simplest way to send POST with data and read response

Use WebRequest. From Scott Hanselman:

public static string HttpPost(string URI, string Parameters) 
{
   System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
   req.Proxy = new System.Net.WebProxy(ProxyString, true);
   //Add these, as we're doing a POST
   req.ContentType = "application/x-www-form-urlencoded";
   req.Method = "POST";
   //We need to count how many bytes we're sending. 
   //Post'ed Faked Forms should be name=value&
   byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
   req.ContentLength = bytes.Length;
   System.IO.Stream os = req.GetRequestStream ();
   os.Write (bytes, 0, bytes.Length); //Push it out there
   os.Close ();
   System.Net.WebResponse resp = req.GetResponse();
   if (resp== null) return null;
   System.IO.StreamReader sr = 
         new System.IO.StreamReader(resp.GetResponseStream());
   return sr.ReadToEnd().Trim();
}

Get index of a key in json

Its too late, but it may be simple and useful

var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };
var keytoFind = "key2";
var index = Object.keys(json).indexOf(keytoFind);
alert(index);

Unit Tests not discovered in Visual Studio 2017

In my case, I target the test project to x64 Architecture and the test setting Architecture (test > Default Processor Architecture) changed was set to x86. They didn't match.

After setting the test setting Architecture back to x64 and rebuilding, all tests were discovered again.

How to change fonts in matplotlib (python)?

I prefer to employ:

from matplotlib import rc
#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('font',**{'family':'serif','serif':['Times']})
rc('text', usetex=True)

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

File Upload ASP.NET MVC 3.0

I am giving you the simple and easy method to understand and learn.

First you have to write the following code in your .Cshtml file.

<input name="Image" type="file" class="form-control" id="resume" />

then in your controller put following code:

if (i > 0) {
    HttpPostedFileBase file = Request.Files["Image"];


    if (file != null && file.ContentLength > 0) {
        if (!string.IsNullOrEmpty(file.FileName)) {
            string extension = Path.GetExtension(file.FileName);

            switch ((extension.ToLower())) {
                case ".doc":
                    break;
                case ".docx":
                    break;
                case ".pdf":
                    break;
                default:
                    ViewBag.result = "Please attach file with extension .doc , .docx , .pdf";
                    return View();
            }

            if (!Directory.Exists(Server.MapPath("~") + "\\Resume\\")) {
                System.IO.Directory.CreateDirectory(Server.MapPath("~") + "\\Resume\\");
            }

            string documentpath = Server.MapPath("~") + "\\Resume\\" + i + "_" + file.FileName;
            file.SaveAs(documentpath);
            string filename = i + "_" + file.FileName;
            result = _objbalResume.UpdateResume(filename, i);
            Attachment at = new Attachment(documentpath);

            //ViewBag.result = (ans == true ? "Thanks for contacting us.We will reply as soon as possible" : "There is some problem. Please try again later.");
        }
    } else {
        ...
    }
}

For this you have to make BAL and DAL layer as per your Database.

Broadcast receiver for checking internet connection in android app

CONNECTIVITY_ACTION docs:

Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

How to pass multiple checkboxes using jQuery ajax post

From the jquery docs for POST (3rd example):

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like

var data = { 'user_ids[]' : []};
$(":checked").each(function() {
  data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);

How to apply a CSS filter to a background image

If you want to content to be scrollable, set the position of the content to absolute:

content {
   position: absolute;
   ...
}

I don't know if this was just for me, but if not that's the fix!

Also since the background is fixed, it means you have a "parallax" effect! So now, not only did this person teach you how to make a blurry background, but it is also a parallax background effect!

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

Iif equivalent in C#

VB.NET:

If(someBool, "true", "false")

C#

someBool ? "true" : "false";

How to insert the current timestamp into MySQL database using a PHP insert query

Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.

You can modify your query to use double quotes at the beginning and end, and single quotes around $somename:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

This line seems to sum up the crux of your problem:

The issue with this is that now you can't call any new methods (only overrides) on the implementing class, as your object reference variable has the interface type.

You are pretty stuck in your current implementation, as not only do you have to attempt a cast, you also need the definition of the method(s) that you want to call on this subclass. I see two options:

1. As stated elsewhere, you cannot use the String representation of the Class name to cast your reflected instance to a known type. You can, however, use a String equals() test to determine whether your class is of the type that you want, and then perform a hard-coded cast:

try {
   String className = "com.path.to.ImplementationType";// really passed in from config
   Class c = Class.forName(className);
   InterfaceType interfaceType = (InterfaceType)c.newInstance();
   if (className.equals("com.path.to.ImplementationType") {
      ((ImplementationType)interfaceType).doSomethingOnlyICanDo();
   } 
} catch (Exception e) {
   e.printStackTrace();
}

This looks pretty ugly, and it ruins the nice config-driven process that you have. I dont suggest you do this, it is just an example.

2. Another option you have is to extend your reflection from just Class/Object creation to include Method reflection. If you can create the Class from a String passed in from a config file, you can also pass in a method name from that config file and, via reflection, get an instance of the Method itself from your Class object. You can then call invoke(http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object, java.lang.Object...)) on the Method, passing in the instance of your class that you created. I think this will help you get what you are after.

Here is some code to serve as an example. Note that I have taken the liberty of hard coding the params for the methods. You could specify them in a config as well, and would need to reflect on their class names to define their Class obejcts and instances.

public class Foo {

    public void printAMessage() {
    System.out.println(toString()+":a message");
    }
    public void printAnotherMessage(String theString) {
        System.out.println(toString()+":another message:" + theString);
    }

    public static void main(String[] args) {
        Class c = null;
        try {
            c = Class.forName("Foo");
            Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{});
            Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class});
            Object o = c.newInstance();
            System.out.println("this is my instance:" + o.toString());
            method1.invoke(o);
            method2.invoke(o, "this is my message, from a config file, of course");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException nsme){
            nsme.printStackTrace();
        } catch (IllegalAccessException iae) {
            iae.printStackTrace();
        } catch (InstantiationException ie) {
            ie.printStackTrace();
        } catch (InvocationTargetException ite) {
            ite.printStackTrace();
        }
    }
}

and my output:

this is my instance:Foo@e0cf70
Foo@e0cf70:a message
Foo@e0cf70:another message:this is my message, from a config file, of course

Initializing array of structures

There's no "step-by-step" here. When initialization is performed with constant expressions, the process is essentially performed at compile time. Of course, if the array is declared as a local object, it is allocated locally and initialized at run-time, but that can be still thought of as a single-step process that cannot be meaningfully subdivided.

Designated initializers allow you to supply an initializer for a specific member of struct object (or a specific element of an array). All other members get zero-initialized. So, if my_data is declared as

typedef struct my_data {
  int a;
  const char *name;
  double x;
} my_data;

then your

my_data data[]={
    { .name = "Peter" },
    { .name = "James" },
    { .name = "John" },
    { .name = "Mike" }
};

is simply a more compact form of

my_data data[4]={
    { 0, "Peter", 0 },
    { 0, "James", 0 },
    { 0, "John", 0 },
    { 0, "Mike", 0 }
};

I hope you know what the latter does.

How can I convert a string to a number in Perl?

This is a simple solution:

Example 1

my $var1 = "123abc";
print $var1 + 0;

Result

123

Example 2

my $var2 = "abc123";
print $var2 + 0;

Result

0

What is Java Servlet?

A servlet at its very core is a java class; which can handle HTTP requests. Typically the internal nitty-gritty of reading a HTTP request and response over the wire is taken care of by the containers like Tomcat. This is done so that as a server side developer you can focus on what to do with the HTTP request and responses and not bother about dealing with code that deals with networking etc. The container will take care of things like wrapping the whole thing in a HTTP response object and send it over to the client (say a browser).

Now the next logical question to ask is who decides what is a container supposed to do? And the answer is; In Java world at least It is guided (note I did not use the word controlled) by specifications. For example Servlet specifications (See resource 2) dictates what a servlet must be able to do. So if you can write an implementation for the specification, congratulations you just created a container (Technically containers like Tomcat also implement other specifications and do tricky stuff like custom class loaders etc but you get the idea).

Assuming you have a container, your servlets are now java classes whose lifecycle will be maintained by the container but their reaction to incoming HTTP requests will be decided by you. You do that by writing what-you-want-to-do in the pre-defined methods like init(), doGet(), doPost() etc. Look at Resource 3.

Here is a fun exercise for you. Create a simple servlet like in Resource 3 and write a few System.out.println() statements in it's constructor method (Yes you can have a constructor of a servlet), init(), doGet(), doPost() methods and run the servlet in tomcat. See the console logs and tomcat logs.

Hope this helps, happy learning.

Resources

  1. Look how the HTTP servlet looks here(Tomcat example).

  2. Servlet Specification.

  3. Simple Servlet example.

  4. Start reading the book online/PDF It also provides you download of the whole book. May be this will help. if you are just starting servlets may be it's a good idea to read the material along with the servlet API. it's a slower process of learning, but is way more helpful in getting the basics clear.

Cut off text in string after/before separator in powershell

$text = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"

$text.split(';')[1].split(' ')

JavaScript split String with white space

Although this is not supported by all browsers, if you use capturing parentheses inside your regular expression then the captured input is spliced into the result.

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. [reference)

So:

var stringArray = str.split(/(\s+)/);
                             ^   ^
//

Output:

["my", " ", "car", " ", "is", " ", "red"]

This collapses consecutive spaces in the original input, but otherwise I can't think of any pitfalls.

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

Cannot construct instance of - Jackson

You cannot instantiate an abstract class, Jackson neither. You should give Jackson information on how to instantiate MyAbstractClass with a concrete type.

See this answer on stackoverflow: Jackson JSON library: how to instantiate a class that contains abstract fields

And maybe also see Jackson Polymorphic Deserialization

Download file through an ajax call php

I have accomplished this with a hidden iframe. I use perl, not php, so will just give concept, not code solution.

Client sends Ajax request to server, causing the file content to be generated. This is saved as a temp file on the server, and the filename is returned to the client.

Client (javascript) receives filename, and sets the iframe src to some url that will deliver the file, like:

$('iframe_dl').src="/app?download=1&filename=" + the_filename

Server slurps the file, unlinks it, and sends the stream to the client, with these headers:

Content-Type:'application/force-download'
Content-Disposition:'attachment; filename=the_filename'

Works like a charm.

How can I call controller/view helper methods from the console in Ruby on Rails?

If you have added your own helper and you want its methods to be available in console, do:

  1. In the console execute include YourHelperName
  2. Your helper methods are now available in console, and use them calling method_name(args) in the console.

Example: say you have MyHelper (with a method my_method) in 'app/helpers/my_helper.rb`, then in the console do:

  1. include MyHelper
  2. my_helper.my_method

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

Python 3.4.0 with MySQL database

mysqlclient is a fork of MySQLdb and can serve as a drop-in replacement with Python 3.4 support. If you have trouble building it on Windows, you can download it from Christoph Gohlke's Unofficial Windows Binaries for Python Extension Packages

Artisan, creating tables in database

in laravel 5 first we need to create migration and then run the migration

Step 1.

php artisan make:migration create_users_table --create=users

Step 2.

php artisan migrate

WPF binding to Listbox selectedItem

Yocoder is right,

Inside the DataTemplate, your DataContext is set to the Rule its currently handling..

To access the parents DataContext, you can also consider using a RelativeSource in your binding:

<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ____Your Parent control here___ }}, Path=DataContext.SelectedRule.Name}" />

More info on RelativeSource can be found here:

http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.aspx

Violation Long running JavaScript task took xx ms

Look in the Chrome console under the Network tab and find the scripts which take the longest to load.

In my case there were a set of Angular add on scripts that I had included but not yet used in the app :

<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-utils/0.1.1/angular-ui-utils.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-animate.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-aria.min.js"></script>

These were the only JavaScript files that took longer to load than the time that the "Long Running Task" error specified.

All of these files run on my other websites with no errors generated but I was getting this "Long Running Task" error on a new web app that barely had any functionality. The error stopped immediately upon removing.

My best guess is that these Angular add ons were looking recursively into increasingly deep sections of the DOM for their start tags - finding none, they had to traverse the entire DOM before exiting, which took longer than Chrome expects - thus the warning.