Programs & Examples On #Import from excel

Reading Excel file using node.js

Useful link

https://ciphertrick.com/read-excel-files-convert-json-node-js/

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

Import and Export Excel - What is the best library?

Check the ExcelPackage project, it uses the Office Open XML file format of Excel 2007, it's lightweight and open source...

How to export data from Excel spreadsheet to Sql Server 2008 table

From your SQL Server Management Studio, you open Object Explorer, go to your database where you want to load the data into, right click, then pick Tasks > Import Data.

This opens the Import Data Wizard, which typically works pretty well for importing from Excel. You can pick an Excel file, pick what worksheet to import data from, you can choose what table to store it into, and what the columns are going to be. Pretty flexible indeed.

You can run this as a one-off, or you can store it as a SQL Server Integration Services (SSIS) package into your file system, or into SQL Server itself, and execute it over and over again (even scheduled to run at a given time, using SQL Agent).

Update: yes, yes, yes, you can do all those things you keep asking - have you even tried at least once to run that wizard??

OK, here it comes - step by step:

Step 1: pick your Excel source

enter image description here

Step 2: pick your SQL Server target database

enter image description here

Step 3: pick your source worksheet (from Excel) and your target table in your SQL Server database; see the "Edit Mappings" button!

enter image description here

Step 4: check (and change, if needed) your mappings of Excel columns to SQL Server columns in the table:

enter image description here

Step 5: if you want to use it later on, save your SSIS package to SQL Server:

enter image description here

Step 6: - success! This is on a 64-bit machine, works like a charm - just do it!!

Reading an Excel file in PHP

I use PHP-ExcelReader to read xls files, and works great.

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

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

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

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

Best way to load module/class from lib folder in Rails 3?

Warning: if you want to load the 'monkey patch' or 'open class' from your 'lib' folder, don't use the 'autoload' approach!!!

  • "config.autoload_paths" approach: only works if you are loading a class that defined only in ONE place. If some class has been already defined somewhere else, then you can't load it again by this approach.

  • "config/initializer/load_rb_file.rb" approach: always works! whatever the target class is a new class or an "open class" or "monkey patch" for existing class, it always works!

For more details , see: https://stackoverflow.com/a/6797707/445908

How to convert an address to a latitude/longitude?

Having rolled my own solution for this before, I can whole heartedly recommend the Geo::Coder::US Perl module for this. Just download all the census data and use the included importer to create the Berkeley DB for your country and point the Perl script at it. Use the module's built in address parsing, and there you have it: An offline geocoding system!

Is there an opposite of include? for Ruby Arrays?

Using unless is fine for statements with single include? clauses but, for example, when you need to check the inclusion of something in one Array but not in another, the use of include? with exclude? is much friendlier.

if @players.include? && @spectators.exclude? do
  ....
end

But as dizzy42 says above, the use of exclude? requires ActiveSupport

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

On Selenium WebDriver how to get Text from Span Tag

PHP way of getting text from span tag:

$spanText = $this->webDriver->findElement(WebDriverBy::xpath("//*[@id='specInformation']/tbody/tr[2]/td[1]/span[1]"))->getText();

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

To use arrow functions with function.prototype.call, I made a helper function on the object prototype:

  // Using
  // @func = function() {use this here} or This => {use This here}
  using(func) {
    return func.call(this, this);
  }

usage

  var obj = {f:3, a:2}
  .using(This => This.f + This.a) // 5

Edit

You don't NEED a helper. You could do:

var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5

Regex for numbers only

If you need to tolerate decimal point and thousand marker

var regex = new Regex(@"^-?[0-9][0-9,\.]+$");

You will need a "-", if the number can go negative.

Create a date from day month and year with T-SQL

Or using just a single dateadd function:

DECLARE @day int, @month int, @year int
SELECT @day = 4, @month = 3, @year = 2011

SELECT dateadd(mm, (@year - 1900) * 12 + @month - 1 , @day - 1)

How to stop java process gracefully?

Similar Question Here

Finalizers in Java are bad. They add a lot of overhead to garbage collection. Avoid them whenever possible.

The shutdownHook will only get called when the VM is shutting down. I think it very well may do what you want.

How to enable scrolling of content inside a modal?

Bootstrap will add or remove a css "modal-open" to the <body> tag when we open or close a modal. So if you open multiple modal and then close arbitrary one, the modal-open css will be removed from the body tag.

But the scroll effect depend on the attribute "overflow-y: auto;" defined in modal-open

How do I concatenate text in a query in sql server?

You have to explicitly cast the string types to the same in order to concatenate them, In your case you may solve the issue by simply addig an 'N' in front of 'SomeText' (N'SomeText'). If that doesn't work, try Cast('SomeText' as nvarchar(8)).

Find the maximum value in a list of tuples in Python

In addition to max, you can also sort:

>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

If you need to both get the raw content from the request, but also need to use a bound model version of it in the controller, you will likely get this exception.

NotSupportedException: Specified method is not supported. 

For example, your controller might look like this, leaving you wondering why the solution above doesn't work for you:

public async Task<IActionResult> Index(WebhookRequest request)
{
    using var reader = new StreamReader(HttpContext.Request.Body);

    // this won't fix your string empty problems
    // because exception will be thrown
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var body = await reader.ReadToEndAsync();

    // Do stuff
}

You'll need to take your model binding out of the method parameters, and manually bind yourself:

public async Task<IActionResult> Index()
{
    using var reader = new StreamReader(HttpContext.Request.Body);

    // You shouldn't need this line anymore.
    // reader.BaseStream.Seek(0, SeekOrigin.Begin);

    // You now have the body string raw
    var body = await reader.ReadToEndAsync();

    // As well as a bound model
    var request = JsonConvert.DeserializeObject<WebhookRequest>(body);
}

It's easy to forget this, and I've solved this issue before in the past, but just now had to relearn the solution. Hopefully my answer here will be a good reminder for myself...

assign multiple variables to the same value in Javascript

Nothing stops you from doing the above, but hold up!

There are some gotchas. Assignment in Javascript is from right to left so when you write:

var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

it effectively translates to:

var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));

which effectively translates to:

var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));

Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.

Note: My above example assumes you are running your code in the browser, hence window. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to global which is the global context for that environment).

Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.

var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.


Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.

linux: kill background task

This should kill all background processes:

jobs -p | xargs kill -9

Get a json via Http Request in NodeJS

http sends/receives data as strings... this is just the way things are. You are looking to parse the string as json.

var jsonObject = JSON.parse(data);

How to parse JSON using Node.js?

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

Binding value to style

I managed to make it work with alpha28 like this:

import {Component, View} from 'angular2/angular2';

@Component({
  selector: 'circle', 
  properties: ['color: color'],
})
@View({
    template: `<style>
    .circle{
        width:50px;
        height: 50px;
        border-radius: 25px;
    }
</style>
<div class="circle" [style.background-color]="changeBackground()">
    <content></content>
</div>
`
})
export class Circle {
    color;

    constructor(){
    }

    changeBackground(): string {
        return this.color;
    }
}

and called it like this <circle color='yellow'></circle>

Asp.net MVC ModelState.Clear

Well the ModelState basically holds the current State of the model in terms of validation, it holds

ModelErrorCollection: Represent the errors when the model try to bind the values. ex.

TryUpdateModel();
UpdateModel();

or like a parameter in the ActionResult

public ActionResult Create(Person person)

ValueProviderResult: Hold the details about the attempted bind to the model. ex. AttemptedValue, Culture, RawValue.

Clear() method must be use with caution because it can lead to unspected results. And you will lose some nice properties of the ModelState like AttemptedValue, this is used by MVC in the background to repopulate the form values in case of error.

ModelState["a"].Value.AttemptedValue

CRON command to run URL address every 5 minutes

Here is an example of the wget script in action:

wget -q -O /dev/null "http://example.com/cronjob.php" > /dev/null 2>&1

Using -O parameter like the above means that the output of the web request will be sent to STDOUT (standard output).

And the >/dev/null 2>&1 will instruct standard output to be redirected to a black hole. So no message from the executing program is returned to the screen.

How to populate a dropdownlist with json data in jquery?

var listItems= "";
var jsonData = jsonObj.d;
    for (var i = 0; i < jsonData.Table.length; i++){
      listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
    }
    $("#<%=DLState.ClientID%>").html(listItems);

Example

   <html>
    <head></head>
    <body>
      <select id="DLState">
      </select>
    </body>
    </html>

    /*javascript*/
    var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
                {"stateid" : "3","statename" : "Karnataka"},
                {"stateid" : "4","statename" : "Andaman and Nicobar"},
                 {"stateid" : "5","statename" : "Andhra Pradesh"},
                 {"stateid" : "6","statename" : "Arunachal Pradesh"}]}

    $(document).ready(function(){
      var listItems= "";
      for (var i = 0; i < jsonList.Table.length; i++){
        listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
      }
      $("#DLState").html(listItems);
    });    

jQuery select2 get value of select tag?

$("#first").val(); // this will give you value of selected element. i.e. 1,2,3.

Insert node at a certain position in a linked list C++

Insert an element at very beginning position. case-1 when the list is empty. case-2 When the list is not empty.

    #include<iostream>

using namespace std;

struct Node{
int data;
Node* next; //link == head =stored the address of the next node
};

Node* head;  //pointer to Head node with empty list

void Insert(int y);
void print();

int main(){
    head = nullptr; //empty list
    int n,y;
    cout<<"how many number do you want to enter?"<<endl;
    cin>>n;
    for (int i=0;i<n;i++){
        cout<<"Enter the number "<<i+1<<endl;
        cin>>y;
        Insert(y);
        print();
    }
}

void Insert(int y){
    Node* temp = new Node(); //create dynamic memory allocation
    temp->data = y;
    temp->next = head; // temp->next = null; when list is empty
    head = temp;
}

void print(){
    Node* temp = head;
    cout<<"List is: "<<endl;
    while(temp!= nullptr){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
    cout<<endl;
}

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

IndentationError: unexpected indent error

As the error says you have not correctly indented code, check_exists_sql is not aligned with line above it cursor = db.cursor() .

Also use 4 spaces for indentation.

Read this http://diveintopython.net/getting_to_know_python/indenting_code.html

Scanner vs. StringTokenizer vs. String.Split

They're essentially horses for courses.

  • Scanner is designed for cases where you need to parse a string, pulling out data of different types. It's very flexible, but arguably doesn't give you the simplest API for simply getting an array of strings delimited by a particular expression.
  • String.split() and Pattern.split() give you an easy syntax for doing the latter, but that's essentially all that they do. If you want to parse the resulting strings, or change the delimiter halfway through depending on a particular token, they won't help you with that.
  • StringTokenizer is even more restrictive than String.split(), and also a bit fiddlier to use. It is essentially designed for pulling out tokens delimited by fixed substrings. Because of this restriction, it's about twice as fast as String.split(). (See my comparison of String.split() and StringTokenizer.) It also predates the regular expressions API, of which String.split() is a part.

You'll note from my timings that String.split() can still tokenize thousands of strings in a few milliseconds on a typical machine. In addition, it has the advantage over StringTokenizer that it gives you the output as a string array, which is usually what you want. Using an Enumeration, as provided by StringTokenizer, is too "syntactically fussy" most of the time. From this point of view, StringTokenizer is a bit of a waste of space nowadays, and you may as well just use String.split().

PHP - Notice: Undefined index:

Before you extract values from $_POST, you should check if they exist. You could use the isset function for this (http://php.net/manual/en/function.isset.php)

How to call Stored Procedure in a View?

This construction is not allowed in SQL Server. An inline table-valued function can perform as a parameterized view, but is still not allowed to call an SP like this.

Here's some examples of using an SP and an inline TVF interchangeably - you'll see that the TVF is more flexible (it's basically more like a view than a function), so where an inline TVF can be used, they can be more re-eusable:

CREATE TABLE dbo.so916784 (
    num int
)
GO

INSERT INTO dbo.so916784 VALUES (0)
INSERT INTO dbo.so916784 VALUES (1)
INSERT INTO dbo.so916784 VALUES (2)
INSERT INTO dbo.so916784 VALUES (3)
INSERT INTO dbo.so916784 VALUES (4)
INSERT INTO dbo.so916784 VALUES (5)
INSERT INTO dbo.so916784 VALUES (6)
INSERT INTO dbo.so916784 VALUES (7)
INSERT INTO dbo.so916784 VALUES (8)
INSERT INTO dbo.so916784 VALUES (9)
GO

CREATE PROCEDURE dbo.usp_so916784 @mod AS int
AS 
BEGIN
    SELECT  *
    FROM    dbo.so916784
    WHERE   num % @mod = 0
END
GO

CREATE FUNCTION dbo.tvf_so916784 (@mod AS int)
RETURNS TABLE
    AS
RETURN
    (
     SELECT *
     FROM   dbo.so916784
     WHERE  num % @mod = 0
    )
GO    

EXEC dbo.usp_so916784 3
EXEC dbo.usp_so916784 4

SELECT * FROM dbo.tvf_so916784(3)    
SELECT * FROM dbo.tvf_so916784(4)

DROP FUNCTION dbo.tvf_so916784
DROP PROCEDURE dbo.usp_so916784
DROP TABLE dbo.so916784

Convert MySQL to SQlite

I found the perfect solution

First, you need this script (put it into a file called 'mysql-to-sqlite.sh'):

#!/bin/bash
if [ "x$1" == "x" ]; then
  echo "Usage: $0 <dumpname>"
  exit
fi

cat $1 |
grep -v ' KEY "' |
grep -v ' UNIQUE KEY "' |
grep -v ' PRIMARY KEY ' |
sed '/^SET/d' |
sed 's/ unsigned / /g' |
sed 's/ auto_increment/ primary key autoincrement/g' |
sed 's/ smallint([0-9]*) / integer /g' |
sed 's/ tinyint([0-9]*) / integer /g' |
sed 's/ int([0-9]*) / integer /g' |
sed 's/ character set [^ ]* / /g' |
sed 's/ enum([^)]*) / varchar(255) /g' |
sed 's/ on update [^,]*//g' |
sed 's/\\r\\n/\\n/g' |
sed 's/\\"/"/g' |
perl -e 'local $/;$_=<>;s/,\n\)/\n\)/gs;print "begin;\n";print;print "commit;\n"' |
perl -pe '
if (/^(INSERT.+?)\(/) {
  $a=$1;
  s/\\'\''/'\'\''/g;
  s/\\n/\n/g;
  s/\),\(/\);\n$a\(/g;
}
' > $1.sql
cat $1.sql | sqlite3 $1.db > $1.err
ERRORS=`cat $1.err | wc -l`
if [ $ERRORS == 0 ]; then
  echo "Conversion completed without error. Output file: $1.db"
  rm $1.sql
  rm $1.err
else
  echo "There were errors during conversion.  Please review $1.err and $1.sql for details."
fi

Then, dump a copy of your database:

you@prompt:~$ mysqldump -u root -p --compatible=ansi --skip-opt generator > dumpfile

And now, run the conversion:

you@prompt:~$ mysql-to-sqlite.sh dumpfile

And if all goes well, you should now have a dumpfile.db which can be used via sqlite3.

you@prompt:~$ sqlite3 dumpfile.db 
SQLite version 3.6.10
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
dg_cities                 dg_forms                  dg_surnames             
dg_counties               dg_provinces              dg_user_accounts        
dg_countries              dg_provinces_netherlands
dg_first_names            dg_states

How to prevent default event handling in an onclick method?

Just place "javascript:void(0)", in place of "#" in href tag

<a href="javascript:void(0);" onclick="callmymethod(24)">Call</a>

python request with authentication (access_token)

The requests package has a very nice API for HTTP requests, adding a custom header works like this (source: official docs):

>>> import requests
>>> response = requests.get(
... 'https://website.com/id', headers={'Authorization': 'access_token myToken'})

If you don't want to use an external dependency, the same thing using urllib2 of the standard library looks like this (source: the missing manual):

>>> import urllib2
>>> response = urllib2.urlopen(
... urllib2.Request('https://website.com/id', headers={'Authorization': 'access_token myToken'})

Duplicate and rename Xcode project & associated folders

I'm posting this since I have always been struggling when renaming a project in XCode.

Renaming the project is good and simple but this doesn't rename the source folder. Here is a step by step of what I have done that worked great in Xcode 4 and 5 thanks to the links below.

REF links:
Rename Project.
Rename Source Folder and other files.

1- Backup your project.

If you are using git, commit any changes, make a copy of the entire project folder and backup in time machine before making any changes (this step is not required but I highly recommended).

2- Open your project.

3- Slow double click or hit enter on the Project name (blue top icon) and rename it to whatever you like.

NOTE: After you rename the project and press ‘enter’ it will suggest to automatically change all project-name-related entries and will allow you to de-select some of them if you want. Select all of them and click ok.

4- Rename the Scheme

a) Click the menu right next to the stop button and select Manage Schemes.

b) Single-slow-click or hit enter on the old name scheme and rename it to whatever you like.

c) Click ok.

5 - Build and run to make sure it works.

NOTES: At this point all of the important project files should be renamed except the comments in the classes created when the project was created nor the source folder. Next we will rename the folder in the file system.

6- Close the project.

7- Rename the main and the source folder.

8- Right click the project bundle .xcodeproj file and select “Show Package Contents” from the context menu. Open the .pbxproj file with any text editor.

9- Search and replace any occurrence of the original folder name with the new folder name.

10- Save the file.

11- Open XCode project, test it.

12- Done.

EDIT 10/11/19:

There is a tool to rename projects in Xcode I haven't tried it enough to comment on it. https://github.com/appculture/xcode-project-renamer

What are callee and caller saved registers?

Caller-saved registers (AKA volatile registers, or call-clobbered) are used to hold temporary quantities that need not be preserved across calls.

For that reason, it is the caller's responsibility to push these registers onto the stack or copy them somewhere else if it wants to restore this value after a procedure call.

It's normal to let a call destroy temporary values in these registers, though.

Callee-saved registers (AKA non-volatile registers, or call-preserved) are used to hold long-lived values that should be preserved across calls.

When the caller makes a procedure call, it can expect that those registers will hold the same value after the callee returns, making it the responsibility of the callee to save them and restore them before returning to the caller. Or to not touch them.

Setting background color for a JFrame

Hello There I did have the same problem and after many attempts I found that the problem is that you need a Graphics Object to be able to draw, paint(setBackgroundColor).

My code usually goes like this:

import javax.swing.*;
import java.awt.*;


public class DrawGraphics extends JFrame{

    public DrawGraphics(String title) throws HeadlessException {
      super(title);
      InitialElements();
    }

    private void InitialElements(){
      setSize(300, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
      // This one does not work
      // getContentPane().setBackground(new Color(70, 80, 70));

    }

    public void paint(Graphics draw){
      //Here you can perform any drawing like an oval...
      draw.fillOval(40, 40, 60, 50);

      getContentPane().setBackground(new Color(70,80,70));
    }
}

The missing part on almost all other answers is where to place the code. Then now you know it goes in paint(Graphics G)

How to use shared memory with Linux in C

Here is an example for shared memory :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 1024  /* make it a 1K shared memory segment */

int main(int argc, char *argv[])
{
    key_t key;
    int shmid;
    char *data;
    int mode;

    if (argc > 2) {
        fprintf(stderr, "usage: shmdemo [data_to_write]\n");
        exit(1);
    }

    /* make the key: */
    if ((key = ftok("hello.txt", 'R')) == -1) /*Here the file must exist */ 
{
        perror("ftok");
        exit(1);
    }

    /*  create the segment: */
    if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
        perror("shmget");
        exit(1);
    }

    /* attach to the segment to get a pointer to it: */
    data = shmat(shmid, NULL, 0);
    if (data == (char *)(-1)) {
        perror("shmat");
        exit(1);
    }

    /* read or modify the segment, based on the command line: */
    if (argc == 2) {
        printf("writing to segment: \"%s\"\n", argv[1]);
        strncpy(data, argv[1], SHM_SIZE);
    } else
        printf("segment contains: \"%s\"\n", data);

    /* detach from the segment: */
    if (shmdt(data) == -1) {
        perror("shmdt");
        exit(1);
    }

    return 0;
}

Steps :

  1. Use ftok to convert a pathname and a project identifier to a System V IPC key

  2. Use shmget which allocates a shared memory segment

  3. Use shmat to attache the shared memory segment identified by shmid to the address space of the calling process

  4. Do the operations on the memory area

  5. Detach using shmdt

Expected response code 220 but got code "", with message "" in Laravel

This problem can generally occur when you do not enable two step verification for the gmail account (which can be done here) you are using to send an email. So first, enable two step verification, you can find plenty of resources for enabling two step verification. After you enable it, then you have to create an app password. And use the app password in your .env file. When you are done with it, your .env file will look something like.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<<your email address>>
MAIL_PASSWORD=<<app password>>
MAIL_ENCRYPTION=tls

and your mail.php

<?php

return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => env('MAIL_PORT', 587),
    'from' => ['address' => '<<your email>>', 'name' => '<<any name>>'],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => false,

];

After doing so, run php artisan config:cache and php artisan config:clear, then check, email should work.

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Most likely the path you are trying to access does not exist. It seems you are trying to save to a relative location and you do not have an file extension in that string. If you need to use relative paths you can parse the path from ActiveWorkbook.FullName

EDIT: Better syntax would also be

ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlWorkbookNormal

How to connect mySQL database using C++

Yes, you will need the mysql c++ connector library. Read on below, where I explain how to get the example given by mysql developers to work.

Note(and solution): IDE: I tried using Visual Studio 2010, but just a few sconds ago got this all to work, it seems like I missed it in the manual, but it suggests to use Visual Studio 2008. I downloaded and installed VS2008 Express for c++, followed the steps in chapter 5 of manual and errors are gone! It works. I'm happy, problem solved. Except for the one on how to get it to work on newer versions of visual studio. You should try the mysql for visual studio addon which maybe will get vs2010 or higher to connect successfully. It can be downloaded from mysql website

Whilst trying to get the example mentioned above to work, I find myself here from difficulties due to changes to the mysql dev website. I apologise for writing this as an answer, since I can't comment yet, and will edit this as I discover what to do and find the solution, so that future developers can be helped.(Since this has gotten so big it wouldn't have fitted as a comment anyways, haha)

@hd1 link to "an example" no longer works. Following the link, one will end up at the page which gives you link to the main manual. The main manual is a good reference, but seems to be quite old and outdated, and difficult for new developers, since we have no experience especially if we missing a certain file, and then what to add.

@hd1's link has moved, and can be found with a quick search by removing the url components, keeping just the article name, here it is anyways: http://dev.mysql.com/doc/connector-cpp/en/connector-cpp-examples-complete-example-1.html

Getting 7.5 MySQL Connector/C++ Complete Example 1 to work

Downloads:

-Get the mysql c++ connector, even though it is bigger choose the installer package, not the zip.

-Get the boost libraries from boost.org, since boost is used in connection.h and mysql_connection.h from the mysql c++ connector

Now proceed:

-Install the connector to your c drive, then go to your mysql server install folder/lib and copy all libmysql files, and paste in your connector install folder/lib/opt

-Extract the boost library to your c drive

Next:

It is alright to copy the code as it is from the example(linked above, and ofcourse into a new c++ project). You will notice errors:

-First: change

cout << "(" << __FUNCTION__ << ") on line " »
 << __LINE__ << endl;

to

cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;

Not sure what that tiny double arrow is for, but I don't think it is part of c++

-Second: Fix other errors of them by reading Chapter 5 of the sql manual, note my paragraph regarding chapter 5 below

[Note 1]: Chapter 5 Building MySQL Connector/C++ Windows Applications with Microsoft Visual Studio If you follow this chapter, using latest c++ connecter, you will likely see that what is in your connector folder and what is shown in the images are quite different. Whether you look in the mysql server installation include and lib folders or in the mysql c++ connector folders' include and lib folders, it will not match perfectly unless they update the manual, or you had a magic download, but for me they don't match with a connector download initiated March 2014.

Just follow that chapter 5,

-But for c/c++, General, Additional Include Directories include the "include" folder from the connector you installed, not server install folder

-While doing the above, also include your boost folder see note 2 below

-And for the Linker, General.. etc use the opt folder from connector/lib/opt

*[Note 2]*A second include needs to happen, you need to include from the boost library variant.hpp, this is done the same as above, add the main folder you extracted from the boost zip download, not boost or lib or the subfolder "variant" found in boostmainfolder/boost.. Just the main folder as the second include

Next:

What is next I think is the Static Build, well it is what I did anyways. Follow it.

Then build/compile. LNK errors show up(Edit: Gone after changing ide to visual studio 2008). I think it is because I should build connector myself(if you do this in visual studio 2010 then link errors should disappear), but been working on trying to get this to work since Thursday, will see if I have the motivation to see this through after a good night sleep(and did and now finished :) ).

what is difference between success and .done() method of $.ajax

.success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine.

The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.

promise.done(doneCallback).fail(failCallback)

.done() has only one callback and it is the success callback

How to prevent tensorflow from allocating the totality of a GPU memory?

i tried to train unet on voc data set but because of huge image size, memory finishes. i tried all the above tips, even tried with batch size==1, yet to no improvement. sometimes TensorFlow version also causes the memory issues. try by using

pip install tensorflow-gpu==1.8.0

Logging in Scala

Logging in 2020

I was really surprised that Scribe logging framework that I use at work isn't even mentioned here. What is more, it doesn't even appear on the first page in Google after searching "scala logging". But this page appears when googling it! So let me leave that here.

Main advantages of Scribe:

Match everything except for specified strings

I had the same question, the solutions proposed were almost working but they had some issue. In the end the regex I used is:

^(?!red|green|blue).*

I tested it in Javascript and .NET.

.* should't be placed inside the negative lookahead like this: ^(?!.*red|green|blue) or it would make the first element behave different from the rest (i.e. "anotherred" wouldn't be matched while "anothergreen" would)

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

$("#ValuationName").bind("keypress", function (event) {
    if (event.charCode!=0) {
        var regex = new RegExp("^[a-zA-Z ]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }
});

How can I format date by locale in Java?

Yes, using DateFormat.getDateInstance(int style, Locale aLocale) This displays the current date in a locale-specific way.

So, for example:

DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, yourLocale);
String formattedDate = df.format(yourDate);

See the docs for the exact meaning of the style parameter (SHORT, MEDIUM, etc)

Access to the path denied error in C#

You are trying to create a FileStream object for a directory (folder). Specify a file name (e.g. @"D:\test.txt") and the error will go away.

By the way, I would suggest that you use the StreamWriter constructor that takes an Encoding as its second parameter, because otherwise you might be in for an unpleasant surprise when trying to read the saved file later (using StreamReader).

How to use font-awesome icons from node-modules

I came upon this question having a similar problem and thought I would share another solution:

If you are creating a Javascript application, font awesome icons can also be referenced directly through Javascript:

First, do the steps in this guide:

npm install @fortawesome/fontawesome-svg-core

Then inside your javascript:

import { library, icon } from '@fortawesome/fontawesome-svg-core'
import { faStroopwafel } from '@fortawesome/free-solid-svg-icons'

library.add(faStroopwafel)

const fontIcon= icon({ prefix: 'fas', iconName: 'stroopwafel' })

After the above steps, you can insert the icon inside an HTML node with:

htmlNode.appendChild(fontIcon.node[0]);

You can also access the HTML string representing the icon with:

fontIcon.html

How to open a page in a new window or tab from code-behind

Target= "_blank"

This does it in html, give it a try in C#

How to prevent Screen Capture in Android

public class InShotApp extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
            registerActivityLifecycle();
        }
    
        private void registerActivityLifecycle() {
    
            registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                    activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);            }
    
                @Override
                public void onActivityStarted(@NonNull Activity activity) {
    
                }
    
                @Override
                public void onActivityResumed(@NonNull Activity activity) {
    
                }
    
                @Override
                public void onActivityPaused(@NonNull Activity activity) {
    
                }
    
                @Override
                public void onActivityStopped(@NonNull Activity activity) {
    
                }
    
                @Override
                public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
    
                }
    
                @Override
                public void onActivityDestroyed(@NonNull Activity activity) {
    
                }
            });
    
        }
    }

HTML5 <video> element on Android

This might not exactly answer your question, but we're using the 3GP or 3GP2 file format. Better even to use the rtsp protocol, but the Android browser will also recognize the 3GP file format.

You can use something like

self.location = URL_OF_YOUR_3GP_FILE

to trigger the video player. The file will be streamed and after playback ends, handling is returned to the browser.

For me this solves a lot of problems with current video tag implementation on android devices.

How to get Map data using JDBCTemplate.queryForMap

queryForMap is appropriate if you want to get a single row. You are selecting without a where clause, so you probably want to queryForList. The error is probably indicative of the fact that queryForMap wants one row, but you query is retrieving many rows.

Check out the docs. There is a queryForList that takes just sql; the return type is a

List<Map<String,Object>>.

So once you have the results, you can do what you are doing. I would do something like

List results = template.queryForList(sql);

for (Map m : results){
   m.get('userid');
   m.get('username');
} 

I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.

If you have a User object, and you actually want to load User instances, you can use the queryForList that takes sql and a class type

queryForList(String sql, Class<T> elementType)

(wow Spring has changed a lot since I left Javaland.)

Parse JSON from HttpURLConnection object

Define the following function (not mine, not sure where I found it long ago):

private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
return sb.toString();

}

Then:

String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
    {
        success = true;
        InputStream response = conn.getInputStream();
        jsonReply = convertStreamToString(response);

        // Do JSON handling here....
    }

how to concat two columns into one with the existing column name in mysql?

Just Remove * from your select clause, and mention all column names explicitly and omit the FIRSTNAME column. After this write CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME. The above query will give you the only one FIRSTNAME column.

Bootstrap 3 - Responsive mp4-video

This worked for me:

<video src="file.mp4" controls style="max-width:100%; height:auto"></video>

Get current language in CultureInfo

I tried {CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;} but it didn`t work for me, since my UI culture was different from my number/currency culture. So I suggest you to use:

CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture;

This will give you the culture your UI is (texts on windows, message boxes, etc).

Android changing Floating Action Button color

Other solutions may work. This is the 10 pound gorilla approach that has the advantage of being broadly applicable in this and similar cases:

Styles.xml:

<style name="AppTheme.FloatingAccentButtonOverlay" >
    <item name="colorAccent">@color/colorFloatingActionBarAccent</item>
</style>

your layout xml:

<android.support.design.widget.FloatingActionButton
       android:theme="AppTheme.FloatingAccentButtonOverlay"
       ...
 </android.support.design.widget.FloatingActionButton>

How to compile makefile using MinGW?

I found a very good example here: https://bigcode.wordpress.com/2016/12/20/compiling-a-very-basic-mingw-windows-hello-world-executable-in-c-with-a-makefile/

It is a simple Hello.c (you can use c++ with g++ instead of gcc) using the MinGW on windows.

The Makefile looking like:

EXECUTABLE = src/Main.cpp

CC = "C:\MinGW\bin\g++.exe"
LDFLAGS = -lgdi32

src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)

all: myprog

myprog: $(obj)
    $(CC) -o $(EXECUTABLE) $^ $(LDFLAGS)

.PHONY: clean
clean:
    del $(obj) $(EXECUTABLE)

Java Regex to Validate Full Name allow only Spaces and Letters

Try with this:

public static boolean userNameValidation(String name){

return name.matches("(?i)(^[a-z])((?![? .,'-]$)[ .]?[a-z]){3,24}$");
}

How to call a method in another class in Java?

Try this :

public void addTeacherToClassRoom(classroom myClassRoom, String TeacherName)
{
    myClassRoom.setTeacherName(TeacherName);
}

How to convert a string to an integer in JavaScript?

I posted the wrong answer here, sorry. fixed.

This is an old question, but I love this trick:

~~"2.123"; //2
~~"5"; //5

The double bitwise negative drops off anything after the decimal point AND converts it to a number format. I've been told it's slightly faster than calling functions and whatnot, but I'm not entirely convinced.

EDIT: Another method I just saw here (a question about the javascript >>> operator, which is a zero-fill right shift) which shows that shifting a number by 0 with this operator converts the number to a uint32 which is nice if you also want it unsigned. Again, this converts to an unsigned integer, which can lead to strange behaviors if you use a signed number.

"-2.123" >>> 0; // 4294967294
"2.123" >>> 0; // 2
"-5" >>> 0; // 4294967291
"5" >>> 0; // 5

Install GD library and freetype on Linux

For CentOS: When installing php-gd you need to specify the version. I fixed it by running: sudo yum install php55-gd

Box shadow in IE7 and IE8

You could try this

box-shadow:
progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=10, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=10, OffY=20, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=20, OffY=30, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=30, OffY=40, Color='#19000000');

how to force maven to update local repo

You can also use this command on the command line:

mvn dependency:purge-local-repository clean install

How do I format a number in Java?

Be aware that classes that descend from NumberFormat (and most other Format descendants) are not synchronized. It is a common (but dangerous) practice to create format objects and store them in static variables in a util class. In practice, it will pretty much always work until it starts experiencing significant load.

Java String.split() Regex

String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];

This should do it. Everything nicely stored in res.

print arraylist element?

Printing a specific element is

list.get(INDEX)

I think the best way to print the whole list in one go and this will also avoid putting a loop

Arrays.toString(list.toArray())

How to get ° character in a string in python?

You can also use chr(176) to print the degree sign. Here is an example using python 3.6.5 interactive shell:

https://i.stack.imgur.com/spoWL.png

Extract hostname name from string

Try this:

var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
var domain = matches && matches[1];  // domain will be null if no match is found

If you want to exclude the port from your result, use this expression instead:

/^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i

Edit: To prevent specific domains from matching, use a negative lookahead. (?!youtube.com)

/^https?\:\/\/(?!(?:www\.)?(?:youtube\.com|youtu\.be))([^\/:?#]+)(?:[\/:?#]|$)/i

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

How to turn NaN from parseInt into 0 for an empty string?

You can also use the isNaN() function:

var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)

Remove a symlink to a directory

If rm cannot remove a symlink, perhaps you need to look at the permissions on the directory that contains the symlink. To remove directory entries, you need write permission on the containing directory.

How to calculate probability in a normal distribution given mean & standard deviation?

The formula cited from wikipedia mentioned in the answers cannot be used to calculate normal probabilites. You would have to write a numerical integration approximation function using that formula in order to calculate the probability.

That formula computes the value for the probability density function. Since the normal distribution is continuous, you have to compute an integral to get probabilities. The wikipedia site mentions the CDF, which does not have a closed form for the normal distribution.

Fastest way to add an Item to an Array

Not very clean but it works :)

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4

arr = arr.Concat({newItem}).ToArray

How can I run a windows batch file but hide the command window?

This little VBScript from technet does the trick:

Const HIDDEN_WINDOW = 12

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")

Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
errReturn = objProcess.Create("mybatch.bat", null, objConfig, intProcessID)

Edit mybatch.bat to your bat file name, save as a vbs, run it.

Doc says it's not tested in Win7, but I just tested it, it works fine. Won't show any window for whatever process you run

Is it possible to return empty in react render function?

Yes you can return an empty value from a React render method.

You can return any of the following: false, null, undefined, or true

According to the docs:

false, null, undefined, and true are valid children. They simply don’t render.

You could write

return null; or
return false; or
return true; or
return <div>{undefined}</div>; 

However return null is the most preferred as it signifies that nothing is returned

Pythonic way to find maximum value and its index in a list?

There are many options, for example:

import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))

Default SQL Server Port

The default port for SQL Server Database Engine is 1433.

And as a best practice it should always be changed after the installation. 1433 is widely known which makes it vulnerable to attacks.

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

Is it possible to have empty RequestParam values use the defaultValue?

You can set RequestParam, using generic class Integer instead of int, it will resolve your issue.

   @RequestParam(value= "i", defaultValue = "20") Integer i

Python Key Error=0 - Can't find Dict error in code

The error you're getting is that self.adj doesn't already have a key 0. You're trying to append to a list that doesn't exist yet.

Consider using a defaultdict instead, replacing this line (in __init__):

self.adj = {}

with this:

self.adj = defaultdict(list)

You'll need to import at the top:

from collections import defaultdict

Now rather than raise a KeyError, self.adj[0].append(edge) will create a list automatically to append to.

How to get the name of the current Windows user in JavaScript

Working for me on IE:

<script type="text/javascript">
  var WinNetwork = new ActiveXObject("WScript.Network");
  document.write(WinNetwork.UserName);
</script>

...but ActiveX controls needs to be on in security settings.

Leave out quotes when copying from cell

My solution when I hit the quotes issue was to strip carriage returns from the end of my cells' text. Because of these carriage returns (inserted by an external program), Excel was adding quotes to the entire string.

How to open an elevated cmd using command line for Windows?

Press the Windows + X key and you can now select the Powershell or Command Prompt with admin rights. Works if you are the admin. The function can be unusable if the system is not yours.

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

After logging in, on the home page of the Server Console you should see 3 sections:

  • Information and Resources
  • Domain Configurations
  • Services Configurations

Under Services Configurations there is subsection Other Services. Click the JTA Configuration link under Other Services. The transaction timeout should be the top setting on the page displayed, labelled Timeout Seconds.

Weblogic Console screenshot

Format specifier %02x

%02x means print at least 2 digits, prepend it with 0's if there's less. In your case it's 7 digits, so you get no extra 0 in front.

Also, %x is for int, but you have a long. Try %08lx instead.

subtract time from date - moment js

Michael Richardson's solution is great. If you would like to subtract dates (because Google will point you here if you search for it), you could also say:

var date1 = moment( "2014-06-07 00:03:00" );
var date2 = moment( "2014-06-07 09:22:00" );

differenceInMs = date2.diff(date1); // diff yields milliseconds
duration = moment.duration(differenceInMs); // moment.duration accepts ms
differenceInMinutes = duration.asMinutes(); // if you would like to have the output 559

How to get day of the month?

It is simplified a lot in version Java 8. I have given some util methods below.

To get the day of the month in the format of int for the given day, month, and year.

    public static int findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.of(year, month, day).getDayOfMonth());
        return LocalDate.of(year, month, day).getDayOfMonth();
    }

To get current day of the month in the format of int.

    public static int findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfMonth());
        return LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfMonth();
    }

To get the day of the week in the format of String for the given day, month, and year.

    public static String findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.of(year, month, day).getDayOfWeek());
        return LocalDate.of(year, month, day).getDayOfWeek().toString();
    }

To get current day of the week in the format of String.

    public static String findDay(final int month, final int day, final int year) {
        // System.out.println(LocalDate.now(ZoneId.of("Asia/Kolkata"))..getDayOfWeek());
        return LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfWeek().toString();
    }

Does document.body.innerHTML = "" clear the web page?

Whilst agreeing with Douwe Maan and Erik's answers, there are a couple of other things here that you may find useful.

Firstly, within your head tags, you can reference a separate JavaScript file, which is then reusable:

<script language="JavaScript" src="/common/common.js"></script>

where common.js is your reusable function file in a top-level directory called common.

Secondly, you can delay the operation of a script using setTimeout, e.g.:

setTimeout(someFunction, 5000);

The second argument is in milliseconds. I mention this, because you appear to be trying to delay something in your original code snippet.

Arrays vs Vectors: Introductory Similarities and Differences

arrays:

  • are a builtin language construct;
  • come almost unmodified from C89;
  • provide just a contiguous, indexable sequence of elements; no bells and whistles;
  • are of fixed size; you can't resize an array in C++ (unless it's an array of POD and it's allocated with malloc);
  • their size must be a compile-time constant unless they are allocated dynamically;
  • they take their storage space depending from the scope where you declare them;
  • if dynamically allocated, you must explicitly deallocate them;
  • if they are dynamically allocated, you just get a pointer, and you can't determine their size; otherwise, you can use sizeof (hence the common idiom sizeof(arr)/sizeof(*arr), that however fails silently when used inadvertently on a pointer);
  • automatically decay to a pointers in most situations; in particular, this happens when passing them to a function, which usually requires passing a separate parameter for their size;
  • can't be returned from a function;
  • can't be copied/assigned directly;
  • dynamical arrays of objects require a default constructor, since all their elements must be constructed first;

std::vector:

  • is a template class;
  • is a C++ only construct;
  • is implemented as a dynamic array;
  • grows and shrinks dynamically;
  • automatically manage their memory, which is freed on destruction;
  • can be passed to/returned from functions (by value);
  • can be copied/assigned (this performs a deep copy of all the stored elements);
  • doesn't decay to pointers, but you can explicitly get a pointer to their data (&vec[0] is guaranteed to work as expected);
  • always brings along with the internal dynamic array its size (how many elements are currently stored) and capacity (how many elements can be stored in the currently allocated block);
  • the internal dynamic array is not allocated inside the object itself (which just contains a few "bookkeeping" fields), but is allocated dynamically by the allocator specified in the relevant template parameter; the default one gets the memory from the freestore (the so-called heap), independently from how where the actual object is allocated;
  • for this reason, they may be less efficient than "regular" arrays for small, short-lived, local arrays;
  • when reallocating, the objects are copied (moved, in C++11);
  • does not require a default constructor for the objects being stored;
  • is better integrated with the rest of the so-called STL (it provides the begin()/end() methods, the usual STL typedefs, ...)

Also consider the "modern alternative" to arrays - std::array; I already described in another answer the difference between std::vector and std::array, you may want to have a look at it.

How to parse a String containing XML in Java and retrieve the value of the root node?

I think you would be look at String class, there are multiple ways to do it. What about substring(int,int) and indexOf(int) lastIndexOf(int)?

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Steps I have followed to fix the issue as follows,

Analyze -> Code Cleanup

File -> Project Structures -> Select project from the list and update the gradle version to latest.

Build -> Clean Project

Build -> Make Project

Now the issue related to the build may get reported like using compile instead of implementation etc.

Please fix those and hopefully it should fix the issue.

Disable EditText blinking cursor

In my case, I wanted to enable/disable the cursor when the edit is focused.

In your Activity:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if (v instanceof EditText) {
            EditText edit = ((EditText) v);
            Rect outR = new Rect();
            edit.getGlobalVisibleRect(outR);
            Boolean isKeyboardOpen = !outR.contains((int)ev.getRawX(), (int)ev.getRawY());
            System.out.print("Is Keyboard? " + isKeyboardOpen);
            if (isKeyboardOpen) {
                System.out.print("Entro al IF");
                edit.clearFocus();
                InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
            }

            edit.setCursorVisible(!isKeyboardOpen);

        }
    }
    return super.dispatchTouchEvent(ev);
}

npm - how to show the latest version of a package

You can use:

npm show {pkg} version

(so npm show express version will return now 3.0.0rc3).

Implode an array with JavaScript?

array.join was not recognizing ";" how a separator, but replacing it with comma. Using jQuery, you can use $.each to implode an array (Note that output_saved_json is the array and tmp is the string that will store the imploded array):

var tmp = "";
$.each(output_saved_json, function(index,value) {
    tmp = tmp + output_saved_json[index] + ";";
});

output_saved_json = tmp.substring(0,tmp.length - 1); // remove last ";" added

I have used substring to remove last ";" added at the final without necessity. But if you prefer, you can use instead substring something like:

var tmp = "";
$.each(output_saved_json, function(index,value) {
    tmp = tmp + output_saved_json[index];

    if((index + 1) != output_saved_json.length) {
         tmp = tmp + ";";
    }
});

output_saved_json = tmp;

I think this last solution is more slower than the 1st one because it needs to check if index is different than the lenght of array every time while $.each do not end.

What is the T-SQL syntax to connect to another SQL Server?

Whenever we are trying to retrieve any data from another server we need two steps.

First step:

-- Server one scalar variable
DECLARE @SERVER VARCHAR(MAX)
--Oracle is the server to which we want to connect
EXEC SP_ADDLINKEDSERVER @SERVER='ORACLE'

Second step:

--DBO is the owner name to know table owner name execute (SP_HELP TABLENAME)    
SELECT * INTO DESTINATION_TABLE_NAME 
FROM ORACLE.SOURCE_DATABASENAME.DBO.SOURCE_TABLE

Easy way to make a confirmation dialog in Angular?

you can use window.confirm inside your function combined with if condition

 delete(whatever:any){
    if(window.confirm('Are sure you want to delete this item ?')){
    //put your delete method logic here
   }
}

when you call the delete method it will popup a confirmation message and when you press ok it will perform all the logic inside the if condition.

What are best practices for REST nested resources?

I've moved what I've done from the question to an answer where more people are likely to see it.

What I've done is to have the creation endpoints at the nested endpoint, The canonical endpoint for modifying or querying an item is not at the nested resource.

So in this example (just listing the endpoints that change a resource)

  • POST /companies/ creates a new company returns a link to the created company.
  • POST /companies/{companyId}/departments when a department is put creates the new department returns a link to /departments/{departmentId}
  • PUT /departments/{departmentId} modifies a department
  • POST /departments/{deparmentId}/employees creates a new employee returns a link to /employees/{employeeId}

So there are root level resources for each of the collections. However the create is in the owning object.

jQuery Find and List all LI elements within a UL within a specific DIV

var column1RelArray = [];
$('#column1 li').each(function(){
    column1RelArray.push($(this).attr('rel'));
});

or fp style

var column1RelArray = $('#column1 li').map(function(){ 
    return $(this).attr('rel'); 
});

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

To add to Martijn’s answer, this is the relevant part of the source (in C, as the range object is written in native code):

static int
range_contains(rangeobject *r, PyObject *ob)
{
    if (PyLong_CheckExact(ob) || PyBool_Check(ob))
        return range_contains_long(r, ob);

    return (int)_PySequence_IterSearch((PyObject*)r, ob,
                                       PY_ITERSEARCH_CONTAINS);
}

So for PyLong objects (which is int in Python 3), it will use the range_contains_long function to determine the result. And that function essentially checks if ob is in the specified range (although it looks a bit more complex in C).

If it’s not an int object, it falls back to iterating until it finds the value (or not).

The whole logic could be translated to pseudo-Python like this:

def range_contains (rangeObj, obj):
    if isinstance(obj, int):
        return range_contains_long(rangeObj, obj)

    # default logic by iterating
    return any(obj == x for x in rangeObj)

def range_contains_long (r, num):
    if r.step > 0:
        # positive step: r.start <= num < r.stop
        cmp2 = r.start <= num
        cmp3 = num < r.stop
    else:
        # negative step: r.start >= num > r.stop
        cmp2 = num <= r.start
        cmp3 = r.stop < num

    # outside of the range boundaries
    if not cmp2 or not cmp3:
        return False

    # num must be on a valid step inside the boundaries
    return (num - r.start) % r.step == 0

Is there an operator to calculate percentage in Python?

There is no such operator in Python, but it is trivial to implement on your own. In practice in computing, percentages are not nearly as useful as a modulo, so no language that I can think of implements one.

What can I use for good quality code coverage for C#/.NET?

See the C# Test Coverage tool from my company, Semantic Designs:

It has very low overhead, handles huge systems of files, intuitive GUI, howing coverage on specific files, and generated report with coverage breakdown at method, class and package levels.

Compiling dynamic HTML strings from database

ng-bind-html-unsafe only renders the content as HTML. It doesn't bind Angular scope to the resulted DOM. You have to use $compile service for that purpose. I created this plunker to demonstrate how to use $compile to create a directive rendering dynamic HTML entered by users and binding to the controller's scope. The source is posted below.

demo.html

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="[email protected]" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Compile dynamic HTML</h1>
    <div ng-controller="MyController">
      <textarea ng-model="html"></textarea>
      <div dynamic="html"></div>
    </div>
  </body>

</html>

script.js

var app = angular.module('app', []);

app.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});

function MyController($scope) {
  $scope.click = function(arg) {
    alert('Clicked ' + arg);
  }
  $scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}

react-router (v4) how to go back?

Hope this will help someone:

import React from 'react';
import * as History from 'history';
import { withRouter } from 'react-router-dom';

interface Props {
  history: History;
}

@withRouter
export default class YourComponent extends React.PureComponent<Props> {

  private onBackClick = (event: React.MouseEvent): void => {
    const { history } = this.props;
    history.goBack();
  };

...

TypeError: can't pickle _thread.lock objects

I had the same problem with Pool() in Python 3.6.3.

Error received: TypeError: can't pickle _thread.RLock objects

Let's say we want to add some number num_to_add to each element of some list num_list in parallel. The code is schematically like this:

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1 

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list)) 
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

    def run_parallel(self, num, shared_new_num_list):
        new_num = num + self.num_to_add # uses class parameter
        shared_new_num_list.append(new_num)

The problem here is that self in function run_parallel() can't be pickled as it is a class instance. Moving this parallelized function run_parallel() out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add and then you have to pass it as an argument.

Solution:

def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
    new_num = num + to_add
    shared_new_num_list.append(new_num)

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

Other suggestions above didn't help me.

Under what conditions is a JSESSIONID created?

JSESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want to get the session, but not create it if it doesn't exist, use request.getSession(false) -- this will return you a session or null. In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that session isn't necessarily created on first request... you and your code are in control when the session is created)

Sessions are per-context:

SRV.7.3 Session Scope

HttpSession objects must be scoped at the application (or servlet context) level. The underlying mechanism, such as the cookie used to establish the session, can be the same for different contexts, but the object referenced, including the attributes in that object, must never be shared between contexts by the container.

(Servlet 2.4 specification)

Update: Every call to JSP page implicitly creates a new session if there is no session yet. This can be turned off with the session='false' page directive, in which case session variable is not available on JSP page at all.

How to make a simple rounded button in Storyboard?

You can connect IBOutlet of yur button from storyboard.

Then you can set corner radius of your button to make it's corner round.

for example, your outlet is myButton then,

Obj - C

 self.myButton.layer.cornerRadius = 5.0 ;

Swift

  myButton.layer.cornerRadius = 5.0

If you want exact round button then your button's width and height must be equal and cornerRadius must be equal to height or width / 2 (half of the width or height).

How do I get the dialer to open with phone number displayed?

As @ashishduh mentioned above, using android:autoLink="phone is also a good solution. But this option comes with one drawback, it doesn't work with all phone number lengths. For instance, a phone number of 11 numbers won't work with this option. The solution is to prefix your phone numbers with the country code.

Example:

08034448845 won't work

but +2348034448845 will

How to cache Google map tiles for offline usage?

On http://www.google.com/earth/media/licensing.html there is a "Mobile" section containing :

Similar to our online terms, if you use our APIs or a mobile device’s native Google Maps implementation (such as on an Android-powered phone or iPhone), no special permission is required, but you must always keep the Google name visible. Offline caching of our content is never allowed.

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

How to fix corrupted git repository?

Here's a script (bash) to automate the first solution by @CodeGnome to restore from a backup (run from the top level of the corrupted repo). The backup doesn't need to be complete, it only needs to have the missing objects.

git fsck 2>&1 | grep -e missing -e invalid | awk '{print $NF}' | sort -u |
    while read entry; do
        mkdir -p .git/objects/${entry:0:2}
        cp ${BACKUP}/objects/${entry:0:2}/${entry:2} .git/objects/${entry:0:2}/${entry:2}
    done

Slack URL to open a channel from browser

Sure you can:

https://<organization>.slack.com/messages/<channel>/

for example: https://tikal.slack.com/messages/general/ (of course that for accessing it, you must be part of the team)

How do I apply CSS3 transition to all properties except background-position?

Here's a solution that also works on Firefox:

transition: all 0.3s ease, background-position 1ms;

I made a small demo: http://jsfiddle.net/aWzwh/

jQuery/JavaScript to replace broken images

I couldn't find a script to suit my needs, so I made a recursive function to check for broken images and attempt to reload them every four seconds until they are fixed.

I limited it to 10 attempts as if it's not loaded by then the image might not be present on server and the function would enter an infinite loop. I am still testing though. Feel free to tweak it :)

var retries = 0;
$.imgReload = function() {
    var loaded = 1;

    $("img").each(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {

            var src = $(this).attr("src");
            var date = new Date();
            $(this).attr("src", src + "?v=" + date.getTime()); //slightly change url to prevent loading from cache
            loaded =0;
        }
    });

    retries +=1;
    if (retries < 10) { // If after 10 retries error images are not fixed maybe because they
                        // are not present on server, the recursion will break the loop
        if (loaded == 0) {
            setTimeout('$.imgReload()',4000); // I think 4 seconds is enough to load a small image (<50k) from a slow server
        }
        // All images have been loaded
        else {
            // alert("images loaded");
        }
    }
    // If error images cannot be loaded  after 10 retries
    else {
        // alert("recursion exceeded");
    }
}

jQuery(document).ready(function() {
    setTimeout('$.imgReload()',5000);
});

In Android, how do I set margins in dp programmatically?

That how I have done in kotlin

fun View.setTopMargin(@DimenRes dimensionResId: Int) {
    (layoutParams as ViewGroup.MarginLayoutParams).topMargin = resources.getDimension(dimensionResId).toInt()
}

Make just one slide different size in Powerpoint

Although you cannot use different sized slides in one PowerPoint file, for the actual presentation you can link several different files together to create a presentation that has different slide sizes.

The process to do so is as follows:

  1. Create the two Powerpoints (with your desired slide dimensions)
    • They need to be properly filled in to have linkable objects and selectable slides
  2. Select an object in the main PowerPoint to act as the hyperlink
  3. Go to "Insert -> Links -> Action"
  4. Select either the "Mouse Click" or the "Mouse Over" tab
  5. Select "Hyperlink to:" and in the drop down menu choose "other PowerPoint Presentation"
  6. Select the slide that you want to link to.
    • Any slide that isn't empty should appear in the "Hyperlink to Slide" dialog box
  7. Repeat the Process in the second Presentation to link back to your main presentation

Reference to Office Support Page where this solution was first posted. https://support.office.com/en-us/article/can-i-use-portrait-and-landscape-slide-orientation-in-the-same-presentation-d8c21781-1fb6-4406-bcd6-25cfac37b5d6?ocmsassetID=HA010099556&CorrelationId=1ac4e97f-bfe6-47b1-bab6-5783e78d126d&ui=en-US&rs=en-US&ad=US

How to find and replace with regex in excel

Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.

To answer your question:

  1. Copy the data from Excel and paste into Google Sheets
  2. Use the find and replace dialog with regex
  3. Copy the data from Google Sheets and paste back into Excel

How do I drag and drop files into an application?

In Windows Forms, set the control's AllowDrop property, then listen for DragEnter event and DragDrop event.

When the DragEnter event fires, set the argument's AllowedEffect to something other than none (e.g. e.Effect = DragDropEffects.Move).

When the DragDrop event fires, you'll get a list of strings. Each string is the full path to the file being dropped.

How to get file_get_contents() to work with HTTPS?

To allow https wrapper:

  • the php_openssl extension must exist and be enabled
  • allow_url_fopen must be set to on

In the php.ini file you should add this lines if not exists:

extension=php_openssl.dll

allow_url_fopen = On

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

How to draw vertical lines on a given plot in matplotlib

matplotlib.pyplot.vlines vs. matplotlib.pyplot.axvline

  • The difference is that vlines accepts 1 or more locations for x, while axvline permits one location.
    • Single location: x=37
    • Multiple locations: x=[37, 38, 39]
  • vlines takes ymin and ymax as a position on the y-axis, while axvline takes ymin and ymax as a percentage of the y-axis range.
    • When passing multiple lines to vlines, pass a list to ymin and ymax.
  • If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.
import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(10, 7))

# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')

# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')

# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')

# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')

# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')

# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')

# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')

plt.show()

enter image description here

Compare DATETIME and DATE ignoring time portion

You can try this one

CONVERT(DATE, GETDATE()) = CONVERT(DATE,'2017-11-16 21:57:20.000')

I test that for MS SQL 2014 by following code

select case when CONVERT(DATE, GETDATE()) = CONVERT(DATE,'2017-11-16 21:57:20.000') then 'ok'
            else '' end

How to search a Git repository by commit message?

git log --grep=<pattern>
            Limit the commits output to ones with log message that matches the
            specified pattern (regular expression).

How to get host name with port from a http or https request

If you want the original URL just use the method as described by jthalborn. If you want to rebuild the url do like David Levesque explained, here is a code snippet for it:

final javax.servlet.http.HttpServletRequest req = (javax.servlet.http.HttpServletRequest) ...;
final int serverPort = req.getServerPort();
if ((serverPort == 80) || (serverPort == 443)) {
  // No need to add the server port for standard HTTP and HTTPS ports, the scheme will help determine it.
  url = String.format("%s://%s/...", req.getScheme(), req.getServerName(), ...);
} else {
  url = String.format("%s://%s:%s...", req.getScheme(), req.getServerName(), serverPort, ...);
}

You still need to consider the case of a reverse-proxy:

Could use constants for the ports but not sure if there is a reliable source for them, default ports:

Most developers will know about port 80 and 443 anyways, so constants are not that helpful.

Also see this similar post.

How do I implement __getattribute__ without an infinite recursion error?

How is the __getattribute__ method used?

It is called before the normal dotted lookup. If it raises AttributeError, then we call __getattr__.

Use of this method is rather rare. There are only two definitions in the standard library:

$ grep -Erl  "def __getattribute__\(self" cpython/Lib | grep -v "/test/"
cpython/Lib/_threading_local.py
cpython/Lib/importlib/util.py

Best Practice

The proper way to programmatically control access to a single attribute is with property. Class D should be written as follows (with the setter and deleter optionally to replicate apparent intended behavior):

class D(object):
    def __init__(self):
        self.test2=21

    @property
    def test(self):
        return 0.

    @test.setter
    def test(self, value):
        '''dummy function to avoid AttributeError on setting property'''

    @test.deleter
    def test(self):
        '''dummy function to avoid AttributeError on deleting property'''

And usage:

>>> o = D()
>>> o.test
0.0
>>> o.test = 'foo'
>>> o.test
0.0
>>> del o.test
>>> o.test
0.0

A property is a data descriptor, thus it is the first thing looked for in the normal dotted lookup algorithm.

Options for __getattribute__

You several options if you absolutely need to implement lookup for every attribute via __getattribute__.

  • raise AttributeError, causing __getattr__ to be called (if implemented)
  • return something from it by
    • using super to call the parent (probably object's) implementation
    • calling __getattr__
    • implementing your own dotted lookup algorithm somehow

For example:

class NoisyAttributes(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self, name):
        print('getting: ' + name)
        try:
            return super(NoisyAttributes, self).__getattribute__(name)
        except AttributeError:
            print('oh no, AttributeError caught and reraising')
            raise
    def __getattr__(self, name):
        """Called if __getattribute__ raises AttributeError"""
        return 'close but no ' + name    


>>> n = NoisyAttributes()
>>> nfoo = n.foo
getting: foo
oh no, AttributeError caught and reraising
>>> nfoo
'close but no foo'
>>> n.test
getting: test
20

What you originally wanted.

And this example shows how you might do what you originally wanted:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return super(D, self).__getattribute__(name)

And will behave like this:

>>> o = D()
>>> o.test = 'foo'
>>> o.test
0.0
>>> del o.test
>>> o.test
0.0
>>> del o.test

Traceback (most recent call last):
  File "<pyshell#216>", line 1, in <module>
    del o.test
AttributeError: test

Code review

Your code with comments. You have a dotted lookup on self in __getattribute__. This is why you get a recursion error. You could check if name is "__dict__" and use super to workaround, but that doesn't cover __slots__. I'll leave that as an exercise to the reader.

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:      #   v--- Dotted lookup on self in __getattribute__
            return self.__dict__[name]

>>> print D().test
0.0
>>> print D().test2
...
RuntimeError: maximum recursion depth exceeded in cmp

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

In Visual Studio 2017 or 2015:

Go to the Solution right click on solution then select Properties-> select all the Configuration-> Debug then click OK. After that Rebuild and Run,this solution worked for me.

How do I unlock a SQLite database?

the SQLite db files are just files, so the first step would be to make sure it isn't read-only. The other thing to do is to make sure that you don't have some sort of GUI SQLite DB viewer with the DB open. You could have the DB open in another shell, or your code may have the DB open. Typically you would see this if a different thread, or application such as SQLite Database Browser has the DB open for writing.

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

If it's working from Postman, try new Spring version, becouse the 'org.springframework.boot' 2.2.2.RELEASE version can throw "Required request body content is missing" exception.
Try 2.2.6.RELEASE version.

Prevent RequireJS from Caching Required Scripts

The urlArgs solution has problems. Unfortunately you cannot control all proxy servers that might be between you and your user's web browser. Some of these proxy servers can be unfortunately configured to ignore URL parameters when caching files. If this happens, the wrong version of your JS file will be delivered to your user.

I finally gave up and implemented my own fix directly into require.js. If you are willing to modify your version of the requirejs library, this solution might work for you.

You can see the patch here:

https://github.com/jbcpollak/requirejs/commit/589ee0cdfe6f719cd761eee631ce68eee09a5a67

Once added, you can do something like this in your require config:

var require = {
    baseUrl: "/scripts/",
    cacheSuffix: ".buildNumber"
}

Use your build system or server environment to replace buildNumber with a revision id / software version / favorite color.

Using require like this:

require(["myModule"], function() {
    // no-op;
});

Will cause require to request this file:

http://yourserver.com/scripts/myModule.buildNumber.js

On our server environment, we use url rewrite rules to strip out the buildNumber, and serve the correct JS file. This way we don't actually have to worry about renaming all of our JS files.

The patch will ignore any script that specifies a protocol, and it will not affect any non-JS files.

This works well for my environment, but I realize some users would prefer a prefix rather than a suffix, it should be easy to modify my commit to suit your needs.

Update:

In the pull request discussion, the requirejs author suggest this might work as a solution to prefix the revision number:

var require = {
    baseUrl: "/scripts/buildNumber."
};

I have not tried this, but the implication is that this would request the following URL:

http://yourserver.com/scripts/buildNumber.myModule.js

Which might work very well for many people who can use a prefix.

Here are some possible duplicate questions:

RequireJS and proxy caching

require.js - How can I set a version on required modules as part of the URL?

How to deep watch an array in angularjs?

Setting the objectEquality parameter (third parameter) of the $watch function is definitely the correct way to watch ALL properties of the array.

$scope.$watch('columns', function(newVal) {
    alert('columns changed');
},true); // <- Right here

Piran answers this well enough and mentions $watchCollection as well.

More Detail

The reason I'm answering an already answered question is because I want to point out that wizardwerdna's answer is not a good one and should not be used.

The problem is that the digests do not happen immediately. They have to wait until the current block of code has completed before executing. Thus, watch the length of an array may actually miss some important changes that $watchCollection will catch.

Assume this configuration:

$scope.testArray = [
    {val:1},
    {val:2}
];

$scope.$watch('testArray.length', function(newLength, oldLength) {
    console.log('length changed: ', oldLength, ' -> ', newLength);
});

$scope.$watchCollection('testArray', function(newArray) {
    console.log('testArray changed');
});

At first glance, it may seem like these would fire at the same time, such as in this case:

function pushToArray() {
    $scope.testArray.push({val:3});
}
pushToArray();

// Console output
// length changed: 2 -> 3
// testArray changed

That works well enough, but consider this:

function spliceArray() {
    // Starting at index 1, remove 1 item, then push {val: 3}.
    $testArray.splice(1, 1, {val: 3});
}
spliceArray();

// Console output
// testArray changed

Notice that the resulting length was the same even though the array has a new element and lost an element, so as watch as the $watch is concerned, length hasn't changed. $watchCollection picked up on it, though.

function pushPopArray() {
    $testArray.push({val: 3});
    $testArray.pop();
}
pushPopArray();

// Console output
// testArray change

The same result happens with a push and pop in the same block.

Conclusion

To watch every property in the array, use a $watch on the array iteself with the third parameter (objectEquality) included and set to true. Yes, this is expensive but sometimes necessary.

To watch when object enter/exit the array, use a $watchCollection.

Do NOT use a $watch on the length property of the array. There is almost no good reason I can think of to do so.

git stash blunder: git stash pop and ended up with merge conflicts

Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.

See commit ed178ef by Jeff King (peff), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster -- in commit 05c3967, 19 May 2015)

Note: This has been reverted. See below.

stash: require a clean index to apply/pop

Problem

If you have staged contents in your index and run "stash apply/pop", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.

In other words:

"git stash pop/apply" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.

Solution

We can make this safer by refusing to apply when there are staged changes.

That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:

Cannot apply stash: Your index contains uncommitted changes.

Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before git stash apply/pop) with a git reset --hard.


See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfb539b, 24 Jun 2015)

That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.

Unfortunately, this hurts some common workflows around "git stash -k", like:

git add -p       ;# (1) stage set of proposed changes
git stash -k     ;# (2) get rid of everything else
make test        ;# (3) make sure proposal is reasonable
git stash apply  ;# (4) restore original working tree

If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).

How to add url parameter to the current url?

It is not elegant but possible to do it as one-liner <a> element

_x000D_
_x000D_
<a href onclick="event.preventDefault(); location+='&like=like'">Like</a>
_x000D_
_x000D_
_x000D_

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

You can use this

if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) 
    {
        // for iOS 8
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

        [application registerForRemoteNotifications];
    }
    else
    {
        // for iOS < 8
        [application registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
    }

    // RESET THE BADGE COUNT 
    application.applicationIconBadgeNumber = 0;

How to convert data.frame column from Factor to numeric

As an alternative to $dollarsign notation, use a within block:

breast <- within(breast, {
  class <- as.numeric(as.character(class))
})

Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class) will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.

Large Numbers in Java

import java.math.BigInteger;
import java.util.*;
class A
{
    public static void main(String args[])
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter The First Number= ");
        String a=in.next();
        System.out.print("Enter The Second Number= ");
        String b=in.next();

        BigInteger obj=new BigInteger(a);
        BigInteger obj1=new BigInteger(b);
        System.out.println("Sum="+obj.add(obj1));
    }
}

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

Android's default system path of your application database is /data/data/YOUR_PACKAGE/databases/YOUR_DB_NAME

Your logcat clearly says Failed to open database '/data/data/com.example.quotes/databasesQuotesdb'

Which means there is no file present on the given path or You have given the wrong path for the data file. As I can see there should be "/" after databases folder.

Your DB_PATH variable should end with a "/".

private static String DB_PATH = "/data/data/com.example.quotes/databases/";

Your correct path will be now "/data/data/com.example.quotes/databases/Quotesdb"

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

In case if you are able to compile mvn compile the project successful from terminal but not from Eclipse check out Window > Preferences >Installed JREs, make sure you have selected JRE that is under JDK (check out the paths of 2 different JRE's in pic), as Maven needs JDK to compile you need to add it.

Installed JREs

How to open a different activity on recyclerView item onclick

This question has been asked long ago but none of the answers above helped me out, though Milad Moosavi`s answer was very close. To open a new activity from a certain position on the recycler view, the following code may help:


    @Override
    public void onBindViewHolder(@NonNull TripViewHolder holder, int position) {
        Trip currentTrip = trips.get(position);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), EditTrip.class);
                v.getContext().startActivity(intent);
            }
        });

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent(v.getContext(), ReadTripActivity.class);
                v.getContext().startActivity(intent);

                return false;
            }
        });
    }

JUnit 5: How to assert an exception is thrown?

Actually I think there is a error in the documentation for this particular example. The method that is intended is expectThrows

public static void assertThrows(
public static <T extends Throwable> T expectThrows(

Detecting an undefined object property

There is a very easy and simple way.

You can use optional chaining:

x = {prop:{name:"sajad"}}

console.log(x.prop?.name) // Output is: "sajad"
console.log(x.prop?.lastName) // Output is: undefined

or

if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error

You can use optional chaining even for functions or arrays.

As of mid-2020 this is not universally implemented. Check the documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

What is the difference between % and %% in a cmd file?

In DOS you couldn't use environment variables on the command line, only in batch files, where they used the % sign as a delimiter. If you wanted a literal % sign in a batch file, e.g. in an echo statement, you needed to double it.

This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your % signs in a .cmd file.

Download Excel file via AJAX MVC

I was recently able to accomplish this in MVC (although there was no need to use AJAX) without creating a physical file and thought I'd share my code:

Super simple JavaScript function (datatables.net button click triggers this):

function getWinnersExcel(drawingId) {
    window.location = "/drawing/drawingwinnersexcel?drawingid=" + drawingId;
}

C# Controller code:

    public FileResult DrawingWinnersExcel(int drawingId)
    {
        MemoryStream stream = new MemoryStream(); // cleaned up automatically by MVC
        List<DrawingWinner> winnerList = DrawingDataAccess.GetWinners(drawingId); // simple entity framework-based data retrieval
        ExportHelper.GetWinnersAsExcelMemoryStream(stream, winnerList, drawingId);

        string suggestedFilename = string.Format("Drawing_{0}_Winners.xlsx", drawingId);
        return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", suggestedFilename);
    }

In the ExportHelper class I do use a 3rd party tool (GemBox.Spreadsheet) to generate the Excel file and it has a Save to Stream option. That being said, there are a number of ways to create Excel files that can easily be written to a memory stream.

public static class ExportHelper
{
    internal static void GetWinnersAsExcelMemoryStream(MemoryStream stream, List<DrawingWinner> winnerList, int drawingId)
    {

        ExcelFile ef = new ExcelFile();

        // lots of excel worksheet building/formatting code here ...

        ef.SaveXlsx(stream);
        stream.Position = 0; // reset for future read

     }
}

In IE, Chrome, and Firefox, the browser prompts to download the file and no actual navigation occurs.

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Just figured this out after trying numerous things. What finally did it for me was adding require('dotenv').config() to my .sequelizerc file. Apparently sequelize-cli doesn't read env variables.

How to get the currently logged in user's user id in Django?

You can access Current logged in user by using the following code:

request.user.id

How to for each the hashmap?

I generally do the same as cx42net, but I don't explicitly create an Entry.

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
for (String key : selects.keySet())
{
    HashMap<innerKey, String> boxHolder = selects.get(key);
    ComboBox cb = new ComboBox();
    for (InnerKey innerKey : boxHolder.keySet())
    {
        cb.items.add(boxHolder.get(innerKey));
    }
}

This just seems the most intuitive to me, I think I'm prejudiced against iterating over the values of a map.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

Update your pom.xml

<dependency>
  <groupId>asm</groupId>
  <artifactId>asm</artifactId>
  <version>3.1</version>
</dependency>

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

Can gcc output C code after preprocessing?

Suppose we have a file as Message.cpp or a .c file

Steps 1: Preprocessing (Argument -E )

g++ -E .\Message.cpp > P1

P1 file generated has expanded macros and header file contents and comments are stripped off.

Step 2: Translate Preprocessed file to assembly (Argument -S). This task is done by compiler

g++ -S .\Message.cpp

An assembler (ASM) is generated (Message.s). It has all the assembly code.

Step 3: Translate assembly code to Object code. Note: Message.s was generated in Step2. g++ -c .\Message.s

An Object file with the name Message.o is generated. It is the binary form.

Step 4: Linking the object file. This task is done by linker

g++ .\Message.o -o MessageApp

An exe file MessageApp.exe is generated here.

#include <iostream>
using namespace std;

 //This a sample program
  int main()
{
cout << "Hello" << endl;
 cout << PQR(P,K) ;
getchar();
return 0;
}

forEach is not a function error with JavaScript array

A more naive version, at least you're sure that it'll work on all devices, without conversion and ES6 :

const children = parent.children;
for (var i = 0; i < children.length; i++){
    console.log(children[i]);
}

https://jsfiddle.net/swb12kqn/5/

Convert date to day name e.g. Mon, Tue, Wed

You can not use strtotime as your time format is not within the supported date and time formats of PHP.

Therefor, you have to create a valid date format first making use of createFromFormat function.

//creating a valid date format
$newDate = DateTime::createFromFormat('YmdHi', $longdate);

//formating the date as we want
$finalDate = $newDate->format('D'); 

How do I make Java register a string input with spaces?

in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Here is a simple mail sending code with attachment

try  
{  
    SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);  
    mailServer.EnableSsl = true;  

    mailServer.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword");  

    string from = "[email protected]";  
    string to = "[email protected]";  
    MailMessage msg = new MailMessage(from, to);  
    msg.Subject = "Enter the subject here";  
    msg.Body = "The message goes here.";
    msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
    mailServer.Send(msg);  
}  
catch (Exception ex)  
{  
    Console.WriteLine("Unable to send email. Error : " + ex);  
}

Read more Sending emails with attachment in C#

C programming: Dereferencing pointer to incomplete type error

How did you actually define the structure? If

struct {
  char name[32];
  int  size;
  int  start;
  int  popularity;
} stasher_file;

is to be taken as type definition, it's missing a typedef. When written as above, you actually define a variable called stasher_file, whose type is some anonymous struct type.

Try

typedef struct { ... } stasher_file;

(or, as already mentioned by others):

struct stasher_file { ... };

The latter actually matches your use of the type. The first form would require that you remove the struct before variable declarations.

A potentially dangerous Request.Path value was detected from the client (*)

If you're using .NET 4.0 you should be able to allow these urls via the web.config

<system.web>
    <httpRuntime 
            requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,:,\,?" />
</system.web>

Note, I've just removed the asterisk (*), the original default string is:

<httpRuntime 
          requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,:,\,?" />

See this question for more details.

Laravel check if collection is empty

To determine if there are any results you can do any of the following:

if ($mentor->first()) { } 
if (!$mentor->isEmpty()) { }
if ($mentor->count()) { }
if (count($mentor)) { }
if ($mentor->isNotEmpty()) { }

Notes / References

->first()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_first

isEmpty() https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_isEmpty

->count()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

count($mentors) works because the Collection implements Countable and an internal count() method:

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

isNotEmpty()

https://laravel.com/docs/5.7/collections#method-isnotempty

So what you can do is :

if (!$mentors->intern->employee->isEmpty()) { }

How to make a flat list out of list of lists?

you can use list extend method, it shows to be the fastest:

flat_list = []
for sublist in l:
    flat_list.extend(sublist)

performance:

import functools
import itertools
import numpy
import operator
import perfplot



def functools_reduce_iconcat(a):
    return functools.reduce(operator.iconcat, a, [])


def itertools_chain(a):
    return list(itertools.chain.from_iterable(a))


def numpy_flat(a):
    return list(numpy.array(a).flat)


def extend(a):
    n = []

    list(map(n.extend, a))

    return n 


perfplot.show(
    setup=lambda n: [list(range(10))] * n,
    kernels=[
        functools_reduce_iconcat, extend,itertools_chain, numpy_flat
        ],
    n_range=[2**k for k in range(16)],
    xlabel='num lists',
    )

output: enter image description here

TypeError: 'NoneType' object is not iterable in Python

Explanation of error: 'NoneType' object is not iterable

In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

Iterating over a variable that has value None fails:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

Python methods return NoneType if they don't return a value:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

You need to check your looping constructs for NoneType like this:

a = None 
print(a is None)              #prints True
print(a is not None)          #prints False
print(a == None)              #prints True
print(a != None)              #prints False
print(isinstance(a, object))  #prints True
print(isinstance(a, str))     #prints False

Guido says only use is to check for None because is is more robust to identity checking. Don't use equality operations because those can spit bubble-up implementationitis of their own. Python's Coding Style Guidelines - PEP-008

NoneTypes are Sneaky, and can sneak in from lambdas:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType is not a valid keyword:

a = NoneType     #NameError: name 'NoneType' is not defined

Concatenation of None and a string:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

What's going on here?

Python's interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__ method on the None.

None has no __iter__ method defined, so Python's virtual machine tells you what it sees: that NoneType has no __iter__ method.

This is why Python's duck-typing ideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.

Java or C++ doesn't have these problems because such a program wouldn't be allowed to compile since you haven't defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.

Command not found after npm install in zsh

for macOS users: consider using .profile instead of .bash_profile. You may still need to manually add it to ~/.zshrc:

source $HOME/.profile

Note that there is no such file by default! Quoting slhck https://superuser.com/a/473103:

Anyway, you can simply create the file if it doesn't exist and open it in a text editor.

touch ~/.profile
open -e !$

The added value is that it feels good man to use a single file to set up the environment, regardless of the shell used. Loading a bash config file in zsh felt awkward.

Quoting an accepted answer by Cos https://stackoverflow.com/a/415444/2445063

.profile is simply the login script filename originally used by /bin/sh. bash, being generally backwards-compatible with /bin/sh, will read .profile if one exists

Following Filip Ekberg's research / opinion https://stackoverflow.com/a/415410/2445063

.profile is the equivalent of .bash_profile for the root. I think the name is changed to let other shells (csh, sh, tcsh) use it as well. (you don't need one as a user)

getting back to slhck, a note of attention regarding bash:

(…) once you create a file called ~/.bash_profile, your ~/.profile will not be read anymore.

how to delete all cookies of my website in php

The provided Answers did not solve my problem,

It did not:

  1. Remove parent domain cookies (from a.b.c; remove b.c; cookies),
  2. Remove cookies from a higher path other then root.

My script does, see.

<?php function unset_cookie($name)
{
    $host = $_SERVER['HTTP_HOST'];
    $domain = explode(':', $host)[0];

    $uri = $_SERVER['REQUEST_URI'];
    $uri = rtrim(explode('?', $uri)[0], '/');

    if ($uri && !filter_var('file://' . $uri, FILTER_VALIDATE_URL)) {
        throw new Exception('invalid uri: ' . $uri);
    }

    $parts = explode('/', $uri);

    $cookiePath = '';
    foreach ($parts as $part) {
        $cookiePath = '/'.ltrim($cookiePath.'/'.$part, '//');

        setcookie($name, '', 1, $cookiePath);

        $_domain = $domain;
        do {
            setcookie($name, '', 1, $cookiePath, $_domain);
        } while (strpos($_domain, '.') !== false && $_domain = substr($_domain, 1 + strpos($_domain, '.')));
    }
}

It is not the most pretty/safe/optimal solution, so use this only if you do not known the cookie-path and/or cookie-domain's. Or use the idea in order to create your version.

Get Specific Columns Using “With()” Function in Laravel Eloquent

I came across this issue but with a second layer of related objects. @Awais Qarni's answer holds up with the inclusion of the appropriate foreign key in the nested select statement. Just as an id is required in the first nested select statement to reference the related model, the foreign key is required to reference the second degree of related models; in this example the Company model.

Post::with(['user' => function ($query) {
        $query->select('id','company_id', 'username');
    }, 'user.company' => function ($query) {
        $query->select('id', 'name');
    }])->get();

Additionally, if you want to select specific columns from the Post model you would need to include the user_id column in the select statement in order to reference it.

Post::with(['user' => function ($query) {
        $query->select('id', 'username');
    }])
    ->select('title', 'content', 'user_id')
    ->get();

Input mask for numeric and decimal

Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.

How to find foreign key dependencies in SQL Server?

This query will return details about foreign keys in a table, it supports multiple column keys.

    SELECT *
    FROM
    (
    SELECT 
    T1.constraint_name ConstraintName,
    T2.COLUMN_NAME ColumnName,
    T3.TABLE_NAME RefTableName, 
    T3.COLUMN_NAME RefColumnName,
    T1.MATCH_OPTION MatchOption, 
    T1.UPDATE_RULE UpdateRule, 
    T1.DELETE_RULE DeleteRule
    FROM 
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS T1
    INNER JOIN
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE T2 
    ON T1.CONSTRAINT_NAME = T2.CONSTRAINT_NAME
    INNER JOIN
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE T3 
    ON T1.UNIQUE_CONSTRAINT_NAME = T3.CONSTRAINT_NAME 
    AND T2.ORDINAL_POSITION = T3.ORDINAL_POSITION) A
    WHERE A.ConstraintName = 'table_name'

How do I specify different layouts for portrait and landscape orientations?

Create a layout-land directory and put the landscape version of your layout XML file in that directory.

Xcode doesn't see my iOS device but iTunes does

Xcode 10.2.1 was not recognizing my ipad mini. I unplugged and rebooted the mini and it became visible.

Use underscore inside Angular controllers

When you include Underscore, it attaches itself to the window object, and so is available globally.

So you can use it from Angular code as-is.

You can also wrap it up in a service or a factory, if you'd like it to be injected:

var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function($window) {
  return $window._; // assumes underscore has already been loaded on the page
}]);

And then you can ask for the _ in your app's module:

// Declare it as a dependency of your module
var app = angular.module('app', ['underscore']);

// And then inject it where you need it
app.controller('Ctrl', function($scope, _) {
  // do stuff
});

How to create a dump with Oracle PL/SQL Developer?

Just to keep this up to date:

The current version of SQLDeveloper has an export tool (Tools > Database Export) that will allow you to dump a schema to a file, with filters for object types, object names, table data etc.

It's a fair amount easier to set-up and use than exp and imp if you're used to working in a GUI environment, but not as versatile if you need to use it for scripting anything.

How do I put a clear button inside my HTML text input box like the iPhone does?

I got a creative solution I think you are looking for

_x000D_
_x000D_
$('#clear').click(function() {_x000D_
  $('#input-outer input').val('');_x000D_
});
_x000D_
body {_x000D_
  font-family: "Tahoma";_x000D_
}_x000D_
#input-outer {_x000D_
  height: 2em;_x000D_
  width: 15em;_x000D_
  border: 1px #e7e7e7 solid;_x000D_
  border-radius: 20px;_x000D_
}_x000D_
#input-outer input {_x000D_
  height: 2em;_x000D_
  width: 80%;_x000D_
  border: 0px;_x000D_
  outline: none;_x000D_
  margin: 0 0 0 10px;_x000D_
  border-radius: 20px;_x000D_
  color: #666;_x000D_
}_x000D_
#clear {_x000D_
  position: relative;_x000D_
  float: right;_x000D_
  height: 20px;_x000D_
  width: 20px;_x000D_
  top: 5px;_x000D_
  right: 5px;_x000D_
  border-radius: 20px;_x000D_
  background: #f1f1f1;_x000D_
  color: white;_x000D_
  font-weight: bold;_x000D_
  text-align: center;_x000D_
  cursor: pointer;_x000D_
}_x000D_
#clear:hover {_x000D_
  background: #ccc;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="input-outer">_x000D_
  <input type="text">_x000D_
  <div id="clear">_x000D_
    X_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/qdesign/xn9eogmx/1/

What are the main performance differences between varchar and nvarchar SQL Server data types?

For your application, nvarchar is fine because the database size is small. Saying "always use nvarchar" is a vast oversimplification. If you're not required to store things like Kanji or other crazy characters, use VARCHAR, it'll use a lot less space. My predecessor at my current job designed something using NVARCHAR when it wasn't needed. We recently switched it to VARCHAR and saved 15 GB on just that table (it was highly written to). Furthermore, if you then have an index on that table and you want to include that column or make a composite index, you've just made your index file size larger.

Just be thoughtful in your decision; in SQL development and data definitions there seems to rarely be a "default answer" (other than avoid cursors at all costs, of course).

How to drop all tables from the database with manage.py CLI in Django?

It is better to use ./manage.py sqlflush | ./manage.py dbshell because sqlclear requires app to flush.

How does @synchronized lock/unlock in Objective-C?

Actually

{
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

transforms directly into:

// needs #import <objc/objc-sync.h>
{
  objc_sync_enter(self)
    id retVal = [[myString retain] autorelease];
  objc_sync_exit(self);
  return retVal;
}

This API available since iOS 2.0 and imported using...

#import <objc/objc-sync.h>

jQuery UI Dialog Box - does not open after being closed

The jQuery documentation has a link to this article 'Basic usage of the jQuery UI dialog' that explains this situation and how to resolve it.

VueJS conditionally add an attribute for an element

You can pass boolean by coercing it, put !! before the variable.

let isRequired = '' || null || undefined
<input :required="!!isRequired"> // it will coerce value to respective boolean 

But I would like to pull your attention for the following case where the receiving component has defined type for props. In that case, if isRequired has defined type to be string then passing boolean make it type check fails and you will get Vue warning. To fix that you may want to avoid passing that prop, so just put undefined fallback and the prop will not sent to component

let isValue = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>

Explanation

I have been through the same problem, and tried above solutions !! Yes, I don't see the prop but that actually does not fulfils what required here.

My problem -

let isValid = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist': false"
/>

In the above case, what I expected is not having my-prop get passed to the child component - <any-conponent/> I don't see the prop in DOM but In my <any-component/> component, an error pops out of prop type check failure. As in the child component, I am expecting my-prop to be a String but it is boolean.

myProp : {
 type: String,
 required: false,
 default: ''
}

Which means that child component did receive the prop even if it is false. Tweak here is to let the child component to take the default-value and also skip the check. Passed undefined works though!

<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
 

This works and my child prop is having the default value.

How can I stop python.exe from closing immediately after I get an output?

Python files are executables, which means that you can run them directly from command prompt(assuming you have windows). You should be able to just enter in the directory, and then run the program. Also, (assuming you have python 3), you can write:

input("Press enter to close program")

and you can just press enter when you've read your results.

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

The entity which has the table with foreign key in the database is the owning entity and the other table, being pointed at, is the inverse entity.

laravel 5.3 new Auth::routes()

This worked for me with Laravel 5.6.

In the file web.php, just replace:

Auth::routes();

By:

//Auth::routes();
// Authentication Routes...
Route::get('admin/login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('admin/login', 'Auth\LoginController@login');
Route::post('admin/logout', 'Auth\LoginController@logout')->name('logout');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');

And remove the Register link in the two files below:

welcome.blade.php
layouts/app.blade.php

Jenkins / Hudson environment variables

Michael,

Two things:

When Jenkins connects to a computer, it goes to the sh shell, and not the bash shell (at least this is what I have noticed - I may be wrong). So any changes you make to $PATH in your bashrc file are not considered.

Also, any changes you make to $PATH in your local shell (one that you personally ssh into) will not show up in Jenkins.

To change the path that Jenkins uses, you have two options (AFAIK):

1) Edit your /etc/profile file and add the paths that you want there

2) Go to the configuration page of your slave, and add environment variable PATH, with value: $PATH:/followed-by/paths/you/want/to/add

If you use the second option, your System Information will still not show it, but your builds will see the added paths.

How can I get the first two digits of a number?

Comparing the O(n) time solution with the "constant time" O(1) solution provided in other answers goes to show that if the O(n) algorithm is fast enough, n may have to get very large before it is slower than a slow O(1).

The strings version is approx. 60% faster than the "maths" version for numbers of 20 or fewer digits. They become closer only when then number of digits approaches 200 digits

# the "maths" version
import math

def first_n_digits1(num, n):
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

%timeit first_n_digits1(34523452452, 2)
1.21 µs ± 75 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits1(34523452452, 8)
1.24 µs ± 47.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 22 digits
%timeit first_n_digits1(3423234239472523452452, 2)
1.33 µs ± 59.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits1(3423234239472523452452, 15)
1.23 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 196 digits
%timeit first_n_digits1(3423234239472523409283475908723908723409872390871243908172340987123409871234012089172340987734507612340981344509873123401234670350981234098123140987314509812734091823509871345109871234098172340987125988123452452, 39)
1.86 µs ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# The "string" verions
def first_n_digits2(num, n):
    return int(str(num)[:n])

%timeit first_n_digits2(34523452452, 2)
744 ns ± 28.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits2(34523452452, 8)
768 ns ± 42.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 22 digits
%timeit first_n_digits2(3423234239472523452452, 2)
767 ns ± 33.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits2(3423234239472523452452, 15)
830 ns ± 55.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 196 digits
%timeit first_n_digits2(3423234239472523409283475908723908723409872390871243908098712340987123401208917234098773450761234098134450987312340123467035098123409812314098734091823509871345109871234098172340987125988123452452, 39)
1.87 µs ± 140 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

I experienced this error while importing component like:

import React, { Components } from 'react';

instead of

import React, { Component } from 'react';

How to call a VbScript from a Batch File without opening an additional command prompt

If you want to fix vbs associations type

regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll

Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.

Big difference is functions and subs are both called using brackets rather than just functions.

So the compilers are installed on all computers with .NET installed.

See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.

How can I convert a VBScript to an executable (EXE) file?

Currency formatting in Python

Simple python code!

def format_us_currency(value):
    value=str(value)
    if value.count(',')==0:
        b,n,v='',1,value
        value=value[:value.rfind('.')]
        for i in value[::-1]:
            b=','+i+b if n==3 else i+b
            n=1 if n==3 else n+1
        b=b[1:] if b[0]==',' else b
        value=b+v[v.rfind('.'):]
    return '$'+(value.rstrip('0').rstrip('.') if '.' in value else value)

How do I remove all non-ASCII characters with regex and Notepad++?

Another good trick is to go into UTF8 mode in your editor so that you can actually see these funny characters and delete them yourself.

How to comment out particular lines in a shell script

You have to rely on '#' but to make the task easier in vi you can perform the following (press escape first):

:10,20 s/^/#

with 10 and 20 being the start and end line numbers of the lines you want to comment out

and to undo when you are complete:

:10,20 s/^#//

How to remove a variable from a PHP session array

If you want to remove or unset all $_SESSION 's then try this

session_destroy();

If you want to remove specific $_SESSION['name'] then try this

session_unset('name');

How to split the screen with two equal LinearLayouts?

Just putting it out there:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF0000"
    android:weightSum="4"
    android:padding="5dp"> <!-- to show what the parent is -->
    <LinearLayout
        android:background="#0000FF"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="2" />
    <LinearLayout
        android:background="#00FF00"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1" />
</LinearLayout>

How to set a CheckBox by default Checked in ASP.Net MVC

@Html.CheckBox("yourId", true, new { value = Model.Ischecked })

This will certainly work

Concatenating Files And Insert New Line In Between Files

If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:

cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

download gradle from here for your OS and extract the file and paste the inner folder into installLocation/gradle

than in Android Studio Goto File > Settings > bulid ,exec,deployment > gradle and choose local gradle option and provide the file path of your new downloaded gradle and hit ok it works :)

Fragments onResume from back stack

A little improved and wrapped into a manager solution.

Things to keep in mind. FragmentManager is not a singleton, it manages only Fragments within Activity, so in every activity it will be new. Also, this solution so far doesn't take ViewPager into account that calls setUserVisibleHint() method helping to control visiblity of Fragments.

Feel free to use following classes when dealing with this issue (uses Dagger2 injection). Call in Activity:

//inject FragmentBackstackStateManager instance to myFragmentBackstackStateManager
FragmentManager fragmentManager = getSupportFragmentManager(); 
myFragmentBackstackStateManager.apply(fragmentManager);

FragmentBackstackStateManager.java:

@Singleton
public class FragmentBackstackStateManager {

    private FragmentManager fragmentManager;

    @Inject
    public FragmentBackstackStateManager() {
    }

    private BackstackCallback backstackCallbackImpl = new BackstackCallback() {
        @Override
        public void onFragmentPushed(Fragment parentFragment) {
            parentFragment.onPause();
        }

        @Override
        public void onFragmentPopped(Fragment parentFragment) {
            parentFragment.onResume();
        }
    };

    public FragmentBackstackChangeListenerImpl getListener() {
        return new FragmentBackstackChangeListenerImpl(fragmentManager, backstackCallbackImpl);
    }

    public void apply(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
        fragmentManager.addOnBackStackChangedListener(getListener());
    }
}

FragmentBackstackChangeListenerImpl.java:

public class FragmentBackstackChangeListenerImpl implements FragmentManager.OnBackStackChangedListener {

    private int lastBackStackEntryCount = 0;
    private final FragmentManager fragmentManager;
    private final BackstackCallback backstackChangeListener;

    public FragmentBackstackChangeListenerImpl(FragmentManager fragmentManager, BackstackCallback backstackChangeListener) {
        this.fragmentManager = fragmentManager;
        this.backstackChangeListener = backstackChangeListener;
        lastBackStackEntryCount = fragmentManager.getBackStackEntryCount();
    }

    private boolean wasPushed(int backStackEntryCount) {
        return lastBackStackEntryCount < backStackEntryCount;
    }

    private boolean wasPopped(int backStackEntryCount) {
        return lastBackStackEntryCount > backStackEntryCount;
    }

    private boolean haveFragments() {
        List<Fragment> fragmentList = fragmentManager.getFragments();
        return fragmentList != null && !fragmentList.isEmpty();
    }


    /**
     * If we push a fragment to backstack then parent would be the one before => size - 2
     * If we pop a fragment from backstack logically it should be the last fragment in the list, but in Android popping a fragment just makes list entry null keeping list size intact, thus it's also size - 2
     *
     * @return fragment that is parent to the one that is pushed to or popped from back stack
     */
    private Fragment getParentFragment() {
        List<Fragment> fragmentList = fragmentManager.getFragments();
        return fragmentList.get(Math.max(0, fragmentList.size() - 2));
    }

    @Override
    public void onBackStackChanged() {
        int currentBackStackEntryCount = fragmentManager.getBackStackEntryCount();
        if (haveFragments()) {
            Fragment parentFragment = getParentFragment();

            //will be null if was just popped and was last in the stack
            if (parentFragment != null) {
                if (wasPushed(currentBackStackEntryCount)) {
                    backstackChangeListener.onFragmentPushed(parentFragment);
                } else if (wasPopped(currentBackStackEntryCount)) {
                    backstackChangeListener.onFragmentPopped(parentFragment);
                }
            }
        }

        lastBackStackEntryCount = currentBackStackEntryCount;
    }
}

BackstackCallback.java:

public interface BackstackCallback {
    void onFragmentPushed(Fragment parentFragment);

    void onFragmentPopped(Fragment parentFragment);
}

Python: How to use RegEx in an if statement?

The REPL makes it easy to learn APIs. Just run python, create an object and then ask for help:

$ python
>>> import re
>>> help(re.compile(r''))

at the command line shows, among other things:

search(...)

search(string[, pos[, endpos]]) --> match object or None. Scan through string looking for a match, and return a corresponding MatchObject instance. Return None if no position in the string matches.

so you can do

regex = re.compile(regex_txt, re.IGNORECASE)

match = regex.search(content)  # From your file reading code.
if match is not None:
  # use match

Incidentally,

regex_txt = "facebook.com"

has a . which matches any character, so re.compile("facebook.com").search("facebookkcom") is not None is true because . matches any character. Maybe

regex_txt = r"(?i)facebook\.com"

The \. matches a literal "." character instead of treating . as a special regular expression operator.

The r"..." bit means that the regular expression compiler gets the escape in \. instead of the python parser interpreting it.

The (?i) makes the regex case-insensitive like re.IGNORECASE but self-contained.

How to get Bitmap from an Uri?

Full method to get image uri from mobile gallery.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                Uri filePath = data.getData();

     try { //Getting the Bitmap from Gallery
           Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
           rbitmap = getResizedBitmap(bitmap, 250);//Setting the Bitmap to ImageView
           serImage = getStringImage(rbitmap);
           imageViewUserImage.setImageBitmap(rbitmap);
      } catch (IOException e) {
           e.printStackTrace();
      }


   }
}

Proper way to use **kwargs in Python

@AbhinavGupta and @Steef suggested using update(), which I found very helpful for processing large argument lists:

args.update(kwargs)

What if we want to check that the user hasn't passed any spurious/unsupported arguments? @VinaySajip pointed out that pop() can be used to iteratively process the list of arguments. Then, any leftover arguments are spurious. Nice.

Here's another possible way to do this, which keeps the simple syntax of using update():

# kwargs = dictionary of user-supplied arguments
# args = dictionary containing default arguments

# Check that user hasn't given spurious arguments
unknown_args = user_args.keys() - default_args.keys()
if unknown_args:
    raise TypeError('Unknown arguments: {}'.format(unknown_args))

# Update args to contain user-supplied arguments
args.update(kwargs)

unknown_args is a set containing the names of arguments that don't occur in the defaults.

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

After some searching, I was able to find the information_schema.routines table and the information_schema.parameters tables. Using those, one can construct a query for this purpose. LEFT JOIN, instead of JOIN, is necessary to retrieve functions without parameters.

SELECT routines.routine_name, parameters.data_type, parameters.ordinal_position
FROM information_schema.routines
    LEFT JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name
WHERE routines.specific_schema='my_specified_schema_name'
ORDER BY routines.routine_name, parameters.ordinal_position;

Executing command line programs from within python

The subprocess module is the preferred way of running other programs from Python -- much more flexible and nicer to use than os.system.

import subprocess
#subprocess.check_output(['ls', '-l'])  # All that is technically needed...
print(subprocess.check_output(['ls', '-l']))