Programs & Examples On #Session variables

Session variable is a unit of information within a session state. It is maintained across a user's visit within the constraints of the stateless HTTP protocol.

How to use sessions in an ASP.NET MVC 4 application?

Try

//adding data to session
//assuming the method below will return list of Products

var products=Db.GetProducts();

//Store the products to a session

Session["products"]=products;

//To get what you have stored to a session

var products=Session["products"] as List<Product>;

//to clear the session value

Session["products"]=null;

How to use store and use session variables across pages?

In the possibility that the second page doesn't have shared access to the session cookie, you'll need to set the session cookie path using session_set_cookie_params:

<?php
session_set_cookie_params( $lifetime, '/shared/path/to/files/' );
session_start();
$_SESSION['myvar']='myvalue';

And

<?php
session_set_cookie_params( $lifetime, '/shared/path/to/files/' );
session_start();
echo("1");
if(isset($_SESSION['myvar']))
{
    echo("2");
   if($_SESSION['myvar'] == 'myvalue')
   {
       echo("3");
       exit;
   }
}

HttpContext.Current.Session is null when routing requests

It seems that you have forgotten to add your state server address in the config file.

 <sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />

MySQL wait_timeout Variable - GLOBAL vs SESSION

As noted by Riedsio, the session variables do not change after connecting unless you specifically set them; setting the global variable only changes the session value of your next connection.

For example, if you have 100 connections and you lower the global wait_timeout then it will not affect the existing connections, only new ones after the variable was changed.

Specifically for the wait_timeout variable though, there is a twist. If you are using the mysql client in the interactive mode, or the connector with CLIENT_INTERACTIVE set via mysql_real_connect() then you will see the interactive_timeout set for @@session.wait_timeout

Here you can see this demonstrated:

> ./bin/mysql -Bsse 'select @@session.wait_timeout, @@session.interactive_timeout, @@global.wait_timeout, @@global.interactive_timeout' 
70      60      70      60

> ./bin/mysql -Bsse 'select @@wait_timeout'                                                                                                 
70

> ./bin/mysql                                                                                                                               
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.12-5 MySQL Community Server (GPL)

Copyright (c) 2009-2016 Percona LLC and/or its affiliates
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select @@wait_timeout;
+----------------+
| @@wait_timeout |
+----------------+
|             60 |
+----------------+
1 row in set (0.00 sec)

So, if you are testing this using the client it is the interactive_timeout that you will see when connecting and not the value of wait_timeout

Set session variable in laravel

To add to the above answers, ensure you define your function like this:

public function functionName(Request $request)  {
       //
}

Note the "(Request $request)", now set a session like this:

$request->session()->put('key', 'value');

And retrieve the session in this way:

$data = $request->session()->get('key');

To erase the session try this:

$request->session()->forget('key');  

or

$request->session()->flush();

How to access session variables from any class in ASP.NET?

The answers presented before mine provide apt solutions to the problem, however, I feel that it is important to understand why this error results:

The Session property of the Page returns an instance of type HttpSessionState relative to that particular request. Page.Session is actually equivalent to calling Page.Context.Session.

MSDN explains how this is possible:

Because ASP.NET pages contain a default reference to the System.Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an .aspx page without the fully qualified class reference to HttpContext.

However, When you try to access this property within a class in App_Code, the property will not be available to you unless your class derives from the Page Class.

My solution to this oft-encountered scenario is that I never pass page objects to classes. I would rather extract the required objects from the page Session and pass them to the Class in the form of a name-value collection / Array / List, depending on the case.

Local storage in Angular 2

To set the item or object in local storage:

   localStorage.setItem('yourKey', 'yourValue');

To get the item or object in local storage, you must remember your key.

   let yourVariable = localStorage.getItem('yourKey');

To remove it from local storage:

   localStorage.removeItem('yourKey');

How to empty/destroy a session in rails?

add this code to your ApplicationController

def reset_session
  @_request.reset_session
end

( Dont know why no one above just mention this code as it fixed my problem ) http://apidock.com/rails/ActionController/RackDelegation/reset_session

Check if PHP session has already started

Recommended way for versions of PHP >= 5.4.0 , PHP 7

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

Reference: http://www.php.net/manual/en/function.session-status.php

For versions of PHP < 5.4.0

if(session_id() == '') {
    session_start();
}

Session variables not working php

I had similar issue and with the cookie domain:

    ini_set('session.cookie_domain', '.domain.com');

the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.

Setting a PHP $_SESSION['var'] using jQuery

I also designed a "php session value setter" solution by myself (similar to Luke Dennis' solution. No big deal here), but after setting my session value, my needs were "jumping onto another .php file". Ok, I did it, inside my jquery code... But something didn't quite work...

My problem was kind of easy:

-After you "$.post" your values onto the small .php file, you should wait for some "success/failure" return value, and ONLY AFTER READING THIS SUCCESS VALUE, perform the jump. If you just immediately jump onto the next big .php file, your session value might have not become set onto the php sessions runtime engine, and will you probably read "empty" when doing $_SESSION["my_var"]; from the destination .php file.

In my case, to correct that situation, I changed my jQuery $.post code this way:

$.post('set_session_value.php', { key: 'keyname', value: 'myvalue'}, function(ret){
    if(ret==0){
        window.alert("success!");
        location.replace("next_page.php");
    }
    else{
        window.alert("error!");
    }
});

Of course, your "set_session_value.php" file, should return 'echo "0"; ' or 'echo "1"; ' (or whatever success values you might need).

Greetings.

Setting session variable using javascript

You can use

sessionStorage.SessionName = "SessionData" ,

sessionStorage.getItem("SessionName") and

sessionStorage.setItem("SessionName","SessionData");

See the supported browsers on http://caniuse.com/namevalue-storage

Session variables in ASP.NET MVC

The answer here is correct, I however struggled to implement it in an ASP.NET MVC 3 app. I wanted to access a Session object in a controller and couldn't figure out why I kept on getting a "Instance not set to an instance of an Object error". What I noticed is that in a controller when I tried to access the session by doing the following, I kept on getting that error. This is due to the fact that this.HttpContext is part of the Controller object.

this.Session["blah"]
// or
this.HttpContext.Session["blah"]

However, what I wanted was the HttpContext that's part of the System.Web namespace because this is the one the Answer above suggests to use in Global.asax.cs. So I had to explicitly do the following:

System.Web.HttpContext.Current.Session["blah"]

this helped me, not sure if I did anything that isn't M.O. around here, but I hope it helps someone!

How do servlets work? Instantiation, sessions, shared variables and multithreading

Sessions - what Chris Thompson said.

Instantiation - a servlet is instantiated when the container receives the first request mapped to the servlet (unless the servlet is configured to load on startup with the <load-on-startup> element in web.xml). The same instance is used to serve subsequent requests.

jQuery select all except first

Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first) is slowed down by that evaluation.

An equally fast and easy to read solution is using the function version .not(":first"):

e.g.

$("li").not(":first").hide();

JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

This is only few percentage points slower than slice(1), but is very readable as "I want all except the first one".

Getting all types in a namespace via reflection

Quite simple

Type[] types = Assembly.Load(new AssemblyName("mynamespace.folder")).GetTypes();
foreach (var item in types)
{
}

How do I check for vowels in JavaScript?

Lots of answers available, speed is irrelevant for such small functions unless you are calling them a few hundred thousand times in a short period of time. For me, a regular expression is best, but keep it in a closure so you don't build it every time:

Simple version:

function vowelTest(s) {
  return (/^[aeiou]$/i).test(s);
}

More efficient version:

var vowelTest = (function() {
  var re = /^[aeiou]$/i;
  return function(s) {
    return re.test(s);
  }
})();

Returns true if s is a single vowel (upper or lower case) and false for everything else.

How to list all the files in a commit?

I like this:

git diff --name-status <SHA1> <SHA1>^

On a CSS hover event, can I change another div's styling?

A pure solution without jQuery:

Javascript (Head)

function chbg(color) {
    document.getElementById('b').style.backgroundColor = color;
}   

HTML (Body)

<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>

JSFiddle: http://jsfiddle.net/YShs2/

Having a UITextField in a UITableViewCell

Try this one. It can handle scrolling as well and you can reuse the cells without the hassle of removing subviews you added before.

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
    return 10;
}   

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"Cell"];
    if( cell == nil)
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];   

    cell.textLabel.text = [[NSArray arrayWithObjects:@"First",@"Second",@"Third",@"Forth",@"Fifth",@"Sixth",@"Seventh",@"Eighth",@"Nineth",@"Tenth",nil] 
                           objectAtIndex:indexPath.row];

    if (indexPath.row % 2) {
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 21)];
        textField.placeholder = @"Enter Text";
        textField.text = [inputTexts objectAtIndex:indexPath.row/2];
        textField.tag = indexPath.row/2;
        textField.delegate = self;
        cell.accessoryView = textField;
        [textField release];
    } else
        cell.accessoryView = nil;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;        
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    [inputTexts replaceObjectAtIndex:textField.tag withObject:textField.text];
    return YES;
}

- (void)viewDidLoad {
    inputTexts = [[NSMutableArray alloc] initWithObjects:@"",@"",@"",@"",@"",nil];
    [super viewDidLoad];
}

Replace contents of factor column in R dataframe

A more general solution that works with all the data frame at once and where you don't have to add new factors levels is:

data.mtx <- as.matrix(data.df)
data.mtx[which(data.mtx == "old.value.to.replace")] <- "new.value"
data.df <- as.data.frame(data.mtx)

A nice feature of this code is that you can assign as many values as you have in your original data frame at once, not only one "new.value", and the new values can be random values. Thus you can create a complete new random data frame with the same size as the original.

How to serve an image using nodejs

2016 Update

Examples with Express and without Express that actually work

This question is over 5 years old but every answer has some problems.

TL;DR

Scroll down for examples to serve an image with:

  1. express.static
  2. express
  3. connect
  4. http
  5. net

All of the examples are also on GitHub: https://github.com/rsp/node-static-http-servers

Test results are available on Travis: https://travis-ci.org/rsp/node-static-http-servers

Introduction

After over 5 years since this question was asked there is only one correct answer by generalhenry but even though that answer has no problems with the code, it seems to have some problems with reception. It was commented that it "doesn't explain much other than how to rely on someone else to get the job done" and the fact how many people have voted this comment up clearly shows that a lot of things need clarification.

First of all, a good answer to "How to serve images using Node.js" is not implementing a static file server from scratch and doing it badly. A good answer is using a module like Express that does the job correctly.

Answering comments that say that using Express "doesn't explain much other than how to rely on someone else to get the job done" it should be noted, that using the http module already relies on someone else to get the job done. If someone doesn't want to rely on anyone to get the job done then at least raw TCP sockets should be used instead - which I do in one of my examples below.

A more serious problem is that all of the answers here that use the http module are broken. They introduce race conditions, insecure path resolution that will lead to path traversal vulnerability, blocking I/O that will completely fail to serve any concurrent requests at all and other subtle problems - they are completely broken as examples of what the question asks about, and yet they already use the abstraction that is provided by the http module instead of using TCP sockets so they don't even do everything from scratch as they claim.

If the question was "How to implement static file server from scratch, as a learning exercise" then by all means answers how to do that should be posted - but even then we should expect them to at least be correct. Also, it is not unreasonable to assume that someone who wants to serve an image might want to serve more images in the future so one could argue that writing a specific custom static file server that can serve only one single file with hard-coded path is somewhat shortsighted. It seems hard to imagine that anyone who searches for an answer on how to serve an image would be content with a solution that serves just a single image instead of a general solution to serve any image.

In short, the question is how to serve an image and an answer to that is to use an appropriate module to do that in a secure, preformant and reliable way that is readable, maintainable and future-proof while using the best practice of professional Node development. But I agree that a great addition to such an answer would be showing a way to implement the same functionality manually but sadly every attempt to do that has failed so far. And that is why I wrote some new examples.

After this short introduction, here are my five examples doing the job on 5 different levels of abstraction.

Minimum functionality

Every example serves files from the public directory and supports the minumum functionality of:

  • MIME types for most common files
  • serves HTML, JS, CSS, plain text and images
  • serves index.html as a default directory index
  • responds with error codes for missing files
  • no path traversal vulnerabilities
  • no race conditions while reading files

I tested every version on Node versions 4, 5, 6 and 7.

express.static

This version uses the express.static built-in middleware of the express module.

This example has the most functionality and the least amount of code.

var path = require('path');
var express = require('express');
var app = express();

var dir = path.join(__dirname, 'public');

app.use(express.static(dir));

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

express

This version uses the express module but without the express.static middleware. Serving static files is implemented as a single route handler using streams.

This example has simple path traversal countermeasures and supports a limited set of most common MIME types.

var path = require('path');
var express = require('express');
var app = express();
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

app.get('*', function (req, res) {
    var file = path.join(dir, req.path.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        return res.status(403).end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.set('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.set('Content-Type', 'text/plain');
        res.status(404).end('Not found');
    });
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

connect

This version uses the connect module which is a one level of abstraction lower than express.

This example has similar functionality to the express version but using slightly lower-lever APIs.

var path = require('path');
var connect = require('connect');
var app = connect();
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

app.use(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

http

This version uses the http module which is the lowest-level API for HTTP in Node.

This example has similar functionality to the connect version but using even more lower-level APIs.

var path = require('path');
var http = require('http');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = http.createServer(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

net

This version uses the net module which is the lowest-level API for TCP sockets in Node.

This example has some of the functionality of the http version but the minimal and incomplete HTTP protocol has been implemented from scratch. Since it doesn't support chunked encoding it loads the files into memory before serving them to know the size before sending a response because statting the files and then loading would introduce a race condition.

var path = require('path');
var net = require('net');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = net.createServer(function (con) {
    var input = '';
    con.on('data', function (data) {
        input += data;
        if (input.match(/\n\r?\n\r?/)) {
            var line = input.split(/\n/)[0].split(' ');
            var method = line[0], url = line[1], pro = line[2];
            var reqpath = url.toString().split('?')[0];
            if (method !== 'GET') {
                var body = 'Method not implemented';
                con.write('HTTP/1.1 501 Not Implemented\n');
                con.write('Content-Type: text/plain\n');
                con.write('Content-Length: '+body.length+'\n\n');
                con.write(body);
                con.destroy();
                return;
            }
            var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
            if (file.indexOf(dir + path.sep) !== 0) {
                var body = 'Forbidden';
                con.write('HTTP/1.1 403 Forbidden\n');
                con.write('Content-Type: text/plain\n');
                con.write('Content-Length: '+body.length+'\n\n');
                con.write(body);
                con.destroy();
                return;
            }
            var type = mime[path.extname(file).slice(1)] || 'text/plain';
            var s = fs.readFile(file, function (err, data) {
                if (err) {
                    var body = 'Not Found';
                    con.write('HTTP/1.1 404 Not Found\n');
                    con.write('Content-Type: text/plain\n');
                    con.write('Content-Length: '+body.length+'\n\n');
                    con.write(body);
                    con.destroy();
                } else {
                    con.write('HTTP/1.1 200 OK\n');
                    con.write('Content-Type: '+type+'\n');
                    con.write('Content-Length: '+data.byteLength+'\n\n');
                    con.write(data);
                    con.destroy();
                }
            });
        }
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

Download examples

I posted all of the examples on GitHub with more explanation.

Examples with express.static, express, connect, http and net:

Other project using only express.static:

Tests

Test results are available on Travis:

Everything is tested on Node versions 4, 5, 6, and 7.

See also

Other related answers:

error C2039: 'string' : is not a member of 'std', header file problem

Your FMAT.h requires a definition of std::string in order to complete the definition of class FMAT. In FMAT.cpp, you've done this by #include <string> before #include "FMAT.h". You haven't done that in your main file.

Your attempt to forward declare string was incorrect on two levels. First you need a fully qualified name, std::string. Second this works only for pointers and references, not for variables of the declared type; a forward declaration doesn't give the compiler enough information about what to embed in the class you're defining.

SQL Group By with an Order By

You can get around this limit with the deprecated syntax: ORDER BY 1 DESC

This syntax is not deprecated at all, it's E121-03 from SQL99.

How to generate auto increment field in select query

In the case you have no natural partition value and just want an ordered number regardless of the partition you can just do a row_number over a constant, in the following example i've just used 'X'. Hope this helps someone

select 
    ROW_NUMBER() OVER(PARTITION BY num ORDER BY col1) as aliascol1, 
    period_next_id, period_name_long
from 
(
  select distinct col1, period_name_long, 'X' as num
  from {TABLE} 
) as x

End of File (EOF) in C

EOF is -1 because that's how it's defined. The name is provided by the standard library headers that you #include. They make it equal to -1 because it has to be something that can't be mistaken for an actual byte read by getchar(). getchar() reports the values of actual bytes using positive number (0 up to 255 inclusive), so -1 works fine for this.

The != operator means "not equal". 0 stands for false, and anything else stands for true. So what happens is, we call the getchar() function, and compare the result to -1 (EOF). If the result was not equal to EOF, then the result is true, because things that are not equal are not equal. If the result was equal to EOF, then the result is false, because things that are equal are not (not equal).

The call to getchar() returns EOF when you reach the "end of file". As far as C is concerned, the 'standard input' (the data you are giving to your program by typing in the command window) is just like a file. Of course, you can always type more, so you need an explicit way to say "I'm done". On Windows systems, this is control-Z. On Unix systems, this is control-D.

The example in the book is not "wrong". It depends on what you actually want to do. Reading until EOF means that you read everything, until the user says "I'm done", and then you can't read any more. Reading until '\n' means that you read a line of input. Reading until '\0' is a bad idea if you expect the user to type the input, because it is either hard or impossible to produce this byte with a keyboard at the command prompt :)

Eclipse and Windows newlines

You could give it a try. The problem is that Windows inserts a carriage return as well as a line feed when given a new line. Unix-systems just insert a line feed. So the extra carriage return character could be the reason why your eclipse messes up with the newlines.

Grab one or two files from your project and convert them. You could use Notepad++ to do so. Just open the file, go to Format->Convert to Unix (when you are using windows).

In Linux just try this on a command line:

sed 's/$'"/`echo \\\r`/" yourfile.java > output.java

How do I rename a Git repository?

To rename any repository of your GitHub account:

  1. Go to that particular repository which you want to rename
  2. Navigate to the settings tab
  3. There, in the repository name section, type the new name you want to put and click Rename

Get the element triggering an onclick event in jquery?

It's top google stackoverflow question, but all answers are not jQuery related!

$(".someclass").click(
    function(event)
    {
        console.log(event, this);
    }
);

'event' contains 2 important values:

event.currentTarget - element to which event is triggered ('.someclass' element)

event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)

this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)

When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.

How to set editable true/false EditText in Android programmatically?

Since setEditable(false) is deprecated, use textView.setKeyListener(null); to make editText non-clickable.

Python function global variables?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

Bootstrap 3.0: How to have text and input on same line?

just give mother of div "class="col-lg-12""

<div class="form-group">
<div class="row">
    <div class="col-xs-3">
        <label for="class_type"><h2><span class=" label label-primary">Class Type</span></h2></label>
    </div>
    <div class="col-xs-2">
        <select name="class_type" id="class_type" class="  form-control input-lg" style="width:200px" autocomplete="off">
            <option >Economy</option>
            <option >Premium Economy</option>
            <option >Club World</option>
            <option >First Class</option>
        </select>
    </div>
 </div>

it will be

<div class="form-group">
<div class="col-lg-12">
  <div class="row">
    <div class="col-xs-3">
        <label for="class_type"><h2><span class=" label label-primary">Class Type</span></h2></label>
    </div>
    <div class="col-xs-2">
        <select name="class_type" id="class_type" class="  form-control input-lg" style="width:200px" autocomplete="off">
            <option >Economy</option>
            <option >Premium Economy</option>
            <option >Club World</option>
            <option >First Class</option>
        </select>
    </div>
</div>
</div>

Pretty Printing a pandas dataframe

A simple approach is to output as html, which pandas does out of the box:

df.to_html('temp.html')

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

Using jQuery's ajax method to retrieve images as a blob

A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
//          set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
   var postEnc, method;
   if (post == null)
   {
      postEnc = '';
      method = 'GET';
   }
   else
   {
      method = 'POST';
      postEnc = new FormData();
      for(var i in post)
         postEnc.append(i, post[i]);
   }
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200)
      {
         var res = this.response;
         var reader = new window.FileReader();
         reader.readAsDataURL(res); 
         reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
      }
   }
   xhr.open(method, url);
   xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   xhr.send('fname=Henry&lname=Ford');
   xhr.responseType = 'blob';
   xhr.send(postEnc);
}

How can I split a text into sentences?

Also, be wary of additional top level domains that aren't included in some of the answers above.

For example .info, .biz, .ru, .online will throw some sentence parsers but aren't included above.

Here's some info on frequency of top level domains: https://www.westhost.com/blog/the-most-popular-top-level-domains-in-2017/

That could be addressed by editing the code above to read:

alphabets= "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov|ai|edu|co.uk|ru|info|biz|online)"

How to export/import PuTTy sessions list?

Using this method it is also possible to perform mass configuration changes, such as changing the all sessions font.

  1. Export to .reg
  2. Perform a search and replace over .reg
  3. Remove all sessions
  4. Import the new .reg

Extracted from here: http://www.sysadmit.com/2015/11/putty-exportar-configuracion.html

Does Arduino use C or C++?

Arduino doesn't run either C or C++. It runs machine code compiled from either C, C++ or any other language that has a compiler for the Arduino instruction set.

C being a subset of C++, if Arduino can "run" C++ then it can "run" C.

If you don't already know C nor C++, you should probably start with C, just to get used to the whole "pointer" thing. You'll lose all the object inheritance capabilities though.

Use stored procedure to insert some data into a table

if you want to populate a table in SQL SERVER you can use while statement as follows:

declare @llenandoTabla INT = 0;
while @llenandoTabla < 10000
begin
insert into employeestable // Name of my table
(ID, FIRSTNAME, LASTNAME, GENDER, SALARY) // Parameters of my table
VALUES 
(555, 'isaias', 'perez', 'male', '12220') //values
set @llenandoTabla = @llenandoTabla + 1;
end

Hope it helps.

javascript get x and y coordinates on mouse click

Like this.

_x000D_
_x000D_
function printMousePos(event) {_x000D_
  document.body.textContent =_x000D_
    "clientX: " + event.clientX +_x000D_
    " - clientY: " + event.clientY;_x000D_
}_x000D_
_x000D_
document.addEventListener("click", printMousePos);
_x000D_
_x000D_
_x000D_

MouseEvent - MDN

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.

MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

I have created this jquery that solved my problem.

public void ChangeClassIntoSelected(String name,String div) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
                "   $(element).addClass('ui-selected');\n" +
                "});");
    }

With this script you are able to change the actual class name into some other thing.

How I can check if an object is null in ruby on rails 2?

You can use the simple not flag to validate that. Example

if !@objectname

This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw

*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass

An ideal nil check would be like:

!@objectname || @objectname.nil? || @objectname.empty?

c++ array - expression must have a constant value

one could also use a fixed lengths vector and access it with indexing

int Lcs(string a, string b) 
{
    int x = a.size() + 1;
    int y = b.size() + 1;

    vector<vector<int>> L(x, vector<int>(y));

    for (int i = 1; i < x; i++)
    {
        for (int j = 1; j < y; j++)
        {
            L[i][j] = a[i - 1] == b[j - 1] ?
                L[i - 1][j - 1] + 1 :
                max(L[i - 1][j], L[i][j - 1]);
        }
    }

    return L[a.size()][b.size()];
}

Google Maps API v3 adding an InfoWindow to each marker

Try this:

for (var i in tracks[racer_id].data.points) {
    values = tracks[racer_id].data.points[i];                
    point = new google.maps.LatLng(values.lat, values.lng);
    if (values.qst) {
        var marker = new google.maps.Marker({map: map, position: point, clickable: true});
        tracks[racer_id].markers[i] = marker;
        var info = new google.maps.InfoWindow({
            content: '<b>Speed:</b> ' + values.inst + ' knots'
        });
        tracks[racer_id].info[i] = info;
        google.maps.event.addListener(tracks[racer_id].markers[i], 'click', function() {
            tracks[racer_id].info[i].open(map, tracks[racer_id].markers[i]);
        });
    }
    track_coordinates.push(point);
    bd.extend(point);
}

Rails 4 LIKE query - ActiveRecord adds quotes

While string interpolation will work, as your question specifies rails 4, you could be using Arel for this and keeping your app database agnostic.

def self.search(query, page=1)
  query = "%#{query}%"
  name_match = arel_table[:name].matches(query)
  postal_match = arel_table[:postal_code].matches(query)
  where(name_match.or(postal_match)).page(page).per_page(5)
end

VMWare Player vs VMWare Workstation

Workstation has some features that Player lacks, such as teams (groups of VMs connected by private LAN segments) and multi-level snapshot trees. It's aimed at power users and developers; they even have some hooks for using a debugger on the host to debug code in the VM (including kernel-level stuff). The core technology is the same, though.

How to add data via $.ajax ( serialize() + extra data ) like this

What kind of data?

data: $('#myForm').serialize() + "&moredata=" + morevalue

The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.

Change the default base url for axios

Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution.

To append 'api' to my baseURL, I have my default baseURL set as,

axios.defaults.baseURL = '/api/';

Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'

axios({
    method:'post',
    url:'logout',
    baseURL: '/',
   })
   .then(response => {
      window.location.reload();
   })
   .catch(error => {
       console.log(error);
   });

What is unexpected T_VARIABLE in PHP?

It could be some other line as well. PHP is not always that exact.

Probably you are just missing a semicolon on previous line.

How to reproduce this error, put this in a file called a.php:

<?php
  $a = 5
  $b = 7;        // Error happens here.
  print $b;
?>

Run it:

eric@dev ~ $ php a.php

PHP Parse error:  syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3

Explanation:

The PHP parser converts your program to a series of tokens. A T_VARIABLE is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.

In the simple case above with variable $b, the parser tried to process this:

$a = 5 $b = 7;

The PHP parser looks at the $b after the 5 and says "that is unexpected".

add allow_url_fopen to my php.ini using .htaccess

Try this, but I don't think it will work because you're not supposed to be able to change this

Put this line in an htaccess file in the directory you want the setting to be enabled:

php_value allow_url_fopen On

Note that this setting will only apply to PHP file's in the same directory as the htaccess file.

As an alternative to using url_fopen, try using curl.

How to get the list of all database users

I try to avoid using the "SELECT * " option and just pull what data I want or need. The code below is what I use, you may cull out or add columns and aliases per your needs.

I also us "IIF" (instant if) to replace binary 0 or 1 with a yes or no. It just makes it easier to read for the non-techie that may want this info.

Here is what I use:

SELECT 
    name AS 'User'
  , PRINCIPAL_ID
  , type AS 'User Type'
  , type_desc AS 'Login Type'
  , CAST(create_date AS DATE) AS 'Date Created' 
  , default_database_name AS 'Database Name'
  , IIF(is_fixed_role LIKE 0, 'No', 'Yes') AS 'Is Active'
FROM master.sys.server_principals
WHERE type LIKE 's' OR type LIKE 'u'
ORDER BY [User], [Database Name]; 
GO

Hope this helps.

How do you check what version of SQL Server for a database using TSQL?

Here's a bit of script I use for testing if a server is 2005 or later

declare @isSqlServer2005 bit
select @isSqlServer2005 = case when CONVERT(int, SUBSTRING(CONVERT(varchar(15), SERVERPROPERTY('productversion')), 0, CHARINDEX('.', CONVERT(varchar(15), SERVERPROPERTY('productversion'))))) < 9 then 0 else 1 end
select @isSqlServer2005

Note : updated from original answer (see comment)

What is the difference between POST and GET?

The only "big" difference between POST & GET (when using them with AJAX) is since GET is URL provided, they are limited in ther length (since URL arent infinite in length).

Error in strings.xml file in Android

I use hebrew(RTL language) in strings.xml. I have manually searched the string.xml for this char: ' than I added the escape char \ infront of it (now it looks like \' ) and still got the same error!

I searched again for the char ' and I replaced the char ' with \'(eng writing) , since it shows a right to left it looks like that '\ in the strings.xml !!

Problem solved.

How do I hide an element when printing a web page?

Here is a simple solution put this CSS

@media print{
   .noprint{
       display:none;
   }
}

and here is the HTML

<div class="noprint">
    element that need to be hidden when printing
</div>

Data access object (DAO) in Java

The Data Access Object is basically an object or an interface that provides access to an underlying database or any other persistence storage.

That definition from: http://en.wikipedia.org/wiki/Data_access_object

Check also the sequence diagram here: http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

Maybe a simple example can help you understand the concept:

Let's say we have an entity to represent an employee:

public class Employee {

    private int id;
    private String name;


    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

The employee entities will be persisted into a corresponding Employee table in a database. A simple DAO interface to handle the database operation required to manipulate an employee entity will be like:

interface EmployeeDAO {

    List<Employee> findAll();
    List<Employee> findById();
    List<Employee> findByName();
    boolean insertEmployee(Employee employee);
    boolean updateEmployee(Employee employee);
    boolean deleteEmployee(Employee employee);

}

Next we have to provide a concrete implementation for that interface to deal with SQL server, and another to deal with flat files, etc.

No module named _sqlite3

I had the same problem with Python 3.5 on Ubuntu while using pyenv.

If you're installing the python using pyenv, it's listed as one of the common build problems. To solve it, remove the installed python version, install the requirements (for this particular case libsqlite3-dev), then reinstall the python version.

How to know which is running in Jupyter notebook?

Assuming you have the wrong backend system you can change the backend kernel by creating a new or editing the existing kernel.json in the kernels folder of your jupyter data path jupyter --paths. You can have multiple kernels (R, Python2, Python3 (+virtualenvs), Haskell), e.g. you can create an Anaconda specific kernel:

$ <anaconda-path>/bin/python3 -m ipykernel install --user --name anaconda --display-name "Anaconda"

Should create a new kernel:

<jupyter-data-dir>/kernels/anaconda/kernel.json

{
    "argv": [ "<anaconda-path>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
    "display_name": "Anaconda",
    "language": "python"
}

You need to ensure ipykernel package is installed in the anaconda distribution.

This way you can just switch between kernels and have different notebooks using different kernels.

How can I order a List<string>?

ListaServizi = ListaServizi.OrderBy(q => q).ToList();

How to add a new row to an empty numpy array

The way to "start" the array that you want is:

arr = np.empty((0,3), int)

Which is an empty array but it has the proper dimensionality.

>>> arr
array([], shape=(0, 3), dtype=int64)

Then be sure to append along axis 0:

arr = np.append(arr, np.array([[1,2,3]]), axis=0)
arr = np.append(arr, np.array([[4,5,6]]), axis=0)

But, @jonrsharpe is right. In fact, if you're going to be appending in a loop, it would be much faster to append to a list as in your first example, then convert to a numpy array at the end, since you're really not using numpy as intended during the loop:

In [210]: %%timeit
   .....: l = []
   .....: for i in xrange(1000):
   .....:     l.append([3*i+1,3*i+2,3*i+3])
   .....: l = np.asarray(l)
   .....: 
1000 loops, best of 3: 1.18 ms per loop

In [211]: %%timeit
   .....: a = np.empty((0,3), int)
   .....: for i in xrange(1000):
   .....:     a = np.append(a, 3*i+np.array([[1,2,3]]), 0)
   .....: 
100 loops, best of 3: 18.5 ms per loop

In [214]: np.allclose(a, l)
Out[214]: True

The numpythonic way to do it depends on your application, but it would be more like:

In [220]: timeit n = np.arange(1,3001).reshape(1000,3)
100000 loops, best of 3: 5.93 µs per loop

In [221]: np.allclose(a, n)
Out[221]: True

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Windows - set environment variable permanently:

setx ANDROID_HOME "C:\Program Files\Android\android-sdk"

or

setx ANDROID_HOME "C:\Program Files (x86)\Android\android-sdk"

How do I convert a String to a BigInteger?

Instead of using valueOf(long) and parse(), you can directly use the BigInteger constructor that takes a string argument:

BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");

That should give you the desired value.

Get last 5 characters in a string

The accepted answer of this post will cause error in the case when the string length is lest than 5. So i have a better solution. We can use this simple code :

If(str.Length <= 5, str, str.Substring(str.Length - 5))

You can test it with variable length string.

    Dim str, result As String
    str = "11!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)
    str = "I will be going to school in 2011!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)

Another simple but efficient solution i found :

str.Substring(str.Length - Math.Min(5, str.Length))

How to pass the -D System properties while testing on Eclipse?

Run -> Run configurations, select project, second tab: “Arguments”. Top box is for your program, bottom box is for VM arguments, e.g. -Dkey=value.

How do I get a file's directory using the File object?

File API File.getParent or File.getParentFile should return you Directory of file.

Your code should be like :

    File file = new File("c:\\temp\\java\\testfile");
    if(!file.exists()){
        file = file.getParentFile();
    }

You can additionally check your parent file is directory using File.isDirectory API

if(file.isDirectory()){
    System.out.println("file is directory ");
}

How to plot multiple functions on the same figure, in Matplotlib?

Perhaps a more pythonic way of doing so.

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

t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, t, b, t, c)
plt.show()

enter image description here

What's the purpose of SQL keyword "AS"?

In the early days of SQL, it was chosen as the solution to the problem of how to deal with duplicate column names (see below note).

To borrow a query from another answer:

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
  FROM Products AS P
       INNER JOIN Orders AS O ON O.ProductID = P.ProductID
 WHERE O.OrderID = 123456

The column ProductID (and possibly others) is common to both tables and since the join condition syntax requires reference to both, the 'dot qualification' provides disambiguation.

Of course, the better solution was to never have allowed duplicate column names in the first place! Happily, if you use the newer NATURAL JOIN syntax, the need for the range variables P and O goes away:

SELECT ProductName, ProductRetailPrice, Quantity
  FROM Products NATURAL JOIN Orders
 WHERE OrderID = 123456

But why is the AS keyword optional? My recollection from a personal discussion with a member of the SQL standard committee (either Joe Celko or Hugh Darwen) was that their recollection was that, at the time of defining the standard, one vendor's product (Microsoft's?) required its inclusion and another vendor's product (Oracle's?) required its omission, so the compromise chosen was to make it optional. I have no citation for this, you either believe me or not!


In the early days of the relational model, the cross product (or theta-join or equi-join) of relations whose headings are not disjoint appeared to produce a relation with two attributes of the same name; Codd's solution to this problem in his relational calculus was the use of dot qualification, which was later emulated in SQL (it was later realised that so-called natural join was primitive without loss; that is, natural join can replace all theta-joins and even cross product.)

Source: Business System 12, Notes keyed to slides of the presentation given at TTM Implementers’ Workshop, University of Northumbria, 2-3 June 2011 by Hugh Darwen

How to secure an ASP.NET Web API

I would suggest starting with the most straightforward solutions first - maybe simple HTTP Basic Authentication + HTTPS is enough in your scenario.

If not (for example you cannot use https, or need more complex key management), you may have a look at HMAC-based solutions as suggested by others. A good example of such API would be Amazon S3 (http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html)

I wrote a blog post about HMAC based authentication in ASP.NET Web API. It discusses both Web API service and Web API client and the code is available on bitbucket. http://www.piotrwalat.net/hmac-authentication-in-asp-net-web-api/

Here is a post about Basic Authentication in Web API: http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers/

Remember that if you are going to provide an API to 3rd parties, you will also most likely be responsible for delivering client libraries. Basic authentication has a significant advantage here as it is supported on most programming platforms out of the box. HMAC, on the other hand, is not that standardized and will require custom implementation. These should be relatively straightforward but still require work.

PS. There is also an option to use HTTPS + certificates. http://www.piotrwalat.net/client-certificate-authentication-in-asp-net-web-api-and-windows-store-apps/

Getting Database connection in pure JPA setup

The word pure doesn't match to the word hibernate.

EclipseLink

It's somewhat straightforward as described in above link.

  • Note that the EntityManager must be joined to a Transaction or the unwrap method will return null. (Not a good move at all.)
  • I'm not sure the responsibility of closing the connection.
// --------------------------------------------------------- EclipseLink
try {
    final Connection connection = manager.unwrap(Connection.class);
    if (connection != null) { // manage is not in any transaction
        return function.apply(connection);
    }
} catch (final PersistenceException pe) {
    logger.log(FINE, pe, () -> "failed to unwrap as a connection");
}

Hibernate

It should be, basically, done with following codes.

// using vendor specific APIs
final Session session = (Session) manager.unwrap(Session.class);
//return session.doReturningWork<R>(function::apply);
return session.doReturningWork(new ReturningWork<R>() {
    @Override public R execute(final Connection connection) {
        return function.apply(connection);
    }
});

Well, we (at least I) might don't want any vendor-specific dependencies. Proxy comes in rescue.

try {
    // See? You shouldn't fire me, ass hole!!!
    final Class<?> sessionClass
            = Class.forName("org.hibernate.Session");
    final Object session = manager.unwrap(sessionClass);
    final Class<?> returningWorkClass
            = Class.forName("org.hibernate.jdbc.ReturningWork");
    final Method executeMethod
            = returningWorkClass.getMethod("execute", Connection.class);
    final Object workProxy = Proxy.newProxyInstance(
            lookup().lookupClass().getClassLoader(),
            new Class[]{returningWorkClass},
            (proxy, method, args) -> {
                if (method.equals(executeMethod)) {
                    final Connection connection = (Connection) args[0];
                    return function.apply(connection);
                }
                return null;
            });
    final Method doReturningWorkMethod = sessionClass.getMethod(
            "doReturningWork", returningWorkClass);
    return (R) doReturningWorkMethod.invoke(session, workProxy);
} catch (final ReflectiveOperationException roe) {
    logger.log(Level.FINE, roe, () -> "failed to work with hibernate");
}

OpenJPA

I'm not sure OpenJPA already serves a way using unwrap(Connection.class) but can be done with the way described in one of above links.

It's not clear the responsibility of closing the connection. The document (one of above links) seems saying clearly but I'm not good at English.

try {
    final Class<?> k = Class.forName(
            "org.apache.openjpa.persistence.OpenJPAEntityManager");
    if (k.isInstance(manager)) {
        final Method m = k.getMethod("getConnection");
        try {
            try (Connection c = (Connection) m.invoke(manager)) {
                return function.apply(c);
            }
        } catch (final SQLException sqle) {
            logger.log(FINE, sqle, () -> "failed to work with openjpa");
        }
    }
} catch (final ReflectiveOperationException roe) {
    logger.log(Level.FINE, roe, () -> "failed to work with openjpa");
}

How to create a horizontal loading progress bar?

For using the new progress bar

style="?android:attr/progressBarStyleHorizontal"

for the old grey color progress bar use

style="@android:style/Widget.ProgressBar.Horizontal"

in this one you have the option of changing the height by setting minHeight

The complete XML code is:

    <ProgressBar
    android:id="@+id/pbProcessing"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tvProcessing"
    android:indeterminateOnly="true"/>

indeterminateOnly is set to true for getting indeterminate horizontal progress bar

Warning: push.default is unset; its implicit value is changing in Git 2.0

I was wondering why I was getting that big warning message on Ubuntu 16.04 (which comes with Git 2.7.4), but not on Arch Linux. The reason is that the warning was removed in Git 2.8 (March 2016):

Across the transition at around Git version 2.0, the user used to get a pretty loud warning when running "git push" without setting push.default configuration variable. We no longer warn because the transition was completed a long time ago.

So you won't see the warning if you have Git 2.8 and later and don't need to set push.default unless you want to change the default 'simple' behavior.

Want to move a particular div to right

You can use float on that particular div, e.g.

<div style="float:right;">

Float the div you want more space to have to the left as well:

<div style="float:left;">

If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

<div style="position:absolute; left:-500px; top:30px;"> 

etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

How to properly set Column Width upon creating Excel file? (Column properties)

Use this One

 ((Excel.Range)oSheet.Cells[1, 1]).EntireColumn.ColumnWidth = 10;

How to set cursor position in EditText?

use the below line

e2.setSelection(e2.length());

e2 is edit text Object Name

How to make shadow on border-bottom?

The issue is shadow coming out the side of the containing div. In order to avoid this, the blur value must equal the absolute value of the spread value.

_x000D_
_x000D_
div {_x000D_
  -webkit-box-shadow: 0 4px 6px -6px #222;_x000D_
  -moz-box-shadow: 0 4px 6px -6px #222;_x000D_
  box-shadow: 0 4px 6px -6px #222;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

covered in depth here

Division in Python 2.7. and 3.3

In Python 3, / is float division

In Python 2, / is integer division (assuming int inputs)

In both 2 and 3, // is integer division

(To get float division in Python 2 requires either of the operands be a float, either as 20. or float(20))

What are the differences between a program and an application?

A "program" can be as simple as a "set of instructions" to implement a logic.

It can be part of an "application", "component", "service" or another "program".

Application is a possibly a collection of coordinating program instances to solve a user's purpose.

Difference between array_push() and $array[] =

No one said, but array_push only pushes a element to the END OF THE ARRAY, where $array[index] can insert a value at any given index. Big difference.

disable editing default value of text input

Probably due to the fact that I could not explain well you do not really understand my question. In general, I found the solution.

Sorry for my english

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

string.Substring(0,n); // 0 - start index and n - number of characters

How to create empty text file from a batch file?

You can use a TYPE command instead of COPY. Try this:

TYPE File1.txt>File2.txt

Where File1.txt is empty.

Difference between a user and a schema in Oracle?

I believe the problem is that Oracle uses the term schema slightly differently from what it generally means.

  1. Oracle's schema (as explained in Nebakanezer's answer): basically the set of all tables and other objects owned by a user account, so roughly equivalent to a user account
  2. Schema in general: The set of all tables, sprocs etc. that make up the database for a given system / application (as in "Developers should discuss with the DBAs about the schema for our new application.")

Schema in sense 2. is similar, but not the same as schema in sense 1. E.g. for an application that uses several DB accounts, a schema in sense 2 might consist of several Oracle schemas :-).

Plus schema can also mean a bunch of other, fairly unrelated things in other contexts (e.g. in mathematics).

Oracle should just have used a term like "userarea" or "accountobjects", instead of overloadin "schema"...

Reading file line by line (with space) in Unix Shell scripting - Issue

Try this,

IFS=''
while read line
do
    echo $line
done < file.txt

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''

How to access List elements

Tried list[:][0] to show all first member of each list inside list is not working. Result is unknowingly will same as list[0][:]

So i use list comprehension like this:

[i[0] for i in list] which return first element value for each list inside list.

How to generate the JPA entity Metamodel?

Ok, based on what I have read here, I did it with EclipseLink this way and I did not need to put the processor dependency to the project, only as an annotationProcessorPath element of the compiler plugin.

    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <annotationProcessorPaths>
                <annotationProcessorPath>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
                    <version>2.7.7</version>
                </annotationProcessorPath>
            </annotationProcessorPaths>
            <compilerArgs>
                <arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
            </compilerArgs>
        </configuration>
    </plugin>

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

filter_input(INPUT_POST, 'var_name') instead of $_POST['var_name']
filter_input_array(INPUT_POST) instead of $_POST

Removing multiple keys from a dictionary safely

a solution is using map and filter functions

python 2

d={"a":1,"b":2,"c":3}
l=("a","b","d")
map(d.__delitem__, filter(d.__contains__,l))
print(d)

python 3

d={"a":1,"b":2,"c":3}
l=("a","b","d")
list(map(d.__delitem__, filter(d.__contains__,l)))
print(d)

you get:

{'c': 3}

npm throws error without sudo

For Mac (adopted from Christoper Will's answer)

Mac OS X 10.9.4

  1. System Preference > Users & Groups > (unlock) > press + :

    New Account > "Group"
    Account Name : nodegrp

    After creating the group, tick the user to be included in this group

  2. sudo chgrp -R nodegrp /usr/local/lib/node_modules/
    sudo chgrp nodegrp /usr/bin/node
    sudo chgrp nodegrp /usr/bin/npm
    sudo chown -R $(whoami):nodegrp ~/.npm

ResourceDictionary in a separate assembly

For UWP:

<ResourceDictionary Source="ms-appx:///##Namespace.External.Assembly##/##FOLDER##/##FILE##.xaml" />

python dictionary sorting in descending order based on values

Whenever one has a dictionary where the values are integers, the Counter data structure is often a better choice to represent the data than a dictionary.

If you already have a dictionary, a counter can easily be formed by:

c = Counter(d['123'])

as an example from your data.

The most_common function allows easy access to descending order of the items in the counter

The more complete writeup on the Counter data structure is at https://docs.python.org/2/library/collections.html

if A vs if A is not None:

if A: will prove false if A is 0, False, empty string, empty list or None, which can lead to undesired results.

How to call getResources() from a class which has no context?

The normal solution to this is to pass an instance of the context to the class as you create it, or after it is first created but before you need to use the context.

Another solution is to create an Application object with a static method to access the application context although that couples the Droid object fairly tightly into the code.

Edit, examples added

Either modify the Droid class to be something like this

 public Droid(Context context,int x, int y) {
    this.bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.birdpic);
    this.x = x;
    this.y = y;
    }   

Or create an Application something like this:

public class App extends android.app.Application
{
    private static App mApp = null;
    /* (non-Javadoc)
     * @see android.app.Application#onCreate()
     */
    @Override
    public void onCreate()
    {
        super.onCreate();
        mApp = this;
    }
    public static Context context()
    {
        return mApp.getApplicationContext();
    }
}

And call App.context() wherever you need a context - note however that not all functions are available on an application context, some are only available on an activity context but it will certainly do with your need for getResources().

Please note that you'll need to add android:name to your application definition in your manifest, something like this:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name=".App" >

datetime to string with series in python pandas

There is a pandas function that can be applied to DateTime index in pandas data frame.

date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list

the element inside the list:

u'1910-11-02'

You might need to replace the 'u'.

There might be some additional arguments that I should put into the previous functions.

How to enter a series of numbers automatically in Excel

Enter the formula =ROW() into any cell and that cell will show the row number as its value.

If you want 1001, 1002 etc just enter =1000+ROW()

What is a difference between unsigned int and signed int in C?

ISO C states what the differences are.

The int data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h as INT_MIN and INT_MAX respectively.

An unsigned int has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX from that same header file.

Beyond that, the standard does not mandate twos complement notation for encoding the values, that's just one of the possibilities. The three allowed types would have encodings of the following for 5 and -5 (using 16-bit data types):

        two's complement  |  ones' complement   |   sign/magnitude
    +---------------------+---------------------+---------------------+
 5  | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101 |
-5  | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101 |
    +---------------------+---------------------+---------------------+
  • In two's complement, you get a negative of a number by inverting all bits then adding 1.
  • In ones' complement, you get a negative of a number by inverting all bits.
  • In sign/magnitude, the top bit is the sign so you just invert that to get the negative.

Note that positive values have the same encoding for all representations, only the negative values are different.

Note further that, for unsigned values, you do not need to use one of the bits for a sign. That means you get more range on the positive side (at the cost of no negative encodings, of course).

And no, 5 and -5 cannot have the same encoding regardless of which representation you use. Otherwise, there'd be no way to tell the difference.


As an aside, there are currently moves underway, in both C and C++ standards, to nominate two's complement as the only encoding for negative integers.

How to get the previous url using PHP

I can't add a comment yet, so I wanted to share that HTTP_REFERER is not always sent.

Notice: Undefined index: HTTP_REFERER

Failed to find Build Tools revision 23.0.1

I had this error:

Failed to find Build Tools revision 23.0.2

When you got updated/installed:

  1. Android SDK Build Tools
  2. Android SDK Tools

Change version number in build.gradle

FROM

buildToolsVersion "23.0.2"

TO

buildToolsVersion "25.0.2"

How to find what Build Tools version you have

How to export SQL Server 2005 query to CSV

If it fits your requirements, you can use bcp on the command line if you do this frequently or want to build it into a production process.

Here's a link describing the configuration.

What is the purpose and use of **kwargs?

Unpacking dictionaries

** unpacks dictionaries.

This

func(a=1, b=2, c=3)

is the same as

args = {'a': 1, 'b': 2, 'c':3}
func(**args)

It's useful if you have to construct parameters:

args = {'name': person.name}
if hasattr(person, "address"):
    args["address"] = person.address
func(**args)  # either expanded to func(name=person.name) or
              #                    func(name=person.name, address=person.address)

Packing parameters of a function

def setstyle(**styles):
    for key, value in styles.iteritems():      # styles is a regular dictionary
        setattr(someobject, key, value)

This lets you use the function like this:

setstyle(color="red", bold=False)

Request string without GET arguments

Why so complicated? =)

$baseurl = 'http://mysite.com';
$url_without_get = $baseurl.$_SERVER['PHP_SELF'];

this should really do it man ;)

How to make input type= file Should accept only pdf and xls

Unfortunately, there is no guaranteed way to do it at time of selection.

Some browsers support the accept attribute for input tags. This is a good start, but cannot be relied upon completely.

<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />

You can use a cfinput and run a validation to check the file extension at submission, but not the mime-type. This is better, but still not fool-proof. Files on OSX often have no file extensions or users could maliciously mislabel the file types.

ColdFusion's cffile can check the mime-type using the contentType property of the result (cffile.contentType), but that can only be done after the upload. This is your best bet, but is still not 100% safe as mime-types could still be wrong.

Install Visual Studio 2013 on Windows 7

The minimum requirements are based on the Express edition you're attempting to install:

Express for Web (Web sites and HTML5 applications) - Windows 7 SP1 (With IE 10)
Express for Windows (Windows 8 Apps) - Windows 8.1
Express for Windows Desktop (Windows Programs) - Windows 7 SP1 (With IE 10)
Express for Windows Phone (Windows Phone Apps) - Windows 8

It sounds like you're trying to install the "Express 2013 for Windows" edition, which is for developing Windows 8 "Modern UI" apps, or the Windows Phone edition.

The similarly named version that is compatible with Windows 7 SP1 is "Express 2013 for Windows Desktop"

Source

How do I convert a long to a string in C++?

You could use stringstream.

#include <sstream>

// ...
std::string number;
std::stringstream strstream;
strstream << 1L;
strstream >> number;

There is usually some proprietary C functions in the standard library for your compiler that does it too. I prefer the more "portable" variants though.

The C way to do it would be with sprintf, but that is not very secure. In some libraries there is new versions like sprintf_s which protects against buffer overruns.

Set iframe content height to auto resize dynamically

In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:

<body onload="parent.alertsize(document.body.scrollHeight);">

In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:

<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>

What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.

To that JavaScript function it sends how many pixels its (iframe) height is.

The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.

That's it, nothing else is needed.


But if you like to know some more small tricks keep on reading...

DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
}
</script>

to that script just add:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>

How you use the above script is easy:

<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>

For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)

Complete holding page code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>

<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>

Complete iframe code: (this iframe named "theiframe.htm")

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight);
}
</script>
</head>

<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END

</body>
</html>

Demo

node.js, socket.io with SSL

This is my nginx config file and iosocket code. Server(express) is listening on port 9191. It works well: nginx config file:

server {
    listen       443 ssl;
    server_name  localhost;
    root   /usr/share/nginx/html/rdist;

    location /user/ {
        proxy_pass   http://localhost:9191;
    }
    location /api/ {
        proxy_pass   http://localhost:9191;
    }
    location /auth/ {
        proxy_pass   http://localhost:9191;
    }

    location / {
        index  index.html index.htm;
        if (!-e $request_filename){
          rewrite ^(.*)$ /index.html break;
        }
    }
    location /socket.io/ {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_pass   http://localhost:9191/socket.io/;
    }


    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    ssl_certificate /etc/nginx/conf.d/sslcert/xxx.pem;
    ssl_certificate_key /etc/nginx/conf.d/sslcert/xxx.key;

}

Server:

const server = require('http').Server(app)
const io = require('socket.io')(server)
io.on('connection', (socket) => {
    handleUserConnect(socket)

  socket.on("disconnect", () => {
   handleUserDisConnect(socket)
  });
})

server.listen(9191, function () {
  console.log('Server listening on port 9191')
})

Client(react):

    const socket = io.connect('', { secure: true, query: `userId=${this.props.user._id}` })

        socket.on('notifications', data => {
            console.log('Get messages from back end:', data)
            this.props.mergeNotifications(data)
        })

How to check if an item is selected from an HTML drop down list?

<script>
var card = document.getElementById("cardtype");
if(card.selectedIndex == 0) {
     alert('select one answer');
}
else {
    var selectedText = card.options[card.selectedIndex].text;
    alert(selectedText);
}
</script>

Logging levels - Logback - rule-of-thumb to assign log levels

My approach, i think coming more from an development than an operations point of view, is:

  • Error means that the execution of some task could not be completed; an email couldn't be sent, a page couldn't be rendered, some data couldn't be stored to a database, something like that. Something has definitively gone wrong.
  • Warning means that something unexpected happened, but that execution can continue, perhaps in a degraded mode; a configuration file was missing but defaults were used, a price was calculated as negative, so it was clamped to zero, etc. Something is not right, but it hasn't gone properly wrong yet - warnings are often a sign that there will be an error very soon.
  • Info means that something normal but significant happened; the system started, the system stopped, the daily inventory update job ran, etc. There shouldn't be a continual torrent of these, otherwise there's just too much to read.
  • Debug means that something normal and insignificant happened; a new user came to the site, a page was rendered, an order was taken, a price was updated. This is the stuff excluded from info because there would be too much of it.
  • Trace is something i have never actually used.

checked = "checked" vs checked = true

document.getElementById('myRadio').checked is a boolean value. It should be true or false

document.getElementById('myRadio').checked = "checked"; casts the string to a boolean, which is true.

document.getElementById('myRadio').checked = true; just assigns true without casting.

Use true as it is marginally more efficient and is more intention revealing to maintainers.

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

I'm meeting this problem for years... eclipse' shame. If your app is split into maven modules then you may consider removing affected modules from IDE, whenever you need to regenerate/run the plugin use maven command line with install, eclipse is then happy with prepared artifacts present in your local repository. No fiddle-around needed.

Naming conventions for Java methods that return boolean

Standard is use is or has as a prefix. For example isValid, hasChildren.

Open S3 object as a string with Boto3

I had a problem to read/parse the object from S3 because of .get() using Python 2.7 inside an AWS Lambda.

I added json to the example to show it became parsable :)

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

NOTE (for python 2.7): My object is all ascii, so I don't need .decode('utf-8')

NOTE (for python 3.6+): We moved to python 3.6 and discovered that read() now returns bytes so if you want to get a string out of it, you must use:

j = json.loads(obj['Body'].read().decode('utf-8'))

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

How to change the background colour's opacity in CSS

background: rgba(0,0,0,.5);

you can use rgba for opacity, will only work in ie9+ and better browsers

Why doesn't wireshark detect my interface?

On Fedora 29 with Wireshark 3.0.0 only adding a user to the wireshark group is required:

sudo usermod -a -G wireshark $USER

Then log out and log back in (or reboot), and Wireshark should work correctly.

Where is localhost folder located in Mac or Mac OS X?

If you use apachectl to start or stop, then you can find it with this command

apachectl -t -D DUMP_RUN_CFG

System.drawing namespace not found under console application

  1. Add using System.Drawing;
  2. Go to solution explorer and right click on references and select add reference
  3. Click on assemblies on the left
  4. search for system.drawing
  5. check system.drawing
  6. Click OK
  7. Done

Core dump file is not generated

Remember if you are starting the server from a service, it will start a different bash session so the ulimit won't be effective there. Try to put this in your script itself:

ulimit -c unlimited

How to: "Separate table rows with a line"

You could use the border-bottom css property.

_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
table tr {_x000D_
  border-bottom: 1px solid black;_x000D_
}_x000D_
_x000D_
table tr:last-child {_x000D_
  border: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>1</td>_x000D_
    <td>Foo</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>2</td>_x000D_
    <td>Bar</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Python SQLite: database is locked

Even when I just had one writer and one reader, my issue was that one of the reads was taking too long: longer than the stipulated timeout of 5 seconds. So the writer timed out and caused the error.

So, be careful when reading all entries from a database especially from one which the size of the table grows over time.

How to pass params with history.push/Link/Redirect in react-router v4?

Add on info to get query parameters.

const queryParams = new URLSearchParams(this.props.location.search);
console.log('assuming query param is id', queryParams.get('id');

For more info about URLSearchParams check this link URLSearchParams

How can I change the color of AlertDialog title and the color of the line under it

    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.BLACK);

    String title = context.getString(R.string.agreement_popup_message);
    SpannableStringBuilder ssBuilder = new SpannableStringBuilder(title);
    ssBuilder.setSpan(
            foregroundColorSpan,
            0,
            title.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    );

AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(context);
alertDialogBuilderUserInput.setTitle(ssBuilder)

how to refresh my datagridview after I add new data

This reloads the datagridview:

Me.ABCListTableAdapter.Fill(Me.ABCLISTDATASET.ABCList)

Hope this helps

AngularJS accessing DOM elements inside directive template

This answer comes a little bit late, but I just was in a similar need.

Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.

For example, use the directive like this:

<my-directive class2add="special-class" />

And get the following html:

<div>
    <ul>
       <li class="special-class">Item 1</li>
       <li class="special-class">Item 2</li>
    </ul>
</div>

The solution found here applied with templateUrl, would be:

app.directive("myDirective", function() {
    return {
        template: function(element, attrs){
            return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
        },
        link: function(scope, element, attrs) {
            var list = element.find("ul");
        }
    }
});

Just tried it successfully with AngularJS 1.4.9.

Hope it helps.

How to check for the type of a template parameter?

std::is_same() is only available since C++11. For pre-C++11 you can use typeid():

template <typename T>
void foo()
{
    if (typeid(T) == typeid(animal)) { /* ... */ }
}

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

How do I get the size of a java.sql.ResultSet?

The way of getting size of ResultSet, No need of using ArrayList etc

int size =0;  
if (rs != null)   
{  
rs.beforeFirst();  
 rs.last();  
size = rs.getRow();
}

Now You will get size, And if you want print the ResultSet, before printing use following line of code too,

rs.beforeFirst();  

Programmatically register a broadcast receiver

Create a broadcast receiver

[BroadcastReceiver(Enabled = true, Exported = false)]

public class BCReceiver : BroadcastReceiver
{

    BCReceiver receiver;

    public override void OnReceive(Context context, Intent intent)
    {
        //Do something here
    }
}

From your activity add this code:

LocalBroadcastManager.getInstance(ApplicationContext)
    .registerReceiver(receiver, filter);

A transport-level error has occurred when receiving results from the server

One of the reason I found for this error is 'Packet Size=xxxxx' in connection string. if the value of xxxx is too large, we will see this error. Either remove this value and let SQL server handle it or keep it low, depending on the network capabilities.

How to trim a list in Python

>>> [1,2,3,4,5,6,7,8,9][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]

how to apply click event listener to image in android

ImageView img = (ImageView) findViewById(R.id.myImageId);
img.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
       // your code here
    }
});

What is the difference between max-device-width and max-width for mobile web?

Don't use device-width/height anymore.

device-width, device-height and device-aspect-ratio are deprecated in Media Queries Level 4: https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features

Just use width/height (without min/max) in combination with orientation & (min/max-)resolution to target specific devices. On mobile width/height should be the same as device-width/height.

how to prevent "directory already exists error" in a makefile when using mkdir

$(OBJDIR):
    mkdir $@

Which also works for multiple directories, e.g..

OBJDIRS := $(sort $(dir $(OBJECTS)))

$(OBJDIRS):
    mkdir $@

Adding $(OBJDIR) as the first target works well.

Android Studio and Gradle build error

Edit the gradle wrapper settings in gradle/wrapper/gradle-wrapper.properties and change gradle-1.6-bin.zip to gradle-2.4-bin.zip.

./gradle/wrapper/gradle-wrapper.properties :

#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-bin.zip

It should compile without any error now.

Note: update version numbers with the most recent ones

Android: Remove all the previous activities from the back stack

You can try finishAffinity(), it closes all current activities and works on and above Android 4.1

Getting Keyboard Input

If you have Java 6 (You should have, btw) or higher, then simply do this :

 Console console = System.console();
 String str = console.readLine("Please enter the xxxx : ");

Please remember to do :

 import java.io.Console;

Thats it!

Getting scroll bar width using JavaScript

I think this will be simple and fast -

var scrollWidth= window.innerWidth-$(document).width()

UITableView with fixed section headers

You can also set the tableview's bounces property to NO. This will keep the section headers non-floating/static, but then you also lose the bounce property of the tableview.

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

How to set full calendar to a specific start date when it's initialized for the 1st time?

You have it backwards. Display the calendar first, and then call gotoDate.

$('#calendar').fullCalendar({
  // Options
});

$('#calendar').fullCalendar('gotoDate', currentDate);

How to filter files when using scp to copy dir recursively?

scp -i /home/<user>/.ssh/id_rsa -o "StrictHostKeyChecking=no" -rp /source/directory/path/[!.]* <target_user>@<target_system:/destination/directory/path

How to implement the Android ActionBar back button?

Android Annotations:

@OptionsItem(android.R.id.home)
void homeSelected() {
    onBackPressed();
}

Source: https://github.com/excilys/androidannotations

What is the purpose of the "final" keyword in C++11 for functions?

Nothing to add to the semantic aspects of "final".

But I'd like to add to chris green's comment that "final" might become a very important compiler optimization technique in the not so distant future. Not only in the simple case he mentioned, but also for more complex real-world class hierarchies which can be "closed" by "final", thus allowing compilers to generate more efficient dispatching code than with the usual vtable approach.

One key disadvantage of vtables is that for any such virtual object (assuming 64-bits on a typical Intel CPU) the pointer alone eats up 25% (8 of 64 bytes) of a cache line. In the kind of applications I enjoy to write, this hurts very badly. (And from my experience it is the #1 argument against C++ from a purist performance point of view, i.e. by C programmers.)

In applications which require extreme performance, which is not so unusual for C++, this might indeed become awesome, not requiring to workaround this problem manually in C style or weird Template juggling.

This technique is known as Devirtualization. A term worth remembering. :-)

There is a great recent speech by Andrei Alexandrescu which pretty well explains how you can workaround such situations today and how "final" might be part of solving similar cases "automatically" in the future (discussed with listeners):

http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-Quickly

Cursor inside cursor

You could also sidestep nested cursor issues, general cursor issues, and global variable issues by avoiding the cursors entirely.

declare @rowid int
declare @rowid2 int
declare @id int
declare @type varchar(10)
declare @rows int
declare @rows2 int
declare @outer table (rowid int identity(1,1), id int, type varchar(100))
declare @inner table (rowid int  identity(1,1), clientid int, whatever int)

insert into @outer (id, type) 
Select id, type from sometable

select @rows = count(1) from @outer
while (@rows > 0)
Begin
    select top 1 @rowid = rowid, @id  = id, @type = type
    from @outer
    insert into @innner (clientid, whatever ) 
    select clientid whatever from contacts where contactid = @id
    select @rows2 = count(1) from @inner
    while (@rows2 > 0)
    Begin
        select top 1 /* stuff you want into some variables */
        /* Other statements you want to execute */
        delete from @inner where rowid = @rowid2
        select @rows2 = count(1) from @inner
    End  
    delete from @outer where rowid = @rowid
    select @rows = count(1) from @outer
End

Intro to GPU programming

Another easy way to get into GPU programming, without getting into CUDA or OpenCL, is to do it via OpenACC.

OpenACC works like OpenMP, with compiler directives (like #pragma acc kernels) to send work to the GPU. For example, if you have a big loop (only larger ones really benefit):

int i;
float a = 2.0;
float b[10000];
#pragma acc kernels
for (i = 0; i < 10000; ++i) b[i] = 1.0f;
#pragma acc kernels
for (i = 0; i < 10000; ++i) {
  b[i] = b[i] * a;
}

Edit: unfortunately, only the PGI compiler really supports OpenACC right now, for NVIDIA GPU cards.

Best way to update data with a RecyclerView adapter

Found following solution working for my similar problem:

private ExtendedHashMap mData = new ExtendedHashMap();
private  String[] mKeys;

public void setNewData(ExtendedHashMap data) {
    mData.putAll(data);
    mKeys = data.keySet().toArray(new String[data.size()]);
    notifyDataSetChanged();
}

Using the clear-command

mData.clear()

is not nessescary

Full Page <iframe>

This is cross-browser and fully responsive:

<iframe
  src="https://drive.google.com/file/d/0BxrMaW3xINrsR3h2cWx0OUlwRms/preview"
  style="
    position: fixed;
    top: 0px;
    bottom: 0px;
    right: 0px;
    width: 100%;
    border: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    z-index: 999999;
    height: 100%;
  ">
</iframe>

How to "wait" a Thread in Android

You need the sleep method of the Thread class.

public static void sleep (long time)

Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.

Parameters

time The time to sleep in milliseconds.

How to Toggle a div's visibility by using a button click

Try following logic:

<script type="text/javascript">
function showHideDiv(id) {
    var e = document.getElementById(id);
    if(e.style.display == null || e.style.display == "none") {
        e.style.display = "block";
    } else {
        e.style.display = "none";
    }
}
</script>

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

I was having some difficulty translating actual VB.NET to the Expression subset that SSRS uses. You definitely inspired me though and this is what I came up with.

StartDate  
=dateadd("d",0,dateserial(year(dateadd("d",-1,dateserial(year(Today),month(Today),1))),month(dateadd("d",-1,dateserial(year(Today),month(Today),1))),1))

End Date
=dateadd("d",0,dateserial(year(Today),month(Today),1))  

I know it's a bit recursive for the StartDate (first day of last month). Is there anything I'm missing here? These are strictly date fields (i.e. no time), but I think this should capture leap year, etc.

How did I do?

Excel "External table is not in the expected format."

Just add my case. My xls file was created by a data export function from a website, the file extention is xls, it can be normally opened by MS Excel 2003. But both Microsoft.Jet.OLEDB.4.0 and Microsoft.ACE.OLEDB.12.0 got an "External table is not in the expected format" exception.

Finally, the problem is, just as the exception said, "it's not in the expected format". Though it's extention name is xls, but when I open it with a text editor, it is actually a well-formed html file, all data are in a <table>, each <tr> is a row and each <td> is a cell. Then I think I can parse it in a html way.

Extracting time from POSIXct

I can't find anything that deals with clock times exactly, so I'd just use some functions from package:lubridate and work with seconds-since-midnight:

require(lubridate)
clockS = function(t){hour(t)*3600+minute(t)*60+second(t)}
plot(clockS(times),val)

You might then want to look at some of the axis code to figure out how to label axes nicely.

Mobile Safari: Javascript focus() method on inputfield only works with click?

Actually, guys, there is a way. I struggled mightily to figure this out for [LINK REMOVED] (try it on an iPhone or iPad).

Basically, Safari on touchscreen devices is stingy when it comes to focus()ing textboxes. Even some desktop browsers do better if you do click().focus(). But the designers of Safari on touchscreen devices realized it's annoying to users when the keyboard keeps coming up, so they made the focus appear only on the following conditions:

1) The user clicked somewhere and focus() was called while executing the click event. If you are doing an AJAX call, then you must do it synchronously, such as with the deprecated (but still available) $.ajax({async:false}) option in jQuery.

2) Furthermore -- and this one kept me busy for a while -- focus() still doesn't seem to work if some other textbox is focused at the time. I had a "Go" button which did the AJAX, so I tried blurring the textbox on the touchstart event of the Go button, but that just made the keyboard disappear and moved the viewport before I had a chance to complete the click on the Go button. Finally I tried blurring the textbox on the touchend event of the Go button, and this worked like a charm!

When you put #1 and #2 together, you get a magical result that will set your login forms apart from all the crappy web login forms, by placing the focus in your password fields, and make them feel more native. Enjoy! :)

JavaScript get clipboard data on paste event (Cross browser)

This was too long for a comment on Nico's answer, which I don't think works on Firefox any more (per the comments), and didn't work for me on Safari as is.

Firstly, you now appear to be able to read directly from the clipboard. Rather than code like:

if (/text\/plain/.test(e.clipboardData.types)) {
    // shouldn't this be writing to elem.value for text/plain anyway?
    elem.innerHTML = e.clipboardData.getData('text/plain');
}

use:

types = e.clipboardData.types;
if (((types instanceof DOMStringList) && types.contains("text/plain")) ||
    (/text\/plain/.test(types))) {
    // shouldn't this be writing to elem.value for text/plain anyway?
    elem.innerHTML = e.clipboardData.getData('text/plain');
}

because Firefox has a types field which is a DOMStringList which does not implement test.

Next Firefox will not allow paste unless the focus is in a contenteditable=true field.

Finally, Firefox will not allow paste reliably unless the focus is in a textarea (or perhaps input) which is not only contenteditable=true but also:

  • not display:none
  • not visibility:hidden
  • not zero sized

I was trying to hide the text field so I could make paste work over a JS VNC emulator (i.e. it was going to a remote client and there was no actually textarea etc to paste into). I found trying to hide the text field in the above gave symptoms where it worked sometimes, but typically failed on the second paste (or when the field was cleared to prevent pasting the same data twice) as the field lost focus and would not properly regain it despite focus(). The solution I came up with was to put it at z-order: -1000, make it display:none, make it as 1px by 1px, and set all the colours to transparent. Yuck.

On Safari, you the second part of the above applies, i.e. you need to have a textarea which is not display:none.

ValueError: unconverted data remains: 02:05

Best answer is to use the from dateutil import parser.

usage:

from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())

Matching a space in regex

It seems to me like using a REGEX in this case would just be overkill. Why not just just strpos to find the space character. Also, there's nothing special about the space character in regular expressions, you should be able to search for it the same as you would search for any other character. That is, unless you disabled pattern whitespace, which would hardly be necessary in this case.

AngularJS : Clear $watch

If you have too much watchers and you need to clear all of them, you can push them into an array and destroy every $watch in a loop.

var watchers = [];
watchers.push( $scope.$watch('watch-xxx', function(newVal){
   //do something
}));    

for(var i = 0; i < watchers.length; ++i){
    if(typeof watchers[i] === 'function'){
        watchers[i]();
    }
}

watchers = [];

Describe table structure

This depends on your database vendor. Mostly it's the "information schema" you should Google for (applies to MySQL, MSSQL and perhaps others).

How to dynamically create a class?

I know i reopen this old task but with c# 4.0 this task is absolutely painless.

dynamic expando = new ExpandoObject();
expando.EmployeeID=42;
expando.Designation="unknown";
expando.EmployeeName="curt"

//or more dynamic
AddProperty(expando, "Language", "English");

for more see https://www.oreilly.com/learning/building-c-objects-dynamically

What is the difference between logical data model and conceptual data model?

This is an old question and maybe this comes way too late, but I don't see one very important aspect necessary to answering the question. That is, the TARGET audience for the data model. The Conceptual Data Model is the model generated from business analysis, from interviews with the BUSINESS about their data. It is not so much "high level" as it is the business's understanding of their data, business rules captured in the relationships between "candidate" entities. At this point, you are capturing the things of importance to the business (Employee, Customer, Contract, Account, etc.) and the relationships between them. The final Conceptual Data Model may be somewhat abstract -- for instance, treating Individuals and Organizations entering into a contract as subtypes of a "Party", Contractors and Permanent Employees as subtypes of an Employee, even Employees and Customers subtypes of "Person" -- but it is a document that a data modeler develops from discussions with the business SMEs and presents to the business for validation.

The Logical Data Model is not just "more detail" -- where useful and important, a Conceptual Data Model may well have attributes included -- it is the ARCHITECTURE document, the model that is presented to the software analysts/engineers to explain and specify the data requirements. It will resolve many-to-many relationships to association tables and will define all attributes, with examples and constraints, so that code can be written against the architecture.

The Physical model is that Logical Model generated specifically for a particular environment, such as SQL Server or Teradata or Oracle or whatever. It will have keys, indexes, partitions, or whatever is needed to implement, based on sizing, access frequency, security constraints, etc.

So, if you are being asked to develop a Conceptual Data Model, you are being asked to design the solution (or part of it) from scratch, getting your information from the business. There's more to it, but I hope that answers the question.

How to have stored properties in Swift, the same way I had on Objective-C?

How about storing static map to class that is extending like this :

extension UIView {

    struct Holder {
        static var _padding:[UIView:UIEdgeInsets] = [:]
    }

    var padding : UIEdgeInsets {
        get{ return UIView.Holder._padding[self] ?? .zero}
        set { UIView.Holder._padding[self] = newValue }
    }

}

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

I fixed it by deleting my app.config with

<assemblyIdentity name="System.Runtime" ....> 

entries.

app.config was automatically added (but not needed) during refactoring

How does the Python's range function work?

A "for loop" in most, if not all, programming languages is a mechanism to run a piece of code more than once.

This code:

for i in range(5):
    print i

can be thought of working like this:

i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i

So you see, what happens is not that i gets the value 0, 1, 2, 3, 4 at the same time, but rather sequentially.

I assume that when you say "call a, it gives only 5", you mean like this:

for i in range(5):
    a=i+1
print a

this will print the last value that a was given. Every time the loop iterates, the statement a=i+1 will overwrite the last value a had with the new value.

Code basically runs sequentially, from top to bottom, and a for loop is a way to make the code go back and something again, with a different value for one of the variables.

I hope this answered your question.

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

Strange PostgreSQL "value too long for type character varying(500)"

By specifying the column as VARCHAR(500) you've set an explicit 500 character limit. You might not have done this yourself explicitly, but Django has done it for you somewhere. Telling you where is hard when you haven't shown your model, the full error text, or the query that produced the error.

If you don't want one, use an unqualified VARCHAR, or use the TEXT type.

varchar and text are limited in length only by the system limits on column size - about 1GB - and by your memory. However, adding a length-qualifier to varchar sets a smaller limit manually. All of the following are largely equivalent:

column_name VARCHAR(500)

column_name VARCHAR CHECK (length(column_name) <= 500) 

column_name TEXT CHECK (length(column_name) <= 500) 

The only differences are in how database metadata is reported and which SQLSTATE is raised when the constraint is violated.

The length constraint is not generally obeyed in prepared statement parameters, function calls, etc, as shown:

regress=> \x
Expanded display is on.
regress=> PREPARE t2(varchar(500)) AS SELECT $1;
PREPARE
regress=> EXECUTE t2( repeat('x',601) );
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
?column? | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

and in explicit casts it result in truncation:

regress=> SELECT repeat('x',501)::varchar(1);
-[ RECORD 1 ]
repeat | x

so I think you are using a VARCHAR(500) column, and you're looking at the wrong table or wrong instance of the database.

Android ListView with Checkbox and all clickable

holder.checkbox.setTag(row_id);

and

holder.checkbox.setOnClickListener( new OnClickListener() {

                @Override
                public void onClick(View v) {
                    CheckBox c = (CheckBox) v;

                    int row_id = (Integer) v.getTag();

                    checkboxes.put(row_id, c.isChecked());


                }
        });

How to show x and y axes in a MATLAB graph?

I know this is coming a bit late, but a colleague of mine figured something out:

figure, plot ((1:10),cos(rand(1,10))-0.75,'*-')
hold on
plot ((1:10),zeros(1,10),'k+-')
text([1:10]-0.09,ones(1,10).*-0.015,[{'0' '1'  '2' '3' '4' '5' '6' '7' '8' '9'}])
set(gca,'XTick',[], 'XColor',[1 1 1])
box off

Android - java.lang.SecurityException: Permission Denial: starting Intent

You need to set android:exported="true" in your AndroidManifest.xml file where you declare this Activity:

<activity
    android:name="com.example.lib.MainActivity"
    android:label="LibMain" 
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" >
        </action>
    </intent-filter>
</activity>

How to add a footer to the UITableView?

You need to implement the UITableViewDelegate method

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

and return the desired view (e.g. a UILabel with the text you'd like in the footer) for the appropriate section of the table.

How do I use method overloading in Python?

Python does not support method overloading like Java or C++. We may overload the methods, but we can only use the latest defined method.

# First sum method.
# Takes two argument and print their sum
def sum(a, b):
    s = a + b
    print(s)

# Second sum method
# Takes three argument and print their sum
def sum(a, b, c):
    s = a + b + c
    print(s)

# Uncommenting the below line shows an error
# sum(4, 5)

# This line will call the second sum method
sum(4, 5, 5)

We need to provide optional arguments or *args in order to provide a different number of arguments on calling.

Courtesy Python | Method Overloading

How to define Gradle's home in IDEA?

This is what helped me solve the problem of not having Gradle home set for the IDEA when importing a Gradle project.

THREE OPTIONS -- (A) Default Wrapper (B) "gradle 'wrapper' task configuration" OR (C) "local gradle distribution" defined by jetbrains: https://www.jetbrains.com/help/idea/gradle-settings.html

A. Default Wrapper (recommended)

If you are able, select this recommended option. If it is grayed out, see option C, which should then set your default for all subsequent projects.

B. Gradle 'Wrapper' Task Configuration

If you want IDEA to define your gradle version for you from your build script

  1. Set this option if you define your gradle build versions as a task within your actual gradle build.

Example below from jetbrains: https://www.jetbrains.com/help/idea/gradle-settings.html

enter image description here

(useful if you do not want to share gradle builds between projects)

C. Local Gradle Distribution

1. Run the following command to get gradle location:

   brew info gradle (if gradle was installed with homebrew)


2. You are looking for something like this:

   /usr/local/Cellar/gradle/4.8.1


3. Next, append 'libexec' to the gradle location you just found:

/usr/local/Cellar/gradle/4.8.1/libexec

This is because "libexec is to be used by other daemons and system utilities executed by other programs" (i.e. IDEA). Please see https://unix.stackexchange.com/questions/312146/what-is-the-purpose-of-usr-libexec

4. Finally, put that new path in the Gradle home input box if IDEA prompts you.

enter image description here

  1. IDEA should now have allowed you to hit OK enter image description here

How much overhead does SSL impose?

Order of magnitude: zero.

In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.

The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.


Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.

How to convert int to string on Arduino?

Here below is a self composed myitoa() which is by far smaller in code, and reserves a FIXED array of 7 (including terminating 0) in char *mystring, which is often desirable. It is obvious that one can build the code with character-shift instead, if one need a variable-length output-string.

void myitoa(int number, char *mystring) {
  boolean negative = number>0;

  mystring[0] = number<0? '-' : '+';
  number = number<0 ? -number : number;
  for (int n=5; n>0; n--) {
     mystring[n] = ' ';
     if(number > 0) mystring[n] = number%10 + 48;
     number /= 10;
  }  
  mystring[6]=0;
}

How to convert string to string[]?

string is a string, and string[] is an array of strings

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

A simple work around(it worked for me) is use the IP address instead of localhost. This should be fine for your development tasks.

How can I sort a dictionary by key?

In Python 3.

>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
    print (key, D1[key])

gives

1 89
2 3
3 0
4 5

How to roundup a number to the closest ten?

You can use the function MROUND(<reference cell>, <round to multiple of digit needed>).

Example:

  1. For a value A1 = 21 round to multiple of 10 it would be written as =MROUND(A1,10) for which Result = 20

  2. For a value Z4 = 55.1 round to multiple of 10 it would be written as =MROUND(Z4,10) for which Result = 60

jQuery send string as POST parameters

$.ajax({
    type: 'POST',    
    url:'http://nakolesah.ru/',
    data:'foo='+ bar+'&calibri='+ nolibri,
    success: function(msg){
        alert('wow' + msg);
    }
});

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag

The rules for turning on the carry flag in binary/integer math are two:

  1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

  2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

    • 0111 + 0001 = 1000 (carry flag is turned off [zero])
    • 1000 - 0001 = 0111 (carry flag is turned off [zero])

In unsigned arithmetic, watch the carry flag to detect errors.

In signed arithmetic, the carry flag tells you nothing interesting.

Overflow Flag

The rules for turning on the overflow flag in binary/integer math are two:

  1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

  2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

Otherwise the "overflow" flag is turned off

  • 0100 + 0001 = 0101 (overflow flag is turned off)
  • 0110 + 1001 = 1111 (overflow flag turned off)
  • 1000 + 0001 = 1001 (overflow flag turned off)
  • 1100 + 1100 = 1000 (overflow flag is turned off)

Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

Specify system property to Maven project

Is there a way ( I mean how do I ) set a system property in a maven project? I want to access a property from my test [...]

You can set system properties in the Maven Surefire Plugin configuration (this makes sense since tests are forked by default). From Using System Properties:

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <systemPropertyVariables>
            <propertyName>propertyValue</propertyName>
            <buildDirectory>${project.build.directory}</buildDirectory>
            [...]
          </systemPropertyVariables>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

and my webapp ( running locally )

Not sure what you mean here but I'll assume the webapp container is started by Maven. You can pass system properties on the command line using:

mvn -DargLine="-DpropertyName=propertyValue"

Update: Ok, got it now. For Jetty, you should also be able to set system properties in the Maven Jetty Plugin configuration. From Setting System Properties:

<project>
  ...
  <plugins>
    ...
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <configuration>
         ...
         <systemProperties>
            <systemProperty>
              <name>propertyName</name>
              <value>propertyValue</value>
            </systemProperty>
            ...
         </systemProperties>
        </configuration>
      </plugin>
  </plugins>
</project>

How to set the value for Radio Buttons When edit?

For those who might be in need for a solution in pug template engine and NodeJs back-end, you can use this:

If values are not boolean(IE: true or false), code below works fine:

input(type='radio' name='sex' value='male' checked=(dbResult.sex ==='male') || (dbResult.sex === 'newvalue') )
input(type='radio' name='sex' value='female' checked=(dbResult.sex ==='female) || (dbResult.sex === 'newvalue'))

If values are boolean(ie: true or false), use this instead:

input(type='radio' name='isInsurable' value='true' checked=singleModel.isInsurable || (singleModel.isInsurable === 'true') )
input(type='radio' name='isInsurable' value='false' checked=!singleModel.isInsurable || (singleModel.isInsurable === 'false'))

the reason for this || operator is to re-display new values if editing fails due to validation error and you have a logic to send back the new values to your front-end

How to declare a type as nullable in TypeScript?

Just add a question mark ? to the optional field.

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

How to make MySQL table primary key auto increment with some prefix

If you really need this you can achieve your goal with help of separate table for sequencing (if you don't mind) and a trigger.

Tables

CREATE TABLE table1_seq
(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
  id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);

Now the trigger

DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
  INSERT INTO table1_seq VALUES (NULL);
  SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;

Then you just insert rows to table1

INSERT INTO Table1 (name) 
VALUES ('Jhon'), ('Mark');

And you'll have

|      ID | NAME |
------------------
| LHPL001 | Jhon |
| LHPL002 | Mark |

Here is SQLFiddle demo

Laravel Soft Delete posts

Here is the details from laravel.com

http://laravel.com/docs/eloquent#soft-deleting

When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, specify the softDelete property on the model:

class User extends Eloquent {

    protected $softDelete = true;

}

To add a deleted_at column to your table, you may use the softDeletes method from a migration:

$table->softDeletes();

Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results.

How can I iterate over files in a given directory?

You can try using glob module:

import glob

for filepath in glob.iglob('my_dir/*.asm'):
    print(filepath)

and since Python 3.5 you can search subdirectories as well:

glob.glob('**/*.txt', recursive=True) # => ['2.txt', 'sub/3.txt']

From the docs:

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.

Get all attributes of an element using jQuery

Using javascript function it is easier to get all the attributes of an element in NamedArrayFormat.

_x000D_
_x000D_
$("#myTestDiv").click(function(){_x000D_
  var attrs = document.getElementById("myTestDiv").attributes;_x000D_
  $.each(attrs,function(i,elem){_x000D_
    $("#attrs").html(    $("#attrs").html()+"<br><b>"+elem.name+"</b>:<i>"+elem.value+"</i>");_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<div id="myTestDiv" ekind="div" etype="text" name="stack">_x000D_
click This_x000D_
</div>_x000D_
<div id="attrs">Attributes are <div>
_x000D_
_x000D_
_x000D_

How to Select Min and Max date values in Linq Query

dim mydate = from cv in mydata.t1s
  select cv.date1 asc

datetime mindata = mydate[0];

How to get the hostname of the docker host from inside a docker container on that host without env vars

I ran

docker info | grep Name: | xargs | cut -d' ' -f2

inside my container.

nodejs mysql Error: Connection lost The server closed the connection

Creating and destroying the connections in each query maybe complicated, i had some headaches with a server migration when i decided to install MariaDB instead MySQL. For some reason in the file etc/my.cnf the parameter wait_timeout had a default value of 10 sec (it causes that the persistence can't be implemented). Then, the solution was set it in 28800, that's 8 hours. Well, i hope help somebody with this "güevonada"... excuse me for my bad english.

iOS 7 - Failing to instantiate default view controller

If you have been committing your code to source control regularly, this may save you the hassle of creating a new Storyboard and possibly introducing more problems...

I was able to solve this by comparing the Git source code of the version that worked against the broken one. The diff showed that the first line should contain the Id of the initial view controller, in my case, initialViewController="Q7U-eo-vxw". I searched through the source code to be sure that the id existed. All I had to do was put it back and everything worked again!

<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="5056" systemVersion="13E28" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" initialViewController="Q7U-eo-vxw">
    <dependencies>
        <deployment defaultVersion="1296" identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="3733"/>
    </dependencies>
    <scenes>

Here are some steps that can help you troubleshoot:

  1. Right click the failing Storyboard and use Source Control > Commit... to preserve your changes since the last commit.
  2. Try right clicking your failing Storyboard and use "Open As > Source Code" to view the XML of the storyboard.
  3. In the document element, look for the attribute named "initialViewController". If it is missing, don't worry, we'll fix that. If it is there, double click the id that is assigned to it, command-c to copy it, command-f command-v to search for it deeper in the document. This is the identifier of the controller that should provide the initial view. If it is not defined in the document then that is a problem - you should remove it from the document tag, in my case initialViewController="Q7U-eo-vxw".
  4. Go to Xcode menu item called View and choose Version Editor > Show Comparison View
  5. This shows your local version on the left and the historical version on the right. Click on the date beneath the historical version to get a list of the commits for this story board. Choose one that you know worked and compare the document element. What is the id of the *initialViewController? Is it different? If so, try editing it back in by hand and running. xcode historical compare tool in action

Bootstrap datepicker disabling past dates without current date

HTML

<input type="text" name="my_date" value="4/26/2015" class="datepicker">

JS

jQuery(function() {
  var datepicker = $('input.datepicker');

  if (datepicker.length > 0) {
    datepicker.datepicker({
      format: "mm/dd/yyyy",
      startDate: new Date()
    });
  }
});

That will highlight the default date as 4/26/2015 (Apr 26, 2015) in the calendar when opened and disable all the dates before current date.

Understanding inplace=True

inplace=True is used depending if you want to make changes to the original df or not.

df.drop_duplicates()

will only make a view of dropped values but not make any changes to df

df.drop_duplicates(inplace  = True)

will drop values and make changes to df.

Hope this helps.:)

Which selector do I need to select an option by its text?

This works for me

var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });

console.log($(targetOption).val());

Thanks for all the posts.

Ansible: Set variable to file content

lookup only works on localhost. If you want to retrieve variables from a variables file you made remotely use include_vars: {{ varfile }} . Contents of {{ varfile }} should be a dictionary of the form {"key":"value"}, you will find ansible gives you trouble if you include a space after the colon.

Find all files with name containing string

grep -R "somestring" | cut -d ":" -f 1

Change background color of R plot

adjustcolor("blanchedalmond",alpha.f = 0.3)

The above function provides a color code which corresponds to a transparent version of the input color (In this case the input color is "blanchedalmond.").

Input alpha values range on a scale of 0 to 1, 0 being completely transparent and 1 being completely opaque. (In this case, the code for the translucent shad of "blanchedalmond" given an alpha of .3 is "#FFEBCD4D." Be sure to include the hashtag symbol). You can make the new translucent color into the background color by using this function provided by joran earlier in this thread:

rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "blanchedalmond")

By using a translucent color, you can be sure that the graph's data can still be seen underneath after the background color is applied. Hope this helps!

Find and replace string values in list

In case you're wondering about the performance of the different approaches, here are some timings:

In [1]: words = [str(i) for i in range(10000)]

In [2]: %timeit replaced = [w.replace('1', '<1>') for w in words]
100 loops, best of 3: 2.98 ms per loop

In [3]: %timeit replaced = map(lambda x: str.replace(x, '1', '<1>'), words)
100 loops, best of 3: 5.09 ms per loop

In [4]: %timeit replaced = map(lambda x: x.replace('1', '<1>'), words)
100 loops, best of 3: 4.39 ms per loop

In [5]: import re

In [6]: r = re.compile('1')

In [7]: %timeit replaced = [r.sub('<1>', w) for w in words]
100 loops, best of 3: 6.15 ms per loop

as you can see for such simple patterns the accepted list comprehension is the fastest, but look at the following:

In [8]: %timeit replaced = [w.replace('1', '<1>').replace('324', '<324>').replace('567', '<567>') for w in words]
100 loops, best of 3: 8.25 ms per loop

In [9]: r = re.compile('(1|324|567)')

In [10]: %timeit replaced = [r.sub('<\1>', w) for w in words]
100 loops, best of 3: 7.87 ms per loop

This shows that for more complicated substitutions a pre-compiled reg-exp (as in 9-10) can be (much) faster. It really depends on your problem and the shortest part of the reg-exp.

How to get the index of a maximum element in a NumPy array along one axis

There is argmin() and argmax() provided by numpy that returns the index of the min and max of a numpy array respectively.

Say e.g for 1-D array you'll do something like this

_x000D_
_x000D_
import numpy as np

a = np.array([50,1,0,2])

print(a.argmax()) # returns 0
print(a.argmin()) # returns 2
_x000D_
_x000D_
_x000D_

And similarly for multi-dimensional array

_x000D_
_x000D_
import numpy as np

a = np.array([[0,2,3],[4,30,1]])

print(a.argmax()) # returns 4
print(a.argmin()) # returns 0
_x000D_
_x000D_
_x000D_

Note that these will only return the index of the first occurrence.

Check if table exists without using "select from"

You can query the INFORMATION_SCHEMA tables system view:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'testtable';

If no rows returned, then the table doesn't exist.

SQL - Update multiple records in one query

Camille's solution worked. Turned it into a basic PHP function, which writes up the SQL statement. Hope this helps someone else.

    function _bulk_sql_update_query($table, $array)
    {
        /*
         * Example:
        INSERT INTO mytable (id, a, b, c)
        VALUES (1, 'a1', 'b1', 'c1'),
        (2, 'a2', 'b2', 'c2'),
        (3, 'a3', 'b3', 'c3'),
        (4, 'a4', 'b4', 'c4'),
        (5, 'a5', 'b5', 'c5'),
        (6, 'a6', 'b6', 'c6')
        ON DUPLICATE KEY UPDATE id=VALUES(id),
        a=VALUES(a),
        b=VALUES(b),
        c=VALUES(c);
    */
        $sql = "";

        $columns = array_keys($array[0]);
        $columns_as_string = implode(', ', $columns);

        $sql .= "
      INSERT INTO $table
      (" . $columns_as_string . ")
      VALUES ";

        $len = count($array);
        foreach ($array as $index => $values) {
            $sql .= '("';
            $sql .= implode('", "', $array[$index]) . "\"";
            $sql .= ')';
            $sql .= ($index == $len - 1) ? "" : ", \n";
        }

        $sql .= "\nON DUPLICATE KEY UPDATE \n";

        $len = count($columns);
        foreach ($columns as $index => $column) {

            $sql .= "$column=VALUES($column)";
            $sql .= ($index == $len - 1) ? "" : ", \n";
        }

        $sql .= ";";

        return $sql;
    }

Where to change the value of lower_case_table_names=2 on windows xampp

Look for a file named my.ini in your hard disk, in my system it's in

c:\program files\mysql\mysql server 5.1

If it's not my.ini it should be my.cnf

Docker - Container is not running

This happens with images for which the script does not launch a service awaiting requests, therefore the container exits at the end of the script.

This is typically the case with most base OS images (centos, debian, etc.), or also with the node images.

Your best bet is to run the image in interactive mode. Example below with the node image:

docker run -it node /bin/bash

Output is

root@cacc7897a20c:/# echo $SHELL
/bin/bash

How to make inline functions in C#

Yes.

You can create anonymous methods or lambda expressions:

Func<string, string> PrefixTrimmer = delegate(string x) {
    return x ?? "";
};
Func<string, string> PrefixTrimmer = x => x ?? "";

How to change angular port from 4200 to any other

This will automatically open your window as well

ng serve -o --port 4801

Looping through GridView rows and Checking Checkbox Control

you have to iterate gridview Rows

for (int count = 0; count < grd.Rows.Count; count++)
{
    if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
    {     
      ((Label)grd.Rows[count].FindControl("labelID")).Text
    }
}

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

A single listening port can accept more than one connection simultaneously.

There is a '64K' limit that is often cited, but that is per client per server port, and needs clarifying.

Each TCP/IP packet has basically four fields for addressing. These are:

source_ip source_port destination_ip destination_port
<----- client ------> <--------- server ------------>

Inside the TCP stack, these four fields are used as a compound key to match up packets to connections (e.g. file descriptors).

If a client has many connections to the same port on the same destination, then three of those fields will be the same - only source_port varies to differentiate the different connections. Ports are 16-bit numbers, therefore the maximum number of connections any given client can have to any given host port is 64K.

However, multiple clients can each have up to 64K connections to some server's port, and if the server has multiple ports or either is multi-homed then you can multiply that further.

So the real limit is file descriptors. Each individual socket connection is given a file descriptor, so the limit is really the number of file descriptors that the system has been configured to allow and resources to handle. The maximum limit is typically up over 300K, but is configurable e.g. with sysctl.

The realistic limits being boasted about for normal boxes are around 80K for example single threaded Jabber messaging servers.

CRON command to run URL address every 5 minutes

Based on the comments try

*/5 * * * * wget http://example.com/check

[Edit: 10 Apr 2017]

This answer still seems to be getting a few hits so I thought I'd add a link to a new page I stumbled across which may help create cron commands: https://crontab.guru

How to remove trailing whitespace in code, using another script?

If you're looking to tidy up for PEP8, this will trim trailing whitespace for your whole project:

import os

PATH = '/path/to/your/project'

for path, dirs, files in os.walk(PATH):
    for f in files:
        file_name, file_extension = os.path.splitext(f)
        if file_extension == '.py':
            path_name = os.path.join(path, f)
            with open(path_name, 'r') as fh:
                new = [line.rstrip() for line in fh]
            with open(path_name, 'w') as fh:
                [fh.write('%s\n' % line) for line in new]

Which characters make a URL invalid?

I need to select character to split urls in string, so I decided to create list of characters which could not be found in URL by myself:

>>> allowed = "-_.~!*'();:@&=+$,/?%#[]?@ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
>>> from string import printable
>>> ''.join(set(printable).difference(set(allowed)))
'`" <\x0b\n\r\x0c\\\t{^}|>'

So, the possible choices are the newline, tab, space, backslash and "<>{}^|. I guess I'll go with the space or newline. :)

Add centered text to the middle of a <hr/>-like line

How about:

_x000D_
_x000D_
<div style="width: 100%; height: 20px; border-bottom: 1px solid black; text-align: center">_x000D_
  <span style="font-size: 40px; background-color: #F3F5F6; padding: 0 10px;">_x000D_
    Section Title <!--Padding is optional-->_x000D_
  </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Check out this JSFiddle.

You can use vw or % to make it responsive.

SQL: How to perform string does not equal

Try the following query

select * from table
where NOT (tester = 'username')

PowerShell to remove text from a string

This should do what you want:

C:\PS> if ('=keep this,' -match '=([^,]*)') { $matches[1] }
keep this