Programs & Examples On #Werkzeug

Werkzeug is a WSGI utility library for Python. It's widely used and BSD licensed.

Get raw POST body in Python Flask regardless of Content-Type header

I created a WSGI middleware that stores the raw body from the environ['wsgi.input'] stream. I saved the value in the WSGI environ so I could access it from request.environ['body_copy'] within my app.

This isn't necessary in Werkzeug or Flask, as request.get_data() will get the raw data regardless of content type, but with better handling of HTTP and WSGI behavior.

This reads the entire body into memory, which will be an issue if for example a large file is posted. This won't read anything if the Content-Length header is missing, so it won't handle streaming requests.

from io import BytesIO

class WSGICopyBody(object):
    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):
        length = int(environ.get('CONTENT_LENGTH') or 0)
        body = environ['wsgi.input'].read(length)
        environ['body_copy'] = body
        # replace the stream since it was exhausted by read()
        environ['wsgi.input'] = BytesIO(body)
        return self.application(environ, start_response)

app.wsgi_app = WSGICopyBody(app.wsgi_app)
request.environ['body_copy']

Configure Flask dev server to be visible across the network

go to project path set FLASK_APP=ABC.py SET FLASK_ENV=development

flask run -h [yourIP] -p 8080 you will following o/p on CMD:- * Serving Flask app "expirement.py" (lazy loading) * Environment: development * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 199-519-700 * Running on http://[yourIP]:8080/ (Press CTRL+C to quit)

Get IP address of visitors using Flask for Python

If you use Nginx behind other balancer, for instance AWS Application Balancer, HTTP_X_FORWARDED_FOR returns list of addresses. It can be fixed like that:

if 'X-Forwarded-For' in request.headers:
    proxy_data = request.headers['X-Forwarded-For']
    ip_list = proxy_data.split(',')
    user_ip = ip_list[0]  # first address in list is User IP
else:
    user_ip = request.remote_addr  # For local development

Get the data received in a Flask request

Here's an example of parsing posted JSON data and echoing it back.

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/foo', methods=['POST']) 
def foo():
    data = request.json
    return jsonify(data)

To post JSON with curl:

curl -i -H "Content-Type: application/json" -X POST -d '{"userId":"1", "username": "fizz bizz"}' http://localhost:5000/foo

Or to use Postman:

using postman to post JSON

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).

Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

Pandas rename column by position?

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)

msvcr110.dll is missing from computer error while installing PHP

You need to install the Visual C++ libraries: http://www.microsoft.com/en-us/download/details.aspx?id=30679

As mentioned by Stuart McLaughlin, make sure you get the x86 version even if you use a 64-bits OS because PHP needs some 32-bit libraries.

Check if element is clickable in Selenium Java

wait.until(ExpectedConditions) won't return null, it will either meet the condition or throw TimeoutException.

You can check if the element is displayed and enabled

WebElement element = driver.findElement(By.xpath);
if (element.isDisplayed() && element.isEnabled()) {
    element.click();
}

How to run Spyder in virtual environment?

Additional to tomaskazemekas's answer: you should install spyder in that virtual environment by:

conda install -n myenv spyder

(on Windows, for Linux or MacOS, you can search for similar commands)

How do I get the name of the rows from the index of a data frame?

if you want to get the index values, you can simply do:

dataframe.index

this will output a pandas.core.index

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

I get the error above when I try to log into MYSQL after installing it using brew, I am running MacOs, Oh yea I also noticed mysql is running I have restarted numerous times with no luck resolving the issue along with removing mysql and numerous reinstalls!

So simple I could slap myself, no but really, I solved this by CD into the temp folder that contains mysqlx.sock and mysql.sock.lock files, I deleted the single sock.lock file only and this solved my issue after doing so and I can log into mysql using the mysql -uroot command. Here are the commands I used. (this issue had me hung up for a while)

~ cd /tmp 

/tmp ls 

(this will list all the sock files in the temp folder, output shown below)

com.apple.launchd.8AgGW2s9Bb mysql.sock.lock
com.apple.launchd.batxrSISAJ mysqlx.sock
com.apple.launchd.cRCaxtT41m mysqlx.sock.lock
com.google.Keystone          powerlog

then run

rm -R mysql.sock.lock 

(use command above to remove the sock.lock file from the /tmp directory this resolved my issue)

hope this helped :)

Bash mkdir and subfolders

FWIW,

Poor mans security folder (to protect a public shared folder from little prying eyes ;) )

mkdir -p {0..9}/{0..9}/{0..9}/{0..9}

Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.

HTML5 and frameborder

Since the frameborder attribute is only necessary for IE, there is another way to get around the validator. This is a lightweight way that doesn't require Javascript or any DOM manipulation.

<!--[if IE]>
   <iframe src="source" frameborder="0">?</iframe>
<![endif]-->
<!--[if !IE]>-->
   <iframe src="source" style="border:none">?</iframe>
<!-- <![endif]-->

Azure SQL Database "DTU percentage" metric

From this document, this DTU percent is determined by this query:

SELECT end_time,   
  (SELECT Max(v)    
   FROM (VALUES (avg_cpu_percent), (avg_data_io_percent), 
(avg_log_write_percent)) AS    
   value(v)) AS [avg_DTU_percent]   
FROM sys.dm_db_resource_stats;  

looks like the max of avg_cpu_percent, avg_data_io_percent and avg_log_write_percent

Reference:

https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-resource-stats-azure-sql-database

LIKE vs CONTAINS on SQL Server

Having run both queries on a SQL Server 2012 instance, I can confirm the first query was fastest in my case.

The query with the LIKE keyword showed a clustered index scan.

The CONTAINS also had a clustered index scan with additional operators for the full text match and a merge join.

Plan

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

jQuery javascript regex Replace <br> with \n

myString.replace(/<br ?\/?>/g, "\n")

How to hide form code from view code/inspect element browser?

you can not stop user from seeing our code but you can avoid it by disabling some keys

simply you can do <body oncontextmenu="return false" onkeydown="return false;" onmousedown="return false;"><!--Your body context--> </body>

After doing this following keys get disabled automatically

1. Ctrl + Shift + U 2. Ctrl + Shift + C 3. Ctrl + Shift + I 4. Right Click of mouse 5. F12 Key

JavaScript ES6 promise for loop

here's my 2 cents worth:

  • resuable function forpromise()
  • emulates a classic for loop
  • allows for early exit based on internal logic, returning a value
  • can collect an array of results passed into resolve/next/collect
  • defaults to start=0,increment=1
  • exceptions thrown inside loop are caught and passed to .catch()

_x000D_
_x000D_
    function forpromise(lo, hi, st, res, fn) {_x000D_
        if (typeof res === 'function') {_x000D_
            fn = res;_x000D_
            res = undefined;_x000D_
        }_x000D_
        if (typeof hi === 'function') {_x000D_
            fn = hi;_x000D_
            hi = lo;_x000D_
            lo = 0;_x000D_
            st = 1;_x000D_
        }_x000D_
        if (typeof st === 'function') {_x000D_
            fn = st;_x000D_
            st = 1;_x000D_
        }_x000D_
        return new Promise(function(resolve, reject) {_x000D_
_x000D_
            (function loop(i) {_x000D_
                if (i >= hi) return resolve(res);_x000D_
                const promise = new Promise(function(nxt, brk) {_x000D_
                    try {_x000D_
                        fn(i, nxt, brk);_x000D_
                    } catch (ouch) {_x000D_
                        return reject(ouch);_x000D_
                    }_x000D_
                });_x000D_
                promise._x000D_
                catch (function(brkres) {_x000D_
                    hi = lo - st;_x000D_
                    resolve(brkres)_x000D_
                }).then(function(el) {_x000D_
                    if (res) res.push(el);_x000D_
                    loop(i + st)_x000D_
                });_x000D_
            })(lo);_x000D_
_x000D_
        });_x000D_
    }_x000D_
_x000D_
_x000D_
    //no result returned, just loop from 0 thru 9_x000D_
    forpromise(0, 10, function(i, next) {_x000D_
        console.log("iterating:", i);_x000D_
        next();_x000D_
    }).then(function() {_x000D_
_x000D_
_x000D_
        console.log("test result 1", arguments);_x000D_
_x000D_
        //shortform:no result returned, just loop from 0 thru 4_x000D_
        forpromise(5, function(i, next) {_x000D_
            console.log("counting:", i);_x000D_
            next();_x000D_
        }).then(function() {_x000D_
_x000D_
            console.log("test result 2", arguments);_x000D_
_x000D_
_x000D_
_x000D_
            //collect result array, even numbers only_x000D_
            forpromise(0, 10, 2, [], function(i, collect) {_x000D_
                console.log("adding item:", i);_x000D_
                collect("result-" + i);_x000D_
            }).then(function() {_x000D_
_x000D_
                console.log("test result 3", arguments);_x000D_
_x000D_
                //collect results, even numbers, break loop early with different result_x000D_
                forpromise(0, 10, 2, [], function(i, collect, break_) {_x000D_
                    console.log("adding item:", i);_x000D_
                    if (i === 8) return break_("ending early");_x000D_
                    collect("result-" + i);_x000D_
                }).then(function() {_x000D_
_x000D_
                    console.log("test result 4", arguments);_x000D_
_x000D_
                    // collect results, but break loop on exception thrown, which we catch_x000D_
                    forpromise(0, 10, 2, [], function(i, collect, break_) {_x000D_
                        console.log("adding item:", i);_x000D_
                        if (i === 4) throw new Error("failure inside loop");_x000D_
                        collect("result-" + i);_x000D_
                    }).then(function() {_x000D_
_x000D_
                        console.log("test result 5", arguments);_x000D_
_x000D_
                    })._x000D_
                    catch (function(err) {_x000D_
_x000D_
                        console.log("caught in test 5:[Error ", err.message, "]");_x000D_
_x000D_
                    });_x000D_
_x000D_
                });_x000D_
_x000D_
            });_x000D_
_x000D_
_x000D_
        });_x000D_
_x000D_
_x000D_
_x000D_
    });
_x000D_
_x000D_
_x000D_

How do you create a Swift Date object?

I often have a need to combine date values from one place with time values for another. I wrote a helper function to accomplish this.

let startDateTimeComponents = NSDateComponents()
startDateTimeComponents.year = NSCalendar.currentCalendar().components(NSCalendarUnit.Year, fromDate: date).year
startDateTimeComponents.month = NSCalendar.currentCalendar().components(NSCalendarUnit.Month, fromDate: date).month
startDateTimeComponents.day = NSCalendar.currentCalendar().components(NSCalendarUnit.Day, fromDate: date).day
startDateTimeComponents.hour = NSCalendar.currentCalendar().components(NSCalendarUnit.Hour, fromDate: time).hour
startDateTimeComponents.minute = NSCalendar.currentCalendar().components(NSCalendarUnit.Minute, fromDate: time).minute
let startDateCalendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
combinedDateTime = startDateCalendar!.dateFromComponents(startDateTimeComponents)!

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

On Mac OS X Lion, to set visualgc to run, I used:

export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home

Correct way to initialize empty slice

They are equivalent. See this code:

mySlice1 := make([]int, 0)
mySlice2 := []int{}
fmt.Println("mySlice1", cap(mySlice1))
fmt.Println("mySlice2", cap(mySlice2))

Output:

mySlice1 0
mySlice2 0

Both slices have 0 capacity which implies both slices have 0 length (cannot be greater than the capacity) which implies both slices have no elements. This means the 2 slices are identical in every aspect.

See similar questions:

What is the point of having nil slice and empty slice in golang?

nil slices vs non-nil slices vs empty slices in Go language

How would I stop a while loop after n amount of time?

import time

abort_after = 5 * 60
start = time.time()

while True:
  delta = time.time() - start
  if delta >= abort_after:
    break

Jquery: Find Text and replace

$("#id1 p:contains('dog')").html("doll");

that'll do it.

http://jsfiddle.net/pgDFQ/

Searching word in vim?

  1. vim filename
  2. press /
  3. type word which you want to search
  4. press Enter

Bash write to file without echo?

Only redirection won't work, since there's nothing to connect the now-open file descriptors. So no, there is no way like this.

403 - Forbidden: Access is denied. ASP.Net MVC

I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.

How to declare a global variable in JavaScript

If you have to generate global variables in production code (which should be avoided) always declare them explicitly:

window.globalVar = "This is global!";

While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode.

SQL 'LIKE' query using '%' where the search criteria contains '%'

To escape a character in sql you can use !:


EXAMPLE - USING ESCAPE CHARACTERS

It is important to understand how to "Escape Characters" when pattern matching. These examples deal specifically with escaping characters in Oracle.

Let's say you wanted to search for a % or a _ character in the SQL LIKE condition. You can do this using an Escape character.

Please note that you can only define an escape character as a single character (length of 1).

For example:

SELECT *
FROM suppliers
WHERE supplier_name LIKE '!%' escape '!';

This SQL LIKE condition example identifies the ! character as an escape character. This statement will return all suppliers whose name is %.

Here is another more complicated example using escape characters in the SQL LIKE condition.

SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!%' escape '!';

This SQL LIKE condition example returns all suppliers whose name starts with H and ends in %. For example, it would return a value such as 'Hello%'.

You can also use the escape character with the _ character in the SQL LIKE condition.

For example:

SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!_' escape '!';

This SQL LIKE condition example returns all suppliers whose name starts with H and ends in _ . For example, it would return a value such as 'Hello_'.


Reference: sql/like

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

This issue should be fixed in the newest version of Homebrew. Try reinstalling it, which is described on the Homebrew home page.

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

I found that in my code when I used a ration or percentage for line-height line-height;1.5;

My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px; so that I could predict exactly how many pixels each page would take with a given number of lines.

What is the correct way to represent null XML elements?

It depends on how you validate your XML. If you use XML Schema validation, the correct way of representing null values is with the xsi:nil attribute.

[Source]

How do I return the SQL data types from my query?

You could also insert the results (or top 10 results) into a temp table and get the columns from the temp table (as long as the column names are all different).

SELECT TOP 10 *
INTO #TempTable
FROM <DataSource>

Then use:

EXEC tempdb.dbo.sp_help N'#TempTable';

or

SELECT * 
FROM tempdb.sys.columns 
WHERE [object_id] = OBJECT_ID(N'tempdb..#TempTable');

Extrapolated from Aaron's answer here.

Converting a String to a List of Words?

A regular expression for words would give you the most control. You would want to carefully consider how to deal with words with dashes or apostrophes, like "I'm".

.NET obfuscation tools/strategy

We're using SmartAssembly on our windows client. Works just fine.

Does add some extra problems too. Printing out your class names in log files/exceptions have to be de-obfuscated. And of course can't create a class from its name. So it's a good idea to take a look at your client and see which problems you can get by obfuscating.

Custom Input[type="submit"] style not working with jquerymobile button

jQuery Mobile >= 1.4

Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

.ui-input-btn.custom-btn {
   border:1px solid red;
   text-decoration:none;
   font-family:helvetica;
   color:red;
   background:url(img.png) repeat-x;
}

Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

<input type="button" data-wrapper-class="custom-btn">

Demo


jQuery Mobile <= 1.3

Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

Demo

div.ui-btn, input[type="submit"] {
 border:1px solid red !important;
 text-decoration:none !important;
 font-family:helvetica !important;
 color:red !important;
 background:url(../images/btn_hover.png) repeat-x !important;
}

HTML Canvas Full Screen

On document load set the

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

How do I put variable values into a text string in MATLAB?

Here's how you convert numbers to strings, and join strings to other things (it's weird):

>> ['the number is ' num2str(15) '.']
ans =
the number is 15.

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

jQuery AJAX Character Encoding

I had an issue with Swedish/Norwegian letters showing up as question marks, despite having specified:

contentType: "application/json; charset=utf-8",

This was solved by adding encodeURIComponent to the string.

url: "/set_comment.do?text=" + encodeURIComponent(comment),

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

So none of the above stuff worked for me. Except this: edit httpd.conf,

find the line

Listen 80 

and change to

listen 0.0.0.0:80 

if you are running windows 8, its got something to do with using ipv6 instead of ipv4

Does Spring @Transactional attribute work on a private method?

If you need to wrap a private method inside a transaction and don't want to use aspectj, you can use TransactionTemplate.

@Service
public class MyService {

    @Autowired
    private TransactionTemplate transactionTemplate;

    private void process(){
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                processInTransaction();
            }
        });

    }

    private void processInTransaction(){
        //...
    }

}

How to determine the Schemas inside an Oracle Data Pump Export file

The running the impdp command to produce an sqlfile, you will need to run it as a user which has the DATAPUMP_IMP_FULL_DATABASE role.

Or... run it as a low privileged user and use the MASTER_ONLY=YES option, then inspect the master table. e.g.

select value_t 
from SYS_IMPORT_TABLE_01 
where name = 'CLIENT_COMMAND' 
and process_order = -59;

col object_name for a30
col processing_status head STATUS for a6
col processing_state head STATE for a5
select distinct
  object_schema,
  object_name,
  object_type,
  object_tablespace,
  process_order,
  duplicate,
  processing_status,
  processing_state
from sys_import_table_01
where process_order > 0
and object_name is not null
order by object_schema, object_name
/

http://download.oracle.com/otndocs/products/database/enterprise_edition/utilities/pdf/oow2011_dp_mastering.pdf

Remove stubborn underline from link

As a rule, if your "underline" is not the same color as your text [and the 'color:' is not overridden inline] it is not coming from "text-decoration:" It has to be "border-bottom:"

Don't forget to take the border off your pseudo classes too!

a, a:link, a:visited, a:active, a:hover {border:0!important;}

This snippet assumes its on an anchor, change to it's wrapper accordingly... and use specificity instead of "!important" after you track down the root cause.

OnclientClick and OnClick is not working at the same time?

Your JavaScript is fine, unless you have other scripts running on this page which may corrupt everything. You may check this using Firebug.

I've now tested a bit and it really seems that ASP.net ignores disabled controls. Basically the postback is issued, but probably the framework ignores such events since it "assumes" that a disabled button cannot raise any postback and so it ignores possibly attached handlers. Now this is just my personal reasoning, one could use Reflector to check this in more depth.

As a solution you could really try to do the disabling at a later point, basically you delay the control.disabled = "disabled" call using a JavaTimer or some other functionality. In this way 1st the postback to the server is issued before the control is being disabled by the JavaScript function. Didn't test this but it could work

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

  1. Tools
  2. NuGet Package Manager
  3. Manage NuGet Packages For Solution
  4. Browse
  5. NUnitTestAdapter.WithFramework
  6. Ctrl+R,A to build/run tests

enter image description here

Using NUnitTestAdapter.WithFramework makes sure there are little/no inconsistencies across versions of NUnit and NUnit Adapter (i.e. "it just works")

Vertically aligning a checkbox

<div>
    <input type="checkbox">
    <img src="/image.png" />
</div>
input[type="checkbox"]
{
    margin-top: -50%;
    vertical-align: middle;
}

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

To this error:

# git pull
sign_and_send_pubkey: signing failed: agent refused operation
[email protected]: Permission denied (publickey).    
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

Verify or add again the public key in Github account > profile > ssh.

I solved like this:

# chmod 400 ~/.ssh/id_rsa

# ls  ~/.ssh/id_rsa -ls  
4 -r--------. 1 reinaldo reinaldo 1679 Jul 26  2017 /home/reinaldo/.ssh/id_rsa

# git pull                                 
remote: Counting objects: 35, done.
remote: Compressing objects: 100% (19/19), done.
remote: Total 35 (delta 9), reused 34 (delta 9), pack-reused 0
Unpacking objects: 100% (35/35), done.

Thank you.

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

I'm having exactly the same problem. The only workaround I've found, is to replace the fragments by a new instance, each time the tabs are changed.

ft.replace(R.id.fragment_container, Fragment.instantiate(PlayerMainActivity.this, fragment.getClass().getName()));

Not a real solution, but i haven't found a way to reuse the previous fragment instance...

java.time.format.DateTimeParseException: Text could not be parsed at index 21

The default parser can parse your input. So you don't need a custom formatter and

String dateTime = "2012-02-22T02:06:58.147Z";
ZonedDateTime d = ZonedDateTime.parse(dateTime);

works as expected.

'negative' pattern matching in python

and(re.search("bla_bla_pattern", str_item, re.IGNORECASE) == None)

is working.

Passing null arguments to C# methods

You can use NullableValueTypes (like int?) for this. The code would be like this:

private void Example(int? arg1, int? arg2)
{
    if(!arg1.HasValue)
    {
        //do something
    }
    if(!arg2.HasValue)
    {
        //do something else
    }
}

What's the difference between map() and flatMap() methods in Java 8?

map() and flatMap()

  1. map()

Just takes a Function a lambda param where T is element and R the return element built using T. At the end we'll have a Stream with objects of Type R. A simple example can be:

Stream
  .of(1,2,3,4,5)
  .map(myInt -> "preFix_"+myInt)
  .forEach(System.out::println);

It simply takes elements 1 to 5 of Type Integer, uses each element to build a new element from type String with value "prefix_"+integer_value and prints it out.

  1. flatMap()

It is useful to know that flatMap() takes a function F<T, R> where

  • T is a type from which a Stream can be built from/with. It can be a List (T.stream()), an array (Arrays.stream(someArray)), etc.. anything that from which a Stream can be with/or form. in the example below each dev has many languages, so dev. Languages is a List and will use a lambda parameter.

  • R is the resulting Stream that will be built using T. Knowing that we have many instances of T, we will naturally have many Streams from R. All these Streams from Type R will now be combined into one single 'flat' Stream from Type R.

Example

The examples of Bachiri Taoufiq see its answer here are simple and easy to understanding. Just for clarity, let just say we have a team of developers:

dev_team = {dev_1,dev_2,dev_3}

, with each developer knowing many languages:

dev_1 = {lang_a,lang_b,lang_c},
dev_2 = {lang_d},
dev_2 = {lang_e,lang_f}

Applying Stream.map() on dev_team to get the languages of each dev:

dev_team.map(dev -> dev.getLanguages())

will give you this structure:

{ 
  {lang_a,lang_b,lang_c},
  {lang_d},
  {lang_e,lang_f}
}

which is basically a List<List<Languages>> /Object[Languages[]]. Not so very pretty, nor Java8-like!!

with Stream.flatMap() you can 'flatten' things out as it takes the above structure
and turns it into {lang_a, lang_b, lang_c, lang_d, lang_e, lang_f}, which can basically used as List<Languages>/Language[]/etc...

so in the end, your code would make more sense like this:

dev_team
   .stream()    /* {dev_1,dev_2,dev_3} */
   .map(dev -> dev.getLanguages()) /* {{lang_a,...,lang_c},{lang_d}{lang_e,lang_f}}} */
   .flatMap(languages ->  languages.stream()) /* {lang_a,...,lang_d, lang_e, lang_f} */
   .doWhateverWithYourNewStreamHere();

or simply:

dev_team
       .stream()    /* {dev_1,dev_2,dev_3} */
       .flatMap(dev -> dev.getLanguages().stream()) /* {lang_a,...,lang_d, lang_e, lang_f} */
       .doWhateverWithYourNewStreamHere();

When to use map() and use flatMap():

  • Use map() when each element of type T from your stream is supposed to be mapped/transformed to a single element of type R. The result is a mapping of type (1 start element -> 1 end element) and new stream of elements of type R is returned.

  • Use flatMap() when each element of type T from your stream is supposed to mapped/transformed to a Collections of elements of type R. The result is a mapping of type (1 start element -> n end elements). These Collections are then merged (or flattened) to a new stream of elements of type R. This is useful for example to represent nested loops.

Pre Java 8:

List<Foo> myFoos = new ArrayList<Foo>();
    for(Foo foo: myFoos){
        for(Bar bar:  foo.getMyBars()){
            System.out.println(bar.getMyName());
        }
    }

Post Java 8

myFoos
    .stream()
    .flatMap(foo -> foo.getMyBars().stream())
    .forEach(bar -> System.out.println(bar.getMyName()));

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

yes, it accepts the tuple of four arguments, if you have Number of training Images(or whatever)=6000, image size=28x28 and a grayscale image you'll have parameters as (6000,28,28,1)

the last argument is 1 for greyscale and 3 for color images.

How to use subList()

Using subList(30, 38); will fail because max index 38 is not available in list, so its not possible.

Only way may be before asking for the sublist, you explicitly determine the max index using list size() method.

for example, check size, which returns 35, so call sublist(30, size());

OR

COPIED FROM pb2q comment

dataList = dataList.subList(30, 38 > dataList.size() ? dataList.size() : 38);

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

you just need to reset dependencies in app.gradle file like old one as

androidTestImplementation 'com.android.support.test:runner:0.5'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'

to new one as

androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

What is the difference between Forking and Cloning on GitHub?

Another weird subtle difference on GitHub is that changes to forks are not counted in your activity log until your changes are pulled into the original repo. What's more, to change a fork into a proper clone, you have to contact Github support, apparently.

From Why are my contributions not showing up:

Commit was made in a fork

Commits made in a fork will not count toward your contributions. To make them count, you must do one of the following:

Open a pull request to have your changes merged into the parent repository. To detach the fork and turn it into a standalone repository on GitHub, contact GitHub Support. If the fork has forks of its own, let support know if the forks should move with your repository into a new network or remain in the current network. For more information, see "About forks."

substring of an entire column in pandas dataframe

Use the str accessor with square brackets:

df['col'] = df['col'].str[:9]

Or str.slice:

df['col'] = df['col'].str.slice(0, 9)

Can constructors be async?

Since it is not possible to make an async constructor, I use a static async method that returns a class instance created by a private constructor. This is not elegant but it works ok.

public class ViewModel       
{       
    public ObservableCollection<TData> Data { get; set; }       

    //static async method that behave like a constructor       
    async public static Task<ViewModel> BuildViewModelAsync()  
    {       
        ObservableCollection<TData> tmpData = await GetDataTask();  
        return new ViewModel(tmpData);
    }       

    // private constructor called by the async method
    private ViewModel(ObservableCollection<TData> Data)
    {
        this.Data = Data;   
    }
}  

google console error `OR-IEH-01`

Recently I was also having this issue, then I contacted Google Support and they gave me this link to provide required info, I posted and within 24 hours my problem was fixed.

Link: https://support.google.com/payments/contact/alt_account_verification

How can I get (query string) parameters from the URL in Next.js?

Use router-hook.

You can use the useRouter hook in any component in your application.

https://nextjs.org/docs/api-reference/next/router#userouter

pass Param

import Link from "next/link";

<Link href={{ pathname: '/search', query: { keyword: 'this way' } }}><a>path</a></Link>
Or
import Router from 'next/router'

Router.push({
    pathname: '/search',
    query: { keyword: 'this way' },
})

In Component

import { useRouter } from 'next/router'

export default () => {
  const router = useRouter()
  console.log(router.query);

  ...
}

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

Finding absolute value of a number without using Math.abs()

Although this shouldn't be a bottle neck as branching issues on modern processors isn't normally a problem, but in the case of integers you could go for a branch-less solution as outlined here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs.

(x + (x >> 31)) ^ (x >> 31);

This does fail in the obvious case of Integer.MIN_VALUE however, so this is a use at your own risk solution.

Create a txt file using batch file in a specific folder

Changed the set to remove % as that will write to text file as Echo on or off

echo off
title Custom Text File
cls
set /p txt=What do you want it to say? ; 
echo %txt% > "D:\Testing\dblank.txt"
exit

How do you reverse a string in place in JavaScript?

Legible way using spread operator:

_x000D_
_x000D_
const reverseString = str => [...str].reverse().join('');

console.log(reverseString('ABC'));
_x000D_
_x000D_
_x000D_

Sum all the elements java arraylist

Two ways:

Use indexes:

double sum = 0;
for(int i = 0; i < m.size(); i++)
    sum += m.get(i);
return sum;

Use the "for each" style:

double sum = 0;
for(Double d : m)
    sum += d;
return sum;

The application was unable to start correctly (0xc000007b)

I tried all the things specified here and found yet another answer. I had to compile my application with 32-bit DLLs. I had built the libraries both in 32-bit and 64-bit but had my PATH set to 64-bit libraries. After I recompiled my application (with a number of changes in my code as well) I got this dreaded error and struggled for two days. Finally, after trying a number of other things, I changed my PATH to have the 32-bit DLLs before the 64-bit DLLs (they have the same names). And it worked. I am just adding it here for completeness.

Capture HTML Canvas as gif/jpg/png/pdf?

I thought I'd extend the scope of this question a bit, with some useful tidbits on the matter.

In order to get the canvas as an image, you should do the following:

var canvas = document.getElementById("mycanvas");
var image = canvas.toDataURL("image/png");

You can use this to write the image to the page:

document.write('<img src="'+image+'"/>');

Where "image/png" is a mime type (png is the only one that must be supported). If you would like an array of the supported types you can do something along the lines of this:

var imageMimes = ['image/png', 'image/bmp', 'image/gif', 'image/jpeg', 'image/tiff']; //Extend as necessary 
var acceptedMimes = new Array();
for(i = 0; i < imageMimes.length; i++) {
    if(canvas.toDataURL(imageMimes[i]).search(imageMimes[i])>=0) {
        acceptedMimes[acceptedMimes.length] = imageMimes[i];
    }
}

You only need to run this once per page - it should never change through a page's lifecycle.

If you wish to make the user download the file as it is saved you can do the following:

var canvas = document.getElementById("mycanvas");
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); //Convert image to 'octet-stream' (Just a download, really)
window.location.href = image;

If you're using that with different mime types, be sure to change both instances of image/png, but not the image/octet-stream. It is also worth mentioning that if you use any cross-domain resources in rendering your canvas, you will encounter a security error when you try to use the toDataUrl method.

How to select into a variable in PL/SQL when the result might be null?

From all the answers above, Björn's answer seems to be the most elegant and short. I personally used this approach many times. MAX or MIN function will do the job equally well. Complete PL/SQL follows, just the where clause should be specified.

declare v_column my_table.column%TYPE;
begin
    select MIN(column) into v_column from my_table where ...;
    DBMS_OUTPUT.PUT_LINE('v_column=' || v_column);
end;

Class has no initializers Swift

In my case I have declared a Bool like this:

var isActivityOpen: Bool 

i.e. I declared it without unwrapping so, This is how I solved the (no initializer) error :

var isActivityOpen: Bool!

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

You probably want to assign the lastname you are reading out here

lastname = sheet.cell(row=r, column=3).value

to something; currently the program just forgets it

you could do that two lines after, like so

unpaidMembers[name] = lastname, email

your program will still crash at the same place, because .items() still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))

good news is, python can handle this

for name, (lastname, email) in unpaidMembers.items():

etc.

Finding the max value of an attribute in an array of objects

Well, first you should parse the JSON string, so that you can easily access it's members:

var arr = $.parseJSON(str);

Use the map method to extract the values:

arr = $.map(arr, function(o){ return o.y; });

Then you can use the array in the max method:

var highest = Math.max.apply(this,arr);

Or as a one-liner:

var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));

How to display table data more clearly in oracle sqlplus

I usually start with something like:

set lines 256
set trimout on
set tab off

Have a look at help set if you have the help information installed. And then select name,address rather than select * if you really only want those two columns.

Is there a Newline constant defined in Java like Environment.Newline in C#?

Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").

When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.

Maximum number of rows in an MS Access database engine table?

It all depends. Theoretically using a single column with 4 byte data type. You could store 300 000 rows. But there is probably alot of overhead in the database even before you do anything. I read some where that you could have 1.000.000 rows but again, it all depends..

You can also link databases together. Limiting yourself to only disk space.

vertical divider between two columns in bootstrap

If you want a vertical divider between 2 columns, all you need is add

class="col-6 border-left" 

to one of your column div-s

BUT

In the world of responsive design, you may need to make it disappear sometimes.

The solution is disappearing <hr> + disappearing <div> + margin-left: -1px;

<div class="container">
  <div class="row">
    <div class="col-md-7">
      1 of 2
    </div>
    <div class="border-left d-sm-none d-md-block" style="width: 0px;"></div>
    <div class="col-md-5" style="margin-left: -1px;">
    <hr class="d-sm-block d-md-none">
      2 of 2
    </div>
  </div>
</div>

https://jsfiddle.net/8z1pag7s/

tested on Bootstrap 4.1

Python def function: How do you specify the end of the function?

In Python whitespace is significant. The function ends when the indentation becomes smaller (less).

def f():
    pass # first line
    pass # second line
pass # <-- less indentation, not part of function f.

Note that one-line functions can be written without indentation, on one line:

def f(): pass

And, then there is the use of semi-colons, but this is not recommended:

def f(): pass; pass

The three forms above show how the end of a function is defined syntactically. As for the semantics, in Python there are three ways to exit a function:

  • Using the return statement. This works the same as in any other imperative programming language you may know.

  • Using the yield statement. This means that the function is a generator. Explaining its semantics is beyond the scope of this answer. Have a look at Can somebody explain me the python yield statement?

  • By simply executing the last statement. If there are no more statements and the last statement is not a return statement, then the function exists as if the last statement were return None. That is to say, without an explicit return statement a function returns None. This function returns None:

    def f():
        pass
    

    And so does this one:

    def f():
        42
    

What is the purpose of flush() in Java streams?

From the docs of the flush method:

Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance.

Pass a data.frame column name to a function

Personally I think that passing the column as a string is pretty ugly. I like to do something like:

get.max <- function(column,data=NULL){
    column<-eval(substitute(column),data, parent.frame())
    max(column)
}

which will yield:

> get.max(mpg,mtcars)
[1] 33.9
> get.max(c(1,2,3,4,5))
[1] 5

Notice how the specification of a data.frame is optional. you can even work with functions of your columns:

> get.max(1/mpg,mtcars)
[1] 0.09615385

LoDash: Get an array of values from an array of object properties

_x000D_
_x000D_
const users = [{
      id: 12,
      name: 'Adam'
   },{
      id: 14,
      name: 'Bob'
   },{
      id: 16,
      name: 'Charlie'
   },{
      id: 18,
      name: 'David'
   }
]
const userIds = _.values(users);
console.log(userIds); //[12, 14, 16, 18]
_x000D_
_x000D_
_x000D_

SQL Server remove milliseconds from datetime

May be this will help.. SELECT [Datetime] = CAST('20120228' AS smalldatetime)

o/p: 2012-02-28 00:00:00

Is there a Java API that can create rich Word documents?

I've used Aspose.Words to do mail merge in .NET. I believe that they also have a Java version.

How to include JavaScript file or library in Chrome console?

If you're just starting out learning javascript & don't want to spend time creating an entire webpage just for embedding test scripts, just open Dev Tools in a new tab in Chrome Browser, and click on Console.

Then type out some test scripts: eg.

console.log('Aha!') 

Then press Enter after every line (to submit for execution by Chrome)

or load your own "external script file":

document.createElement('script').src = 'http://example.com/file.js';

Then call your functions:

console.log(file.function('?????'))

Tested in Google Chrome 85.0.4183.121

Select value from list of tuples where condition

If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10]

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10]

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

How to create composite primary key in SQL Server 2008

I know I'm late to this party, but for an existing table, try:

ALTER table TABLE_NAME
ADD CONSTRAINT [name of your PK, e.g. PK_TableName] PRIMARY KEY CLUSTERED (column1, column2, etc.)

What is a good game engine that uses Lua?

World of Warcraft's engine seems all right, and it uses Lua. :)

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I know this thread is old, but still answering it so that no-one else should spend sleepless nights.

I was refactoring an old project, whose layout files all contained hardcoded attributes such as android:maxLength = 500. So I decided to register it in my res/dimen file as <dimen name="max_length">500</dimen>.

Finished refactoring almost 30 layout files with my res-value. Guess what? the next time I ran my project it started throwing the same InflateException.

As a solution, needed to redo my all changes and keep all-those values as same as before.

TLDR;

step 1: All running good.

step 2: To boost my maintenance I replaced android:maxLength = 500 with <dimen name="max_length">500</dimen> and android:maxLength = @dimen/max_length , that's where it all went wrong(crashing with InflateException).

step 3: All running bad

step 4: Re-do all my work by again replacing android:maxLength = @dimen/max_length with android:maxLength = 500.Everything got fixed.

step 5: All running good.

Model backing a DB Context has changed; Consider Code First Migrations

Just go to Package Manage Console, type the following:

Enable-Migrations

*If the error like this appears "Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration."

Do this >>> Add-Migration

*Visual studio will ask for a name, kindly input the name you want.

Update-Database

Convert String to Type in C#

If you really want to get the type by name you may use the following:

System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");

Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.

How to convert wstring into string?

#include <boost/locale.hpp>
namespace lcv = boost::locale::conv;

inline std::wstring fromUTF8(const std::string& s)
{ return lcv::utf_to_utf<wchar_t>(s); }

inline std::string toUTF8(const std::wstring& ws)
{ return lcv::utf_to_utf<char>(ws); }

How to margin the body of the page (html)?

I hope this will be helpful.. If I understood the problem

html{
     background-color:green;
}

body {
    position:relative; 
    left:200px;    
    background-color:red;
}
div{
    position:relative;  
    left:100px;
    width:100px;
    height:100px;
    background-color:blue;
}

http://jsfiddle.net/6M6ZQ/

File count from a folder

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directry and sub directries

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length; // Will Retrieve count of all files in directry but not sub directries

int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directry and sub directries

Convert a PHP object to an associative array

You can also create a function in PHP to convert an object array:

function object_to_array($object) {
    return (array) $object;
}

How to set label size in Bootstrap

In Bootstrap 3 they do not have separate classes for different styles of labels.

http://getbootstrap.com/components/

However, you can customize bootstrap classes that way. In your css file

.lb-sm {
  font-size: 12px;
}

.lb-md {
  font-size: 16px;
}

.lb-lg {
  font-size: 20px;
}

Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label

_x000D_
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
_x000D_
_x000D_

They might add size classes for labels in future Bootstrap versions.

Command to find information about CPUs on a UNIX machine

Try psrinfo to find the processor type and the number of physical processors installed on the system.

How to add a "sleep" or "wait" to my Lua Script?

If you have luasocket installed:

local socket = require 'socket'
socket.sleep(0.2)

Xml serialization - Hide null values

You can create a function with the pattern ShouldSerialize{PropertyName} which tells the XmlSerializer if it should serialize the member or not.

For example, if your class property is called MyNullableInt you could have

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

Here is a full sample

public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}

Serialized with the following code

Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);

Results in the followng XML - Notice there is no Age

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

Multipart File Upload Using Spring Rest Template + Spring Web MVC

More based on the feeling, but this is the error you would get if you missed to declare a bean in the context configuration, so try adding

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10000000"/>
</bean>

Magento - How to add/remove links on my account navigation?

Open navigation.phtml

app/design/frontend/yourtheme/default/template/customer/account/navigation.phtml

replace

<?php $_links = $this->getLinks(); ?>

with unset link which you want to remove

<?php 
$_count = count($_links);
unset($_links['account']); // Account Information     
unset($_links['account_edit']); // Account Information  
unset($_links['address_book']); // Address Book
unset($_links['orders']); // My Orders
unset($_links['billing_agreements']); // Billing Agreements
unset($_links['recurring_profiles']); // Recurring Profiles
unset($_links['reviews']);  // My Product Reviews
unset($_links['wishlist']); // My Wishlist
unset($_links['OAuth Customer Tokens']); // My Applications
unset($_links['newsletter']); // Newsletter Subscriptions
unset($_links['downloadable_products']); // My Downloadable Products
unset($_links['tags']); // My Tags
unset($_links['invitations']); // My Invitations
unset($_links['enterprise_customerbalance']); // Store Credit
unset($_links['enterprise_reward']); // Reward Points
unset($_links['giftregistry']); // Gift Registry
unset($_links['enterprise_giftcardaccount']); // Gift Card Link
?>

jQuery Upload Progress and AJAX file upload

Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.

This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html

(It also includes the drag/drop interface but that's easily ignored.)

Basically what it comes down to is this:

<input id="files" type="file" />

<script>
document.getElementById('files').addEventListener('change', function(e) {
    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    (xhr.upload || xhr).addEventListener('progress', function(e) {
        var done = e.position || e.loaded
        var total = e.totalSize || e.total;
        console.log('xhr progress: ' + Math.round(done/total*100) + '%');
    });
    xhr.addEventListener('load', function(e) {
        console.log('xhr upload complete', e, this.responseText);
    });
    xhr.open('post', '/URL-HERE', true);
    xhr.send(file);
});
</script>

(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)

So basically what it comes down to is this =)

xhr.send(file);

Where file is typeof Blob: http://www.w3.org/TR/FileAPI/

Another (better IMO) way is to use FormData. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.

var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);

FormData makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).

All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.

This is how I handled the request (1 image per request) in PHP:

if ( isset($_FILES['file']) ) {
    $filename = basename($_FILES['file']['name']);
    $error = true;

    // Only upload if on my home win dev machine
    if ( isset($_SERVER['WINDIR']) ) {
        $path = 'uploads/'.$filename;
        $error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
    }

    $rsp = array(
        'error' => $error, // Used in JS
        'filename' => $filename,
        'filepath' => '/tests/uploads/' . $filename, // Web accessible
    );
    echo json_encode($rsp);
    exit;
}

downloading all the files in a directory with cURL

You can use script like this for mac:

for f in $(curl -s -l -u user:pass ftp://your_ftp_server_ip/folder/) 
 do curl -O -u user:pass ftp://your_ftp_server_ip/folder/$f 
done

Split a String into an array in Swift?

Swift 4, Xcode 10 and iOS 12 Update 100% working

let fullName = "First Last"    
let fullNameArr = fullName.components(separatedBy: " ")
let firstName = fullNameArr[0] //First
let lastName = fullNameArr[1] //Last

See the Apple's documentation here for further information.

Highlight the difference between two strings in PHP

If you want a robust library, Text_Diff (a PEAR package) looks to be pretty good. It has some pretty cool features.

Maven compile with multiple src directories

This worked for with maven 3.5.4 and now Intellij Idea see this code as source:

<plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-compiler-plugin</artifactId>
     <version>3.3</version>
     <configuration>
         <generatedSourcesDirectory>src/main/generated</generatedSourcesDirectory>                    
     </configuration>
</plugin>

NuGet: 'X' already has a dependency defined for 'Y'

I faced this error on outdated version of Visual Studio 2010. Due to project configuration I was not able to update this version to newer. Therefore, update of NuGet advised above did not fix things for me.

Root reason for the error in this and similar situations is in dependencies of the package you try to install, which are not compatible with .NET version available in your project.

Universal solution is not obligatory update of Visual Studio or .NET but in installation of older NuGet versions of the same package compatible with your system.

It is not possible to tell for sure, which of earlier versions will work. In my case, this command installed the package without any NuGet updates.

Install-Package X -Version [compatible version number]

Java: How to set Precision for double value?

To set precision for double values DecimalFormat is good technique. To use this class import java.text.DecimalFormat and create object of it for example

double no=12.786;
DecimalFormat dec = new DecimalFormat("#0.00");
System.out.println(dec.format(no));

So it will print two digits after decimal point here it will print 12.79

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

The sessions parameter is derived from the processes parameter and changes accordingly when you change the number of max processes. See the Oracle docs for further info.

To get only the info about the sessions:

    select current_utilization, limit_value 
    from v$resource_limit 
    where resource_name='sessions';
CURRENT_UTILIZATION LIMIT_VALUE
------------------- -----------
                110         792

Try this to show info about both:

    select resource_name, current_utilization, max_utilization, limit_value 
    from v$resource_limit 
    where resource_name in ('sessions', 'processes');
RESOURCE_NAME CURRENT_UTILIZATION MAX_UTILIZATION LIMIT_VALUE
------------- ------------------- --------------- -----------
processes                      96             309         500
sessions                      104             323         792

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

You have included a dependency on the SLF4J API, which is what you use in your application for logging, but you must also include an implementation that does the real logging work.

For example to log through Log4J you would add this dependency:

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.5.2</version>
    </dependency>

The recommended implementation would be logback-classic, which is the successor of Log4j, made by the same guys that made SLF4J and Log4J:

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>0.9.24</version>
</dependency>

Note: The versions may be incorrect.

Shortest way to print current year in a website

TJ's answer is excellent but I ran into one scenario where my HTML was already rendered and the document.write script would overwrite all of the page contents with just the date year.

For this scenario, you can append a text node to the existing element using the following code:

<div>
    &copy;
    <span id="copyright">
        <script>document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))</script>
    </span>
    Company Name
</div>

jquery save json data object in cookie

use JSON.stringify(userData) to coverty json object to string.

var dataStore = $.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));

and for getting back from cookie use JSON.parse()

var data=JSON.parse($.cookie("basket-data"))

How to redirect all HTTP requests to HTTPS

This is the html redirect approach it works but not the best.

 <meta http-equiv="Refresh" content="0;URL=https://www.example.com" />

PHP approach

<?php
function redirectTohttps() {
    if ($_SERVER['HTTPS']!="on") {
        $redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        header("Location:$redirect"); 
    } 
}
?>

.htaccess approch

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

copied from: www.letuslook.org

Matplotlib connect scatterplot points with line - Python

In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:

plt.plot(x,y,zorder=1) 
plt.scatter(x,y,zorder=2)

plots the scatter symbols on top of the line, while

plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)

plots the line over the scatter symbols.

See, e.g., the zorder demo

Using column alias in WHERE clause of MySQL query produces an error

Maybe my answer is too late but this can help others.

You can enclose it with another select statement and use where clause to it.

SELECT * FROM (Select col1, col2,...) as t WHERE t.calcAlias > 0

calcAlias is the alias column that was calculated.

In Chrome 55, prevent showing Download button for HTML 5 video

This can hide download button on Chrome when HTML5 Audio is used.

_x000D_
_x000D_
 #aPlayer > audio { width: 100% }_x000D_
/* Chrome 29+ */_x000D_
@media screen and (-webkit-min-device-pixel-ratio:0)_x000D_
  and (min-resolution:.001dpcm) {_x000D_
     /* HIDE DOWNLOAD AUDIO BUTTON */_x000D_
     #aPlayer {_x000D_
           overflow: hidden;width: 390px; _x000D_
    }_x000D_
_x000D_
    #aPlayer > audio { _x000D_
      width: 420px; _x000D_
    }_x000D_
}_x000D_
_x000D_
/* Chrome 22-28 */_x000D_
@media screen and(-webkit-min-device-pixel-ratio:0) {_x000D_
    _x000D_
      #aPlayer {_x000D_
           overflow: hidden;width: 390px; _x000D_
        }_x000D_
_x000D_
    #aPlayer > audio { width: 420px; }_x000D_
}
_x000D_
<div id="aPlayer">_x000D_
 <audio autoplay="autoplay" controls="controls">_x000D_
  <source src="http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2012.mp3" type="audio/mpeg" />_x000D_
 </audio>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Click here to see the screenshot

Fastest way to copy a file in Node.js

I was not able to get the createReadStream/createWriteStream method working for some reason, but using the fs-extra npm module it worked right away. I am not sure of the performance difference though.

npm install --save fs-extra

var fs = require('fs-extra');

fs.copySync(path.resolve(__dirname, './init/xxx.json'), 'xxx.json');

How can I check if a var is a string in JavaScript?

You were close:

if (typeof a_string === 'string') {
    // this is a string
}

On a related note: the above check won't work if a string is created with new String('hello') as the type will be Object instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.

Custom sort function in ng-repeat

The following link explains filters in Angular extremely well. It shows how it is possible to define custom sort logic within an ng-repeat. http://toddmotto.com/everything-about-custom-filters-in-angular-js

For sorting object with properties, this is the code I have used: (Note that this sort is the standard JavaScript sort method and not specific to angular) Column Name is the name of the property on which sorting is to be performed.

self.myArray.sort(function(itemA, itemB) {
    if (self.sortOrder === "ASC") {
        return itemA[columnName] > itemB[columnName];
    } else {
        return itemA[columnName] < itemB[columnName];
    }
});

Spring Boot access static resources missing scr/main/resources

Just use Spring type ClassPathResource.

File file = new ClassPathResource("countries.xml").getFile();

As long as this file is somewhere on classpath Spring will find it. This can be src/main/resources during development and testing. In production, it can be current running directory.

EDIT: This approach doesn't work if file is in fat JAR. In such case you need to use:

InputStream is = new ClassPathResource("countries.xml").getInputStream();

Generating Fibonacci Sequence

    // using recursive approach and in one line
    const fib = x => (x <= 1)? x : fib (x - 1) + fib(x -2);
    fib(15); // 610

    // display the 15 first 
    Array.from({ length: 15 }, (v, i) => fib(i)); 
    // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
    
    

    // using memoization approach
    function fibonacci(num, memo) {
      memo = memo || {};
      if (memo[num]) return memo[num];
      if (num === 0) return 0;
      if (num === 1) return 1;
      return memo[num] = fibonacci(num - 1, memo) + fibonacci(num - 2, memo);
    }
    fibonacci(15); // 610

    // display the 15 first 
    Array.from({ length: 15 }, (v, i) => fibonacci(i));
    // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

Is there a template engine for Node.js?

Check out the Node js modules wiki page. They have listed all the templating engines supporting node.js.

Loading another html page from javascript

You can use the following code :

<!DOCTYPE html>
<html>
    <body onLoad="triggerJS();">

    <script>
        function triggerJS(){
        location.replace("http://www.google.com");
        /*
        location.assign("New_WebSite_Url");
        //Use assign() instead of replace if you want to have the first page in the history (i.e if you want the user to be able to navigate back when New_WebSite_Url is loaded)
        */
        }
    </script>

    </body>
</html>

Will using 'var' affect performance?

For the following method:

   private static void StringVsVarILOutput()
    {
        var string1 = new String(new char[9]);

        string string2 = new String(new char[9]);
    }

The IL Output is this:

        {
          .method private hidebysig static void  StringVsVarILOutput() cil managed
          // Code size       28 (0x1c)
          .maxstack  2
          .locals init ([0] string string1,
                   [1] string string2)
          IL_0000:  nop
          IL_0001:  ldc.i4.s   9
          IL_0003:  newarr     [mscorlib]System.Char
          IL_0008:  newobj     instance void [mscorlib]System.String::.ctor(char[])
          IL_000d:  stloc.0
          IL_000e:  ldc.i4.s   9
          IL_0010:  newarr     [mscorlib]System.Char
          IL_0015:  newobj     instance void [mscorlib]System.String::.ctor(char[])
          IL_001a:  stloc.1
          IL_001b:  ret
        } // end of method Program::StringVsVarILOutput

How do I update pip itself from inside my virtual environment?

To get this to work for me I had to drill down in the Python directory using the Python command prompt (on WIN10 from VS CODE). In my case it was in my "AppData\Local\Programs\Python\python35-32" directory. From there now I ran the command...

python -m pip install --upgrade pip

This worked and I'm good to go.

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

I am not an expert in the JS compiling business, but it makes sense to say, that v8 makes use from the const flag

Normally a after declaring and changing a bunch of variables, the memory gets fragmented, and v8 is stopping to execute, makes a pause some time of a few seconds, to make gc, or garbage collection.

if a variable is declared with const v8 can be confident to put it in a tight fixed size container between other const variables, since it will never change. It can also save the proper operations for that datatypes since the type will not change.

postgresql - sql - count of `true` values

SELECT count(*)         -- or count(myCol)
FROM   <table name>     -- replace <table name> with your table
WHERE  myCol = true;

Here's a way with Windowing Function:

SELECT DISTINCT *, count(*) over(partition by myCol)
FROM   <table name>;

-- Outputs:
-- --------------
-- myCol | count
-- ------+-------
--  f    |  2
--  t    |  3
--       |  1

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

You can register a class for your UITableViewCell like this:

With Swift 3+:

self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

With Swift 2.2:

self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

Make sure same identifier "cell" is also copied at your storyboard's UITableViewCell.

"self" is for getting the class use the class name followed by .self.

Javascript - Regex to validate date format

You could use a character class ([./-]) so that the seperators can be any of the defined characters

var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/

Or better still, match the character class for the first seperator, then capture that as a group ([./-]) and use a reference to the captured group \1 to match the second seperator, which will ensure that both seperators are the same:

var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/

"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches

How to play videos in android from assets folder or raw folder?

String UrlPath="android.resource://"+getPackageName()+"/"+R.raw.ur file name;
videocontainer.setVideoURI(Uri.parse(UrlPath));
videocontainer.start();

where videocontainer of type videoview.

How to install Android Studio on Ubuntu?

The easiest method to install Android Studio (or any other developer tool) on Ubuntu is to use the snap package from Ubuntu Software store. No need to download Android Studio as zip, try to manually install it, add PPAs or fiddle with Java installation. The snap package bundles the latest Android Studio along with OpenJDK and all the necessary dependencies.

Step 1: Install Android Studio

Search "android studio" in Ubuntu Software, select the first entry that shows up and install it:

Search Android Studio on Ubuntu Software Android Studio on Ubuntu Software

Or if you prefer the command line way, run this in Terminal:

sudo snap install --classic android-studio

Step 2: Install Android SDK

Open the newly installed Android Studio from dashboard:

Android Studio app on Dash

Don't need to import anything if this is the first time you're installing it:

Import Dialog

The Setup Wizard'll guide you through installation:

Android Studio Setup Wizard

Select Standard install to get the latest SDK and Custom in-case you wanna change the SDK version or its install location. From here on, it's pretty straightforward, just click next-next and you'll have the SDK downloaded and installed.

Select Standard or Custom installation

Step 3: Setting PATHs (Optional)

This step might be useful if you want Android SDK's developer tool commands like adb, fastboot, aapt, etc available in Terminal. Might be needed by 3rd party dev platforms like React Native, Ionic, Cordova, etc and other tools too. For setting PATHs, edit your ~/.profile file:

gedit ~/.profile

and then add the following lines to it:

# Android SDK Tools PATH
export ANDROID_HOME=${HOME}/Android/Sdk
export PATH="${ANDROID_HOME}/tools:${PATH}"
export PATH="${ANDROID_HOME}/emulator:${PATH}"
export PATH="${ANDROID_HOME}/platform-tools:${PATH}"

If you changed SDK location at the end of Step 2, don't forget to change the line export ANDROID_HOME=${HOME}/Android/Sdk accordingly. Do a restart (or just logout and then log back in) for the PATHs to take effect.


Tested on Ubuntu 16.04LTS and above. Would work on 14.04LTS too if you install support for snap packages first.


Note: This question is similar to the AskUbuntu question "How to install Android Studio on Ubuntu?" and my answer equally applies. I'm reproducing my answer here to ensure a full complete answer exists rather than just a link.

Entity Framework: There is already an open DataReader associated with this Command

I solved this problem using the following section of code before the second query:

 ...first query
 while (_dbContext.Connection.State != System.Data.ConnectionState.Closed)
 {
     System.Threading.Thread.Sleep(500);
 }
 ...second query

you can change the time of sleep in miliseconds

P.D. Useful when using threads

How to drop all tables from a database with one SQL query?

If you want to use only one SQL query to delete all tables you can use this:

EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

This is a hidden Stored Procedure in sql server, and will be executed for each table in the database you're connected.

Note: You may need to execute the query a few times to delete all tables due to dependencies.

Note2: To avoid the first note, before running the query, first check if there foreign keys relations to any table. If there are then just disable foreign key constraint by running the query bellow:

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

What version of Java is running in Eclipse?

Under the help menu, there should be a menu item labeled "About Eclipse" I can't say with absolute precision because I'm using STS which is the same thing but my label is different.

In the dialog box that opens after you click the relevant about menu item there should be an installation details button in the lower left hand corner.

The version of Java that you're running Eclipse against ought to be in "System properties:" under the "Configuration" tab.

IPhone/IPad: How to get screen width programmatically?

As of iOS 9.0 there's no way to get the orientation reliably. This is the code I used for an app I design for only portrait mode, so if the app is opened in landscape mode it will still be accurate:

screenHeight = [[UIScreen mainScreen] bounds].size.height;
screenWidth = [[UIScreen mainScreen] bounds].size.width;
if (screenWidth > screenHeight) {
    float tempHeight = screenWidth;
    screenWidth = screenHeight;
    screenHeight = tempHeight;
}

Using onBackPressed() in Android Fragments

This works for me :D

    @Override
    public void onResume() {
    super.onResume();

    if(getView() == null){
        return;
    }

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                // handle back button's click listener
                return true;
            }
            return false;
        }
    });}

Merge development branch with master

I generally like to merge master into the development first so that if there are any conflicts, I can resolve in the development branch itself and my master remains clean.

(on branch development)$ git merge master
(resolve any merge conflicts if there are any)
git checkout master
git merge development (there won't be any conflicts now)

There isn't much of a difference in the two approaches, but I have noticed sometimes that I don't want to merge the branch into master yet, after merging them, or that there is still more work to be done before these can be merged, so I tend to leave master untouched until final stuff.

EDIT: From comments

If you want to keep track of who did the merge and when, you can use --no-ff flag while merging to do so. This is generally useful only when merging development into the master (last step), because you might need to merge master into development (first step) multiple times in your workflow, and creating a commit node for these might not be very useful.

git merge --no-ff development

Bootstrap 3 collapsed menu doesn't close on click

Just to share this from solutions on GitHub, this was the popular answer:

https://github.com/twbs/bootstrap/issues/9013#issuecomment-39698247

$(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a') ) {
        $(this).collapse('hide');
    }
});

This is wired to the document, so you don't have to do it on ready() (you can dynamically append links to your menu and it will still work), and it only gets called if the menu is already expanded. Some people have reported weird flashing where the menu opens and then immediately closes with other code that did not verify that the menu had the "in" class.

[UPDATE 2014-11-04] apparently when using sub-menus, the above can cause problems, so the above got modified to:

$(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a:not(".dropdown-toggle")') ) {
        $(this).collapse('hide');
    }
});

Setting POST variable without using form

You can do it using jQuery. Example:

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<script>
    $.ajax({
        url : "next.php",
        type: "POST",
        data : "name=Denniss",
        success: function(data)
        {
            //data - response from server
            $('#response_div').html(data);
        }
    });
</script>

Add support library to Android Studio project

I no longer work on Android project for a while. Although the below provides some clue to how an android studio project can be configured, but I can't guarantee it works flawlessly.

In principle, IntelliJ respects the build file and will try to use it to configure the IDE project. It's not true in the other way round, IDE changes normally will not affect the build file.

Since most Android projects are built by Gradle, it's always a good idea to understand this tool.

I'd suggest referring to @skyfishjy's answer, as it seems to be more updated than this one.


The below is not updated

Although android studio is based on IntelliJ IDEA, at the same time it relies on gradle to build your apk. As of 0.2.3, these two doesn't play nicely in term of configuring from GUI. As a result, in addition to use the GUI to setup dependencies, it will also require you to edit the build.gradle file manually.

Assuming you have a Test Project > Test structure. The build.gradle file you're looking for is located at TestProject/Test/build.gradle

Look for the dependencies section, and make sure you have

compile 'com.android.support:support-v4:13.0.+'

Below is an example.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.android.support:support-v4:13.0.+'
}

android {
    compileSdkVersion 18
    buildToolsVersion "18.0.1"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

You can also add 3rd party libraries from the maven repository

compile group: 'com.google.code.gson', name: 'gson', version: '2.2.4'

The above snippet will add gson 2.2.4 for you.

In my experiment, it seems that adding the gradle will also setup correct IntelliJ dependencies for you.

How to get week numbers from dates?

I think the problem is that the week calculation somehow uses the first day of the year. I don't understand the internal mechanics, but you can see what I mean with this example:

library(data.table)

dd <- seq(as.IDate("2013-12-20"), as.IDate("2014-01-20"), 1)
# dd <- seq(as.IDate("2013-12-01"), as.IDate("2014-03-31"), 1)

dt <- data.table(i = 1:length(dd),
                 day = dd,
                 weekday = weekdays(dd),
                 day_rounded = round(dd, "weeks"))
## Now let's add the weekdays for the "rounded" date
dt[ , weekday_rounded := weekdays(day_rounded)]
## This seems to make internal sense with the "week" calculation
dt[ , weeknumber := week(day)]
dt 

    i        day   weekday day_rounded weekday_rounded weeknumber
1:  1 2013-12-20    Friday  2013-12-17         Tuesday         51
2:  2 2013-12-21  Saturday  2013-12-17         Tuesday         51
3:  3 2013-12-22    Sunday  2013-12-17         Tuesday         51
4:  4 2013-12-23    Monday  2013-12-24         Tuesday         52
5:  5 2013-12-24   Tuesday  2013-12-24         Tuesday         52
6:  6 2013-12-25 Wednesday  2013-12-24         Tuesday         52
7:  7 2013-12-26  Thursday  2013-12-24         Tuesday         52
8:  8 2013-12-27    Friday  2013-12-24         Tuesday         52
9:  9 2013-12-28  Saturday  2013-12-24         Tuesday         52
10: 10 2013-12-29    Sunday  2013-12-24         Tuesday         52
11: 11 2013-12-30    Monday  2013-12-31         Tuesday         53
12: 12 2013-12-31   Tuesday  2013-12-31         Tuesday         53
13: 13 2014-01-01 Wednesday  2014-01-01       Wednesday          1
14: 14 2014-01-02  Thursday  2014-01-01       Wednesday          1
15: 15 2014-01-03    Friday  2014-01-01       Wednesday          1
16: 16 2014-01-04  Saturday  2014-01-01       Wednesday          1
17: 17 2014-01-05    Sunday  2014-01-01       Wednesday          1
18: 18 2014-01-06    Monday  2014-01-01       Wednesday          1
19: 19 2014-01-07   Tuesday  2014-01-08       Wednesday          2
20: 20 2014-01-08 Wednesday  2014-01-08       Wednesday          2
21: 21 2014-01-09  Thursday  2014-01-08       Wednesday          2
22: 22 2014-01-10    Friday  2014-01-08       Wednesday          2
23: 23 2014-01-11  Saturday  2014-01-08       Wednesday          2
24: 24 2014-01-12    Sunday  2014-01-08       Wednesday          2
25: 25 2014-01-13    Monday  2014-01-08       Wednesday          2
26: 26 2014-01-14   Tuesday  2014-01-15       Wednesday          3
27: 27 2014-01-15 Wednesday  2014-01-15       Wednesday          3
28: 28 2014-01-16  Thursday  2014-01-15       Wednesday          3
29: 29 2014-01-17    Friday  2014-01-15       Wednesday          3
30: 30 2014-01-18  Saturday  2014-01-15       Wednesday          3
31: 31 2014-01-19    Sunday  2014-01-15       Wednesday          3
32: 32 2014-01-20    Monday  2014-01-15       Wednesday          3
     i        day   weekday day_rounded weekday_rounded weeknumber

My workaround is this function: https://github.com/geneorama/geneorama/blob/master/R/round_weeks.R

round_weeks <- function(x){
    require(data.table)
    dt <- data.table(i = 1:length(x),
                     day = x,
                     weekday = weekdays(x))
    offset <- data.table(weekday = c('Sunday', 'Monday', 'Tuesday', 'Wednesday', 
                                     'Thursday', 'Friday', 'Saturday'),
                         offset = -(0:6))
    dt <- merge(dt, offset, by="weekday")
    dt[ , day_adj := day + offset]
    setkey(dt, i)
    return(dt[ , day_adj])
}

Of course, you can easily change the offset to make Monday first or whatever. The best way to do this would be to add an offset to the offset... but I haven't done that yet.

I provided a link to my simple geneorama package, but please don't rely on it too much because it's likely to change and not very documented.

How to add content to html body using JS?

I Just came across to a similar to this question solution with included some performance statistics.

It seems that example below is faster:

_x000D_
_x000D_
document.getElementById('container').insertAdjacentHTML('beforeend', '<div id="idChild"> content html </div>');
_x000D_
_x000D_
_x000D_

InnerHTML vs jQuery 1 vs appendChild vs innerAdjecentHTML.

enter image description here

Reference: 1) Performance stats 2) API - insertAdjacentHTML

I hope this will help.

How to install Android SDK on Ubuntu?

sudo add-apt-repository -y ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer oracle-java7-set-default
wget https://dl.google.com/dl/android/studio/ide-zips/2.2.0.12/android-studio-ide-145.3276617-linux.zip
unzip android-studio-ide-145.3276617-linux.zip
cd android-studio/bin
./studio.sh

Try-catch speeding up my code?

9 years later and the bug is still there! You can see it easily with:

   static void Main( string[] args )
    {
      int hundredMillion = 1000000;
      DateTime start = DateTime.Now;
      double sqrt;
      for (int i=0; i < hundredMillion; i++)
      {
        sqrt = Math.Sqrt( DateTime.Now.ToOADate() );
      }
      DateTime end = DateTime.Now;

      double sqrtMs = (end - start).TotalMilliseconds;

      Console.WriteLine( "Elapsed milliseconds: " + sqrtMs );

      DateTime start2 = DateTime.Now;

      double sqrt2;
      for (int i = 0; i < hundredMillion; i++)
      {
        try
        {
          sqrt2 = Math.Sqrt( DateTime.Now.ToOADate() );
        }
        catch (Exception e)
        {
          int br = 0;
        }
      }
      DateTime end2 = DateTime.Now;

      double sqrtMsTryCatch = (end2 - start2).TotalMilliseconds;

      Console.WriteLine( "Elapsed milliseconds: " + sqrtMsTryCatch );

      Console.WriteLine( "ratio is " + sqrtMsTryCatch / sqrtMs );

      Console.ReadLine();
    }

The ratio is less than one on my machine, running the latest version of MSVS 2019, .NET 4.6.1

Check if passed argument is file or directory in Bash

This should work:

#!/bin/bash

echo "Enter your Path:"
read a

if [[ -d $a ]]; then 
    echo "$a is a Dir" 
elif [[ -f $a ]]; then 
    echo "$a is the File" 
else 
    echo "Invalid path" 
fi

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

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

Simple is cheap in web development. I recommend using empty string when removing a particular style

$(element).style.attr = '  ';

What is the canonical way to check for errors using the CUDA runtime API?

The C++-canonical way: Don't check for errors...use the C++ bindings which throw exceptions.

I used to be irked by this problem; and I used to have a macro-cum-wrapper-function solution just like in Talonmies and Jared's answers, but, honestly? It makes using the CUDA Runtime API even more ugly and C-like.

So I've approached this in a different and more fundamental way. For a sample of the result, here's part of the CUDA vectorAdd sample - with complete error checking of every runtime API call:

// (... prepare host-side buffers here ...)

auto current_device = cuda::device::current::get();
auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements);

cuda::memory::copy(d_A.get(), h_A.get(), size);
cuda::memory::copy(d_B.get(), h_B.get(), size);

// (... prepare a launch configuration here... )

cuda::launch(vectorAdd, launch_config,
    d_A.get(), d_B.get(), d_C.get(), numElements
);    
cuda::memory::copy(h_C.get(), d_C.get(), size);

// (... verify results here...)

Again - all potential errors are checked , and an exception if an error occurred (caveat: If the kernel caused some error after launch, it will be caught after the attempt to copy the result, not before; to ensure the kernel was successful you would need to check for error between the launch and the copy with a cuda::outstanding_error::ensure_none() command).

The code above uses my

Thin Modern-C++ wrappers for the CUDA Runtime API library (Github)

Note that the exceptions carry both a string explanation and the CUDA runtime API status code after the failing call.

A few links to how CUDA errors are automagically checked with these wrappers:

How to convert / cast long to String?

1.

long date = curDateFld.getDate();
//convert long to string
String str = String.valueOf(date);

//convert string to long
date = Long.valueOf(str);

2.

 //convert long to string just concat long with empty string
 String str = ""+date;
//convert string to long

date = Long.valueOf(str);

CSS selector based on element text?

I know it's not exactly what you are looking for, but maybe it'll help you.

You can try use a jQuery selector :contains(), add a class and then do a normal style for a class.

pg_config executable not found

Just to sum up, I also faced exactly same problem. After reading a lot of stackoverflow posts and online blogs, the final solution which worked for me is this:

1) PostgreSQL(development or any stable version) should be installed before installing psycopg2.

2) The pg_config file (this file normally resides in the bin folder of the PostgreSQL installation folder) PATH had to be explicitly setup before installing psycopg2. In my case, the installation PATH for PostgreSQL is:

/opt/local/lib/postgresql91/

so in order to explicitly set the PATH of pg_config file, I entered following command in my terminal:

PATH=$PATH:/opt/local/lib/postgresql91/bin/

This command ensures that when you try to pip install psycopg2, it would find the PATH to pg_config automatically this time.

I have also posted a full error with trace and its solution on my blog which you may want to refer. Its for Mac OS X but the pg_config PATH problem is generic and applicable to Linux also.

Change Text Color of Selected Option in a Select Box

Try this:

_x000D_
_x000D_
.greenText{ background-color:green; }_x000D_
_x000D_
.blueText{ background-color:blue; }_x000D_
_x000D_
.redText{ background-color:red; }
_x000D_
<select_x000D_
    onchange="this.className=this.options[this.selectedIndex].className"_x000D_
    class="greenText">_x000D_
     <option class="greenText" value="apple" >Apple</option>_x000D_
    <option class="redText"   value="banana" >Banana</option>_x000D_
    <option class="blueText" value="grape" >Grape</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Cannot connect to repo with TortoiseSVN

I faced similar issue while doing svn update.

The approach which worked for me is to rename C:\Users\user\AppData\Roaming\TortoiseSVN folder to TortoiseSVN_bkp folder and then tried svn update again. This time I was able to connect to repository and it got updated.

How can I do width = 100% - 100px in CSS?

Are you using standards mode? This solution depends on it I think.

If you're trying to make 2 columns you could do something like this:

<div id="outer">
    <div id="left">
        sidebar
    </div>
    <div id="main">
        lorem ispsum etc... 
    </div>
</div>

Then use CSS to style it:

div#outer
{
    width:100%;
    height: 500px;
}

div#left
{
    width: 100px;
    height: 100%;
    float:left;
    background: green;
}

div#main
{
   width: auto;
   margin-left: 100px; /* same as div#left width */
   height: 100%;
   background:red;
}

If you don't want 2 columns you can probably remove <div id="left">

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

If you have to use the older client, here is my experience.

We are running a 32bit server so the development machines run the 32bit client. We run the 11.1 install, 11.2 gets the error. Once you have installed the 11.2 version you have to manually delete the files Oracle.Web.dll and System.Data.OracleClient.dll from the %windir%\Microsoft.NET\Framework\v2.0.50727, reinstall 11.1, then register the dlls with gacutil.exe.

This fixed the issue with my systems.

Redirecting to a page after submitting form in HTML

What you could do is, a validation of the values, for example:

if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.

_x000D_
_x000D_
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");

// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");

// Form
let contactForm = document.getElementById("form");

// Event listener
contactForm.addEventListener("submit", function (e) {
  let messageName = [];
  let messageAddress = [];
  
    if (fullname.value === "" || fullname.value === null) {
    messageName.push("* This field is required");
  }

  if (address.value === "" || address.value === null) {
    messageAddress.push("* This field is required");
  }

  // Statement to shows the errors
  if (messageName.length || messageAddress.length > 0) {
    e.preventDefault();
    errorElement.innerText = messageName;
    errorElementAddress.innerText = messageAddress;
  }
  
   // if the values length is filled and it's greater than 2 then redirect to this page
    if (
    (fullname.value.length > 2,
    address.value.length > 2)
  ) {
    e.preventDefault();
    window.location.assign("https://www.google.com");
  }

});
_x000D_
.error {
  color: #000;
}

.input-container {
  display: flex;
  flex-direction: column;
  margin: 1rem auto;
}
_x000D_
<html>
  <body>
    <form id="form" method="POST">
    <div class="input-container">
    <label>Full name:</label>
      <input type="text" id="fullname" name="fullname">
      <div class="error" id="name_error"></div>
      </div>
      
      <div class="input-container">
      <label>Address:</label>
      <input type="text" id="address" name="address">
      <div class="error" id="address_error"></div>
      </div>
      <button type="submit" id="submit_button" value="Submit request" >Submit</button>
    </form>
  </body>
</html>
_x000D_
_x000D_
_x000D_

Create an array or List of all dates between two dates

list = list.Where(s => s.startDate >= Input_startDate && s.endDate <= Input_endDate);

 

C# "as" cast vs classic cast

using as will return null if not a valid cast which allows you to do other things besides wrapping the cast in a try/catch. I hate classic cast. I always use as cast if i'm not sure. Plus, exceptions are expensive. Null checks are not.

MySQL duplicate entry error even though there is no duplicate entry

In my case the error was very misleading. The problem was that PHPMyAdmin uses "ALTER TABLE" when you click on the "make unique" button instead of "ALTER IGNORE TABLE", so I had to do it manually, like in:

ALTER TABLE mytbl ADD UNIQUE (columnName);

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

As others pointed out, this message is coming from your shell prompt. The problem is that in a freshly created repository HEAD (.git/HEAD) points to a ref that doesn't exist yet.

% git init test
Initialized empty shared Git repository in /Users/jhelwig/tmp/test/.git/
% cd test
% cat .git/HEAD
ref: refs/heads/master
% ls -l .git/refs/heads
total 0
% git rev-parse HEAD
HEAD
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions

It looks like rev-parse is being used without sufficient error checking before-hand. After the first commit has been created .git/refs/heads looks a bit different and git rev-parse HEAD will no longer fail.

% ls -l .git/refs/heads
total 4
-rw------- 1 jhelwig staff 41 Oct 14 16:07 master
% git rev-parse HEAD
af0f70f8962f8b88eef679a1854991cb0f337f89

In the function that updates the Git information for the rest of my shell prompt (heavily modified version of wunjo prompt theme for ZSH), I have the following to get around this:

zgit_info_update() {
    zgit_info=()

    local gitdir=$(git rev-parse --git-dir 2>/dev/null)
    if [ $? -ne 0 ] || [ -z "$gitdir" ]; then
        return
    fi

    # More code ...
}

C++ Remove new line from multiline string

s.erase(std::remove(s.begin(), s.end(), '\n'), s.end());

jquery if div id has children

if ( $('#myfav').children().length > 0 ) {
     // do something
}

This should work. The children() function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.

document.getElementById('btnid').disabled is not working in firefox and chrome

I've tried all the possibilities. Nothing worked for me except the following. var element = document.querySelectorAll("input[id=btn1]"); element[0].setAttribute("disabled",true);

How to filter multiple values (OR operation) in angularJS

You can also use ngIf if the situation permits:

<div ng-repeat="p in [
 { name: 'Justin' }, 
 { name: 'Jimi' }, 
 { name: 'Bob' }
 ]" ng-if="['Jimi', 'Bob'].indexOf(e.name) > -1">
 {{ p.name }} is cool
</div>

Serializing class instance to JSON

You could use jsonic for to serialize pretty much anything to JSON:

https://github.com/OrrBin/Jsonic

Example:

class TestClass:
def __init__(self):
    self.x = 1
    self.y = 2

instance = TestClass()
s = serialize(instance): # instance s set to: {"x":1, "y":2}
d = deserialize(s) # d is a new class instance of TestClass

pythonic has some nice features like declaring class attributes transient and type safe deserialization.

(A few years late with the answer, but i think it might help others)

Why did my Git repo enter a detached HEAD state?

Any checkout of a commit that is not the name of one of your branches will get you a detached HEAD. A SHA1 which represents the tip of a branch still gives a detached HEAD. Only a checkout of a local branch name avoids that mode.

See committing with a detached HEAD

When HEAD is detached, commits work like normal, except no named branch gets updated. (You can think of this as an anonymous branch.)

alt text

For example, if you checkout a "remote branch" without tracking it first, you can end up with a detached HEAD.

See git: switch branch without detaching head

Meaning: git checkout origin/main (or origin/master in the old days) would result in:

Note: switching to 'origin/main'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at a1b2c3d My commit message

That is why you should not use git checkout anymore, but the new git switch command.

With git switch, the same attempt to "checkout" (switch to) a remote branch would fail immediately:

git switch origin/main
fatal: a branch is expected, got remote branch 'origin/main'

To add more on git switch:

With Git 2.23 (August 2019), you don't have to use the confusing git checkout command anymore.

git switch can also checkout a branch, and get a detach HEAD, except:

  • it has an explicit --detach option

To check out commit HEAD~3 for temporary inspection or experiment without creating a new branch:

git switch --detach HEAD~3
HEAD is now at 9fc9555312 Merge branch 'cc/shared-index-permbits'
  • it cannot detached by mistake a remote tracking branch

See:

C:\Users\vonc\arepo>git checkout origin/master
Note: switching to 'origin/master'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

Vs. using the new git switch command:

C:\Users\vonc\arepo>git switch origin/master
fatal: a branch is expected, got remote branch 'origin/master'

If you wanted to create a new local branch tracking a remote branch:

git switch <branch> 

If <branch> is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat as equivalent to

git switch -c <branch> --track <remote>/<branch>

No more mistake!
No more unwanted detached HEAD!

if checkbox is checked, do this

I found out a crazy solution for dealing with this issue of checkbox not checked or checked here is my algorithm... create a global variable lets say var check_holder

check_holder has 3 states

  1. undefined state
  2. 0 state
  3. 1 state

If the checkbox is clicked,

$(document).on("click","#check",function(){
    if(typeof(check_holder)=="undefined"){
          //this means that it is the first time and the check is going to be checked
          //do something
          check_holder=1; //indicates that the is checked,it is in checked state
    }
    else if(check_holder==1){
          //do something when the check is going to be unchecked
          check_holder=0; //it means that it is not checked,it is in unchecked state
    }
     else if(check_holder==0){
            //do something when the check is going to be checked
            check_holder=1;//indicates that it is in a checked state
     }
});

The code above can be used in many situation to find out if a checkbox has been checked or not checked. The concept behind it is to save the checkbox states in a variable, ie when it is on,off. i Hope the logic can be used to solve your problem.

How to pass all arguments passed to my bash script to a function of mine?

The $@ variable expands to all command-line parameters separated by spaces. Here is an example.

abc "$@"

When using $@, you should (almost) always put it in double-quotes to avoid misparsing of arguments containing spaces or wildcards (see below). This works for multiple arguments. It is also portable to all POSIX-compliant shells.

It is also worth nothing that $0 (generally the script's name or path) is not in $@.

The Bash Reference Manual Special Parameters Section says that $@ expands to the positional parameters starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is "$@" is equivalent to "$1" "$2" "$3"....

Passing some arguments:

If you want to pass all but the first arguments, you can first use shift to "consume" the first argument and then pass "$@" to pass the remaining arguments to another command. In bash (and zsh and ksh, but not in plain POSIX shells like dash), you can do this without messing with the argument list using a variant of array slicing: "${@:3}" will get you the arguments starting with "$3". "${@:3:4}" will get you up to four arguments starting at "$3" (i.e. "$3" "$4" "$5" "$6"), if that many arguments were passed.

Things you probably don't want to do:

"$*" gives all of the arguments stuck together into a single string (separated by spaces, or whatever the first character of $IFS is). This looses the distinction between spaces within arguments and the spaces between arguments, so is generally a bad idea. Although it might be ok for printing the arguments, e.g. echo "$*", provided you don't care about preserving the space within/between distinction.

Assigning the arguments to a regular variable (as in args="$@") mashes all the arguments together just like "$*" does. If you want to store the arguments in a variable, use an array with args=("$@") (the parentheses make it an array), and then reference them as e.g. "${args[0]}" etc (note that bash array indexes start at 0, so $1 will be in args[0], etc).

Leaving off the double-quotes, with either $@ or $*, will try to split each argument up into separate words (based on whitespace or whatever's in $IFS), and also try to expand anything that looks like a filename wildcard into a list of matching filenames. This can have really weird effects, and should almost always be avoided.

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

How to create enum like type in TypeScript?

Enums in typescript:

Enums are put into the typescript language to define a set of named constants. Using enums can make our life easier. The reason for this is that these constants are often easier to read than the value which the enum represents.

Creating a enum:

enum Direction {
    Up = 1,
    Down,
    Left,
    Right,
}

This example from the typescript docs explains very nicely how enums work. Notice that our first enum value (Up) is initialized with 1. All the following members of the number enum are then auto incremented from this value (i.e. Down = 2, Left = 3, Right = 4). If we didn't initialize the first value with 1 the enum would start at 0 and then auto increment (i.e. Down = 1, Left = 2, Right = 3).

Using an enum:

We can access the values of the enum in the following manner:

Direction.Up;     // first the enum name, then the dot operator followed by the enum value
Direction.Down;

Notice that this way we are much more descriptive in the way we write our code. Enums basically prevent us from using magic numbers (numbers which represent some entity because the programmer has given a meaning to them in a certain context). Magic numbers are bad because of the following reasons:

  1. We need to think harder, we first need to translate the number to an entity before we can reason about our code.
  2. If we review our code after a long while, or other programmers review our code, they don't necessarily know what is meant with these numbers.

Current user in Magento?

Found under "app/code/core/Mage/Page/Block/Html/Header.php":

public function getWelcome()
{
    if (empty($this->_data['welcome'])) {
        if (Mage::app()->isInstalled() && Mage::getSingleton('customer/session')->isLoggedIn()) {
            $this->_data['welcome'] = $this->__('Welcome, %s!', Mage::getSingleton('customer/session')->getCustomer()->getName());
        } else {
            $this->_data['welcome'] = Mage::getStoreConfig('design/header/welcome');
        }
    }

    return $this->_data['welcome'];
}

So it looks like Mage::getSingleton('customer/session')->getCustomer() will get your current logged in customer ;)

To get the currently logged in admin:

Mage::getSingleton('admin/session')->getUser();

Maven project version inheritance - do I have to specify the parent version?

eFox's answer worked for a single project, but not when I was referencing a module from another one (the pom.xml were still stored in my .m2 with the property instead of the version).

However, it works if you combine it with the flatten-maven-plugin, since it generates the poms with the correct version, not the property.

The only option I changed in the plug-in definition is the outputDirectory, it's empty by default, but I prefer to have it in target, which is set in my .gitignore configuration:

<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>flatten-maven-plugin</artifactId>
   <version>1.0.1</version>
   <configuration>
      <updatePomFile>true</updatePomFile>
      <outputDirectory>target</outputDirectory>
   </configuration>
   <executions>
      <execution>
         <id>flatten</id>
         <phase>process-resources</phase>
         <goals>
            <goal>flatten</goal>
         </goals>
      </execution>
   </executions>
</plugin>

The plug-in configuration goes in the parent pom.xml

How do I find the maximum of 2 numbers?

(num1>=num2)*num1+(num2>num1)*num2 will return the maximum of two values.

Select multiple images from android gallery

For selecting multiple image from gallery

i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);

An Ultimate Solution for multiple image upload with camera option also for Android Lollipop to Android 10, SDK 30.

private static final int FILECHOOSER_RESULTCODE   = 1;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mUploadMessages;
private Uri mCapturedImageURI = null;

Add this to OnCreate of MainActivity

mWebView.setWebChromeClient(new WebChromeClient() {

            // openFileChooser for Android 3.0+

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
                mUploadMessage = uploadMsg;
                openImageChooser();
            }

            // For Lollipop 5.0+ Devices

            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                mUploadMessages = filePathCallback;
                openImageChooser();
                return true;
            }

            // openFileChooser for Android < 3.0

            public void openFileChooser(ValueCallback<Uri> uploadMsg){
                openFileChooser(uploadMsg, "");
            }

            //openFileChooser for other Android versions

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooser(uploadMsg, acceptType);
            }

private void openImageChooser() {
    try {
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "FolderName");
        if (!imageStorageDir.exists()) {
            imageStorageDir.mkdirs();
        }
        File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        mCapturedImageURI = Uri.fromFile(file);

        final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);

        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
        Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});

        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

        });

onActivityResult

public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {


        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {

            if (null == mUploadMessage && null == mUploadMessages) {
                return;
            }

            if (null != mUploadMessage) {
                handleUploadMessage(requestCode, resultCode, data);

            } else if (mUploadMessages != null) {
                handleUploadMessages(requestCode, resultCode, data);
            }
        }





    }

    private void handleUploadMessage(final int requestCode, final int resultCode, final Intent data) {
        Uri result = null;
        try {
            if (resultCode != RESULT_OK) {
                result = null;
            } else {
                // retrieve from the private variable if the intent is null

                result = data == null ? mCapturedImageURI : data.getData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;

        // code for all versions except of Lollipop
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

                result = null;

                try {
                    if (resultCode != RESULT_OK) {
                        result = null;
                    } else {
                        // retrieve from the private variable if the intent is null
                        result = data == null ? mCapturedImageURI : data.getData();
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
                }

                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }

        } // end of code for all versions except of Lollipop






    private void handleUploadMessages(final int requestCode, final int resultCode, final Intent data) {
        Uri[] results = null;
        try {
            if (resultCode != RESULT_OK) {
                results = null;
            } else {
                if (data != null) {
                    String dataString = data.getDataString();
                    ClipData clipData = data.getClipData();
                    if (clipData != null) {
                        results = new Uri[clipData.getItemCount()];
                        for (int i = 0; i < clipData.getItemCount(); i++) {
                            ClipData.Item item = clipData.getItemAt(i);
                            results[i] = item.getUri();
                        }
                    }
                    if (dataString != null) {
                        results = new Uri[]{Uri.parse(dataString)};
                    }
                } else {
                    results = new Uri[]{mCapturedImageURI};
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mUploadMessages.onReceiveValue(results);
        mUploadMessages = null;
    }

Determining if an Object is of primitive type

public static boolean isValidType(Class<?> retType)
{
    if (retType.isPrimitive() && retType != void.class) return true;
    if (Number.class.isAssignableFrom(retType)) return true;
    if (AbstractCode.class.isAssignableFrom(retType)) return true;
    if (Boolean.class == retType) return true;
    if (Character.class == retType) return true;
    if (String.class == retType) return true;
    if (Date.class.isAssignableFrom(retType)) return true;
    if (byte[].class.isAssignableFrom(retType)) return true;
    if (Enum.class.isAssignableFrom(retType)) return true;
    return false;
}

index.php not loading by default

This might be helpful to somebody. here is the snippet from httpd.conf (Apache version 2.2 windows)

# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html
    DirectoryIndex index.php
</IfModule>

now this will look for index.html file if not found it will look for index.php.

How to add files/folders to .gitignore in IntelliJ IDEA?

You can create file .gitignore and then Idea will suggest you install plugin

Difference between /res and /assets directories

Use assets like a filesystem to dump any kind of files. And use res to store what it is made for, layouts, images, values.

how to convert string into time format and add two hours

Try this one, I test it, working fine

Date date = null;
String str = "2012/07/25 12:00:00";
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
date = formatter.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, 2);
System.out.println(calendar.getTime());  // Output : Wed Jul 25 14:00:00 IST 2012

If you want to convert in your input type than add this code also

formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
str=formatter.format(calendar.getTime());
System.out.println(str);  // Output : 2012-07-25 14:00:00

How can I run a PHP script in the background after a form is submitted?

On Linux/Unix servers, you can execute a job in the background by using proc_open:

$descriptorspec = array(
   array('pipe', 'r'),               // stdin
   array('file', 'myfile.txt', 'a'), // stdout
   array('pipe', 'w'),               // stderr
);

$proc = proc_open('php email_script.php &', $descriptorspec, $pipes);

The & being the important bit here. The script will continue even if the original script has ended.

How to create a timer using tkinter?

The root.after(ms, func) is the method you need to use. Just call it once before the mainloop starts and reschedule it inside the bound function every time it is called. Here is an example:

from tkinter import *
import time


def update_clock():
    timer_label.config(text=time.strftime('%H:%M:%S',time.localtime()),
                  font='Times 25')  # change the text of the time_label according to the current time
    root.after(100, update_clock)  # reschedule update_clock function to update time_label every 100 ms

root = Tk()  # create the root window
timer_label = Label(root, justify='center')  # create the label for timer
timer_label.pack()  # show the timer_label using pack geometry manager
root.after(0, update_clock)  # schedule update_clock function first call
root.mainloop()  # start the root window mainloop

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

Table variable error: Must declare the scalar variable "@temp"

You could stil use @TEMP if you quote the identifier "@TEMP":

declare @TEMP table (ID int, Name varchar(max));
insert into @temp SELECT 1 AS ID, 'a' Name;

SELECT * FROM @TEMP WHERE "@TEMP".ID  = 1 ;   

db<>fiddle demo

How can I scan barcodes on iOS?

The iPhone 4 camera is more than capabale of doing barcodes. The zebra crossing barcode library has a fork on github zxing-iphone. It's open-source.

Generate list of all possible permutations of a string

You might look at "Efficiently Enumerating the Subsets of a Set", which describes an algorithm to do part of what you want - quickly generate all subsets of N characters from length x to y. It contains an implementation in C.

For each subset, you'd still have to generate all the permutations. For instance if you wanted 3 characters from "abcde", this algorithm would give you "abc","abd", "abe"... but you'd have to permute each one to get "acb", "bac", "bca", etc.

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Requested registry access is not allowed

As a temporary fix, users can right click the utility and select "Run as administrator."

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

SVG rounded corner

Just to simplify implementing answer of @hmak.me, here's a commented piece of React code to generate rounded rectangles.

const Rect = ({width, height, round, strokeWidth}) => {
    // overhang over given width and height that we get due to stroke width
    const s = strokeWidth / 2;

    // how many pixels do we need to cut from vertical and horizontal parts
    // due to rounded corners and stroke width
    const over = 2 * round + strokeWidth;

    // lengths of straight lines
    const w = width - over;
    const h = height - over;

    // beware that extra spaces will not be minified
    // they are added for clarity
    const d = `
        M${round + s},${s}
        h${w}
        a${round},${round} 0 0 1 ${round},${round}
        v${h}
        a${round},${round} 0 0 1 -${round},${round}
        h-${w}
        a${round},${round} 0 0 1 -${round},-${round}
        v-${h}
        a${round},${round} 0 0 1 ${round},-${round}
        z
    `;
    return (
        <svg width={width} height={height}>
            <path d={d} fill="none" stroke="black" strokeWidth={strokeWidth} />
        </svg>
    );
};

ReactDOM.render(
    <Rect width={64} height={32} strokeWidth={2} round={4} />,
    document.querySelector('#app'),
);

Jsfiddle link.

How to print the number of characters in each line of a text file

I've tried the other answers listed above, but they are very far from decent solutions when dealing with large files -- especially once a single line's size occupies more than ~1/4 of available RAM.

Both bash and awk slurp the entire line, even though for this problem it's not needed. Bash will error out once a line is too long, even if you have enough memory.

I've implemented an extremely simple, fairly unoptimized python script that when tested with large files (~4 GB per line) doesn't slurp, and is by far a better solution than those given.

If this is time critical code for production, you can rewrite the ideas in C or perform better optimizations on the read call (instead of only reading a single byte at a time), after testing that this is indeed a bottleneck.

Code assumes newline is a linefeed character, which is a good assumption for Unix, but YMMV on Mac OS/Windows. Be sure the file ends with a linefeed to ensure the last line character count isn't overlooked.

from sys import stdin, exit

counter = 0
while True:
    byte = stdin.buffer.read(1)
    counter += 1
    if not byte:
        exit()
    if byte == b'\x0a':
        print(counter-1)
        counter = 0

adb command for getting ip address assigned by operator

Try this command, it will help you to get ipaddress

adb shell ifconfig tiwlan0

tiwlan0 is the name of the wi-fi network interface on the device. This is generic command for getting ipaddress,

 adb shell netcfg

It will output like this

usb0     DOWN  0.0.0.0         0.0.0.0         0×00001002
sit0     DOWN  0.0.0.0         0.0.0.0         0×00000080
ip6tnl0  DOWN  0.0.0.0         0.0.0.0         0×00000080
gannet0  DOWN  0.0.0.0         0.0.0.0         0×00001082
rmnet0   UP    112.79.87.220   255.0.0.0       0x000000c1
rmnet1   DOWN  0.0.0.0         0.0.0.0         0×00000080
rmnet2   DOWN  0.0.0.0         0.0.0.0         0×00000080

Session only cookies with Javascript

Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return false;
  }
  
  
  if(getCookie("KoiMilGaya")) {
    //alert('found'); 
    // Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again.. 
  } else {
    //alert('nothing');
    // Display popup or anthing here. it shows on first visit only.  
    // this will load again when user closer browser and open again. 
    setCookie('KoiMilGaya','1');
  }

Bootstrap 3 - 100% height of custom div inside column

My solution was to make all the parents 100% and set a specific percentage for each row:

html, body,div[class^="container"] ,.column {
    height: 100%;
}

.row0 {height: 10%;}
.row1 {height: 40%;}
.row2 {height: 50%;}

Can the Android layout folder contain subfolders?

Now with Android Studio and Gradle, you can have multiple resource folders in your project. Allowing to organize not only your layout files but any kind of resources.

It's not exactly a sub-folder, but may separte parts of your application.

The configuration is like this:

sourceSets {
    main {
        res.srcDirs = ['src/main/res', 'src/main/res2']
    }
}

Check the documentation.

How to substring in jquery

That's just plain JavaScript: see substring and substr.

Is the size of C "int" 2 bytes or 4 bytes?

Mostly it depends on the platform you are using .It depends from compiler to compiler.Nowadays in most of compilers int is of 4 bytes. If you want to check what your compiler is using you can use sizeof(int).

main()
{
    printf("%d",sizeof(int));
    printf("%d",sizeof(short));
    printf("%d",sizeof(long));
}

The only thing c compiler promise is that size of short must be equal or less than int and size of long must be equal or more than int.So if size of int is 4 ,then size of short may be 2 or 4 but not larger than that.Same is true for long and int. It also says that size of short and long can not be same.

Regex in JavaScript for validating decimal numbers

The schema for passing the value in as a string. The regex will validate a string of at least one digit, possibly followed by a period and exactly two digits:

{
    "type": "string",
    "pattern": "^[0-9]+(\\.[0-9]{2})?$"
}

The schema below is equivalent, except that it also allows empty strings:

{
    "type": "string",
    "pattern": "^$|^[0-9]+(\\.[0-9]{2})?$"
}

Calculating how many minutes there are between two times

double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);

TimeSpan.TotalMinutes: The total number of minutes represented by this instance.

Using an array from Observable Object with ngFor and Async Pipe Angular 2

Here's an example

// in the service
getVehicles(){
    return Observable.interval(2200).map(i=> [{name: 'car 1'},{name: 'car 2'}])
}

// in the controller
vehicles: Observable<Array<any>>
ngOnInit() {
    this.vehicles = this._vehicleService.getVehicles();
}

// in template
<div *ngFor='let vehicle of vehicles | async'>
    {{vehicle.name}}
</div>

How can I get a resource "Folder" from inside my jar File?

This link tells you how.

The magic is the getResourceAsStream() method :

InputStream is = 
this.getClass().getClassLoader().getResourceAsStream("yourpackage/mypackage/myfile.xml")

Display the current time and date in an Android application

The obvious choices for displaying the time are the AnalogClock View and the DigitalClock View.

For example, the following layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="vertical">

    <AnalogClock
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"/>

    <DigitalClock 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:gravity="center" 
        android:textSize="20sp"/>
</LinearLayout>

Looks like this:

screenshot

How to find the process id of a running Java process on Windows? And how to kill the process alone?

The solution I found is very simple. Use Window's WMIC & Java's Runtime to locate & kill the process.

Part 1: You need to put some sort of identifier into your app's startup command line. E.g. something like:

String id = "com.domain.app";

Part 2: When you run your app, make sure to include the string. Let's say you start it from within Java, do the following:

Runtime.getRuntime().exec(
   "C:\...\javaw.exe -cp ... -Dwhatever=" + id + " com.domain.app.Main"
);

Part 3: To kill the process, use Window's WMIC. Just make sure you app was started containing your id from above:

Runtime.getRuntime().exec(
  "wmic process Where \"CommandLine Like '%" + id + "%'\" Call Terminate"
);

python: sys is not defined

Move import sys outside of the try-except block:

import sys
try:
    # ...
except ImportError:
    # ...

If any of the imports before the import sys line fails, the rest of the block is not executed, and sys is never imported. Instead, execution jumps to the exception handling block, where you then try to access a non-existing name.

sys is a built-in module anyway, it is always present as it holds the data structures to track imports; if importing sys fails, you have bigger problems on your hand (as that would indicate that all module importing is broken).

How to remove numbers from a string?

A secondary option would be to match and return non-digits with some expression similar to,

/\D+/g

which would likely work for that specific string in the question (1 ding ?).

Demo

Test

_x000D_
_x000D_
function non_digit_string(str) {_x000D_
 const regex = /\D+/g;_x000D_
 let m;_x000D_
_x000D_
 non_digit_arr = [];_x000D_
 while ((m = regex.exec(str)) !== null) {_x000D_
  // This is necessary to avoid infinite loops with zero-width matches_x000D_
  if (m.index === regex.lastIndex) {_x000D_
   regex.lastIndex++;_x000D_
  }_x000D_
_x000D_
_x000D_
  m.forEach((match, groupIndex) => {_x000D_
   if (match.trim() != '') {_x000D_
    non_digit_arr.push(match.trim());_x000D_
   }_x000D_
  });_x000D_
 }_x000D_
 return non_digit_arr;_x000D_
}_x000D_
_x000D_
const str = `1 ding ? 124_x000D_
12 ding ?_x000D_
123 ding ? 123`;_x000D_
console.log(non_digit_string(str));
_x000D_
_x000D_
_x000D_


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here