Programs & Examples On #Gitweb

Gitweb is a Git repository web interface.

Install pip in docker

An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine. They offer pip out of the box (and have a smaller footprint which leads to faster builds etc).

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

Why is nginx responding to any domain name?

To answer your question - nginx picks the first server if there's no match. See documentation:

If its value does not match any server name, or the request does not contain this header field at all, then nginx will route the request to the default server for this port. In the configuration above, the default server is the first one...

Now, if you wanted to have a default catch-all server that, say, responds with 404 to all requests, then here's how to do it:

server {
    listen 80 default_server;
    listen 443 ssl default_server;
    server_name _;
    ssl_certificate <path to cert>
    ssl_certificate_key <path to key>
    return 404;
}

Note that you need to specify certificate/key (that can be self-signed), otherwise all SSL connections will fail as nginx will try to accept connection using this default_server and won't find cert/key.

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

If you really want to match only the dot, then StringComparison.Ordinal would be fastest, as there is no case-difference.

"Ordinal" doesn't use culture and/or casing rules that are not applicable anyway on a symbol like a ..

How to get progress from XMLHttpRequest

The only way to do that with pure javascript is to implement some kind of polling mechanism. You will need to send ajax requests at fixed intervals (each 5 seconds for example) to get the number of bytes received by the server.

A more efficient way would be to use flash. The flex component FileReference dispatchs periodically a 'progress' event holding the number of bytes already uploaded. If you need to stick with javascript, bridges are available between actionscript and javascript. The good news is that this work has been already done for you :)

swfupload

This library allows to register a javascript handler on the flash progress event.

This solution has the hudge advantage of not requiring aditionnal resources on the server side.

Can I convert a C# string value to an escaped string literal

try:

var t = HttpUtility.JavaScriptStringEncode(s);

Are PHP Variables passed by value or by reference?

http://www.php.net/manual/en/migration5.oop.php

In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).

Get current user id in ASP.NET Identity 2.0

GetUserId() is an extension method on IIdentity and it is in Microsoft.AspNet.Identity.IdentityExtensions. Make sure you have added the namespace with using Microsoft.AspNet.Identity;.

Returning multiple values from a C++ function

There is precedent for returning structures in the C (and hence C++) standard with the div, ldiv (and, in C99, lldiv) functions from <stdlib.h> (or <cstdlib>).

The 'mix of return value and return parameters' is usually the least clean.

Having a function return a status and return data via return parameters is sensible in C; it is less obviously sensible in C++ where you could use exceptions to relay failure information instead.

If there are more than two return values, then a structure-like mechanism is probably best.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Besides the already stated answers about using Vector, Vector also has a bunch of methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation.

How to properly stop the Thread in Java?

Some supplementary info. Both flag and interrupt are suggested in the Java doc.

https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

private volatile Thread blinker;

public void stop() {
    blinker = null;
}

public void run() {
    Thread thisThread = Thread.currentThread();
    while (blinker == thisThread) {
        try {
            Thread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}

For a thread that waits for long periods (e.g., for input), use Thread.interrupt

public void stop() {
     Thread moribund = waiter;
      waiter = null;
      moribund.interrupt();
 }

Inline elements shifting when made bold on hover

Not very elegant solution, but "works":

a
{
    color: #fff;
}

a:hover
{
    text-shadow: -1px 0 #fff, 0 1px #fff, 1px 0 #fff, 0 -1px #fff;
}

Iterate two Lists or Arrays with one ForEach statement in C#

I understand/hope that the lists have the same length: No, your only bet is going with a plain old standard for loop.

What does hash do in python?

TL;DR:

Please refer to the glossary: hash() is used as a shortcut to comparing objects, an object is deemed hashable if it can be compared to other objects. that is why we use hash(). It's also used to access dict and set elements which are implemented as resizable hash tables in CPython.

Technical considerations

  • usually comparing objects (which may involve several levels of recursion) is expensive.
  • preferably, the hash() function is an order of magnitude (or several) less expensive.
  • comparing two hashes is easier than comparing two objects, this is where the shortcut is.

If you read about how dictionaries are implemented, they use hash tables, which means deriving a key from an object is a corner stone for retrieving objects in dictionaries in O(1). That's however very dependent on your hash function to be collision-resistant. The worst case for getting an item in a dictionary is actually O(n).

On that note, mutable objects are usually not hashable. The hashable property means you can use an object as a key. If the hash value is used as a key and the contents of that same object change, then what should the hash function return? Is it the same key or a different one? It depends on how you define your hash function.

Learning by example:

Imagine we have this class:

>>> class Person(object):
...     def __init__(self, name, ssn, address):
...         self.name = name
...         self.ssn = ssn
...         self.address = address
...     def __hash__(self):
...         return hash(self.ssn)
...     def __eq__(self, other):
...         return self.ssn == other.ssn
... 

Please note: this is all based on the assumption that the SSN never changes for an individual (don't even know where to actually verify that fact from authoritative source).

And we have Bob:

>>> bob = Person('bob', '1111-222-333', None)

Bob goes to see a judge to change his name:

>>> jim = Person('jim bo', '1111-222-333', 'sf bay area')

This is what we know:

>>> bob == jim
True

But these are two different objects with different memory allocated, just like two different records of the same person:

>>> bob is jim
False

Now comes the part where hash() is handy:

>>> dmv_appointments = {}
>>> dmv_appointments[bob] = 'tomorrow'

Guess what:

>>> dmv_appointments[jim] #?
'tomorrow'

From two different records you are able to access the same information. Now try this:

>>> dmv_appointments[hash(jim)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in __eq__
AttributeError: 'int' object has no attribute 'ssn'
>>> hash(jim) == hash(hash(jim))
True

What just happened? That's a collision. Because hash(jim) == hash(hash(jim)) which are both integers btw, we need to compare the input of __getitem__ with all items that collide. The builtin int does not have an ssn attribute so it trips.

>>> del Person.__eq__
>>> dmv_appointments[bob]
'tomorrow'
>>> dmv_appointments[jim]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: <__main__.Person object at 0x7f611bd37110>

In this last example, I show that even with a collision, the comparison is performed, the objects are no longer equal, which means it successfully raises a KeyError.

How to check if dropdown is disabled?

I was searching for something like this, because I've got to check which of all my selects are disabled.

So I use this:

let select= $("select");

for (let i = 0; i < select.length; i++) {
    const element = select[i];
    if(element.disabled == true ){
        console.log(element)
    }
}

What are the correct version numbers for C#?

The biggest problem when dealing with C#'s version numbers is the fact that it is not tied to a version of the .NET Framework, which it appears to be due to the synchronized releases between Visual Studio and the .NET Framework.

The version of C# is actually bound to the compiler, not the framework. For instance, in Visual Studio 2008 you can write C# 3.0 and target .NET Framework 2.0, 3.0 and 3.5. The C# 3.0 nomenclature describes the version of the code syntax and supported features in the same way that ANSI C89, C90, C99 describe the code syntax/features for C.

Take a look at Mono, and you will see that Mono 2.0 (mostly implemented version 2.0 of the .NET Framework from the ECMA specifications) supports the C# 3.0 syntax and features.

How should I unit test multithreaded code?

(if possible) don't use threads, use actors / active objects. Easy to test.

How to configure Git post commit hook

I want to add to the answers above that it becomes a little more difficult if Jenkins authorization is enabled.

After enabling it I got an error message that anonymous user needs read permission.

I saw two possible solutions:

1: Changing my hook to:

curl --user name:passwd -s http://domain?token=whatevertokenuhave

2: setting project based authorization.

The former solutions has the disadvantage that I had to expose my passwd in the hook file. Unacceptable in my case.

The second works for me. In the global auth settings I had to enable Overall>Read for Anonymous user. In the project I wanted to trigger I had to enable Job>Build and Job>Read for Anonymous.

This is still not a perfect solution because now you can see the project in Jenkins without login. There might be an even better solution using the former approach with http login but I haven't figured it out.

Detecting iOS orientation change instantly

Why you didn`t use

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

?

Or you can use this

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

Or this

-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

Hope it owl be useful )

Line break (like <br>) using only css

It works like this:

h4 {
    display:inline;
}
h4:after {
    content:"\a";
    white-space: pre;
}

Example: http://jsfiddle.net/Bb2d7/

The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)

regex match any whitespace

Your regex should work 'as-is'. Assuming that it is doing what you want it to.

wordA(\s*)wordB(?! wordc)

This means match wordA followed by 0 or more spaces followed by wordB, but do not match if followed by wordc. Note the single space between ?! and wordc which means that wordA wordB wordc will not match, but wordA wordB wordc will.

Here are some example matches and the associated replacement output:

enter image description here

Note that all matches are replaced no matter how many spaces. There are a couple of other points: -

  • (?! wordc) is a negative lookahead, so you wont match lines wordA wordB wordc which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?! to match the whitespace. You may want to be more precise and use (?!\swordc). If you want to match against more than one space before wordc you can use (?!\s*wordc) for 0 or more spaces or (?!\s*+wordc) for 1 or more spaces depending on what your intention is. Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.

  • * will match 0 or more spaces so it will match wordAwordB. You may want to consider + if you want at least one space.

  • (\s*) - the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s.

Update based on comment

Hello the problem is not the expression but the HTML out put   that are not considered as whitespace. it's a Joomla website.

Preserving your original regex you can use:

wordA((?:\s|&nbsp;)*)wordB(?!(?:\s|&nbsp;)wordc)

The only difference is that not the regex matches whitespace OR &nbsp;. I replaced wordc with \swordc since that is more explicit. Note as I have already pointed out that the negative lookahead ?! will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.

Example matches:

enter image description here

Multiple IF AND statements excel

With your ANDs you shouldn't have a FALSE value -2, until right at the end, e.g. with just 2 ANDs

=IF(AND(E2="In Play",F2="Closed"),3,IF(AND(E2="In Play",F2=" Suspended"),3,-2))

although it might be better with a combination of nested IFs and ANDs - try like this for the full formula:[Edited - thanks David]

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="Suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-play",F2="Null"),-1,IF(AND(E2="Completed",F2="Closed"),2,IF(AND(E2="Pre-play",F2="Null"),3,-2))))

To avoid a long formula like the above you could create a table with all E2 possibilities in a column like K2:K5 and all F2 possibilities in a row like L1:N1 then fill in the required results in L2:N5 and use this formula

=INDEX($L$2:$N$5,MATCH(E2,$K$2:$K$5,0),MATCH(F2,$L$1:$N$1,0))

Keep overflow div scrolled to bottom unless user scrolls up

You can use something like this,

var element = document.getElementById("yourDivID");
window.scrollTo(0,element.offsetHeight);

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

In ONLINE mode the new index is built while the old index is accessible to reads and writes. any update on the old index will also get applied to the new index. An antimatter column is used to track possible conflicts between the updates and the rebuild (ie. delete of a row which was not yet copied). See Online Index Operations. When the process is completed the table is locked for a brief period and the new index replaces the old index. If the index contains LOB columns, ONLINE operations are not supported in SQL Server 2005/2008/R2.

In OFFLINE mode the table is locked upfront for any read or write, and then the new index gets built from the old index, while holding a lock on the table. No read or write operation is permitted on the table while the index is being rebuilt. Only when the operation is done is the lock on the table released and reads and writes are allowed again.

Note that in SQL Server 2012 the restriction on LOBs was lifted, see Online Index Operations for indexes containing LOB columns.

Is there a way to remove unused imports and declarations from Angular 2+?

To be able to detect unused imports, code or variables, make sure you have this options in tsconfig.json file

"compilerOptions": {
    "noUnusedLocals": true,
    "noUnusedParameters": true
}

have the typescript compiler installed, ifnot install it with:

npm install -g typescript

and the tslint extension installed in Vcode, this worked for me, but after enabling I notice an increase amount of CPU usage, specially on big projects.

I would also recomend using typescript hero extension for organizing your imports.

Selecting one row from MySQL using mysql_* API

It is working for me..

$show = mysql_query("SELECT data FROM wp_10_options WHERE
 option_name='homepage' limit 1"); $row = mysql_fetch_assoc($show);
 echo $row['data'];

What is the idiomatic Go equivalent of C's ternary operator?

eold's answer is interesting and creative, perhaps even clever.

However, it would be recommended to instead do:

var index int
if val > 0 {
    index = printPositiveAndReturn(val)
} else {
    index = slowlyReturn(-val)  // or slowlyNegate(val)
}

Yes, they both compile down to essentially the same assembly, however this code is much more legible than calling an anonymous function just to return a value that could have been written to the variable in the first place.

Basically, simple and clear code is better than creative code.

Additionally, any code using a map literal is not a good idea, because maps are not lightweight at all in Go. Since Go 1.3, random iteration order for small maps is guaranteed, and to enforce this, it's gotten quite a bit less efficient memory-wise for small maps.

As a result, making and removing numerous small maps is both space-consuming and time-consuming. I had a piece of code that used a small map (two or three keys, are likely, but common use case was only one entry) But the code was dog slow. We're talking at least 3 orders of magnitude slower than the same code rewritten to use a dual slice key[index]=>data[index] map. And likely was more. As some operations that were previously taking a couple of minutes to run, started completing in milliseconds.\

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

If you want to compare file in your project/directory with an external file (which is by the way the most common way I used to compare files) you can easily drag and drop the external file into the editor's tab and just use the command: "Compare Active File With..." on one of them selecting the other one in the newly popped up choice window. That seems to be the fastest way.

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

Here is my solution:

[12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]) ([01][0-9]|2[0-3]):[0-5]\d

Regular expression visualization

Debuggex Demo

https://regex101.com/r/lbthaT/4

Finding the length of a Character Array in C

Provided the char array is null terminated,

char chararray[10] = { 0 };
size_t len = strlen(chararray);

AWS ssh access 'Permission denied (publickey)' issue

If you are using EBS, you can also try to mount the EBS Volume on a running instance. Then mount it on that running instance and see what's going on in /home. You can see things like is the user ubuntu or ec2-user ? or does it have the right public keys under ~/.ssh/authorized_keys

how to make label visible/invisible?

You are looking for display:

document.getElementById("endTimeLabel").style.display = 'none';
document.getElementById("endTimeLabel").style.display = 'block';

Edit: You could also easily reuse your validation function.

HTML:

<span id="startDateLabel">Start date/time: </span>
<input id="startDateStr" name="startDateStr" size="8" onchange="if (!formatDate(this,'USA')) {this.value = '';}" />
<button id="startDateCalendarTrigger">...</button>
<input id="startDateTime" type="text" size="8" name="startTime" value="12:00 AM" onchange="validateHHMM(this.value, 'startTimeLabel');"/>
<label id="startTimeLabel" class="errorMsg">Time must be entered in the format HH:MM AM/PM</label><br />

<span id="endDateLabel">End date/time: </span>
<input id="endDateStr" name="endDateStr" size="8" onchange="if (!formatDate(this,'USA')) {this.value = '';}" />
<button id="endDateCalendarTrigger">...</button>

<input id="endDateTime" type="text" size="8" name="endTime" value="12:00 AM" onchange="validateHHMM(this.value, 'endTimeLabel');"/>
<label id="endTimeLabel" class="errorMsg">Time must be entered in the format HH:MM AM/PM</label>

Javascript:

function validateHHMM(value, message) {
    var isValid = /^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/.test(value);

    if (isValid) {
        document.getElementById(message).style.display = "none";
    }else {
        document.getElementById(message).style.display= "inline";
    }

    return isValid;
}

Live DEMO

How to unzip a file using the command line?

There is an article on getting to the built-in Windows .ZIP file handling with VBscript here:

https://www.aspfree.com/c/a/Windows-Scripting/Compressed-Folders-in-WSH/

(The last code blurb deals with extraction)

How to remove/delete a large file from commit history in Git repository?

(The best answer I've seen to this problem is: https://stackoverflow.com/a/42544963/714112 , copied here since this thread appears high in Google search rankings but that other one doesn't)

A blazingly fast shell one-liner

This shell script displays all blob objects in the repository, sorted from smallest to largest.

For my sample repo, it ran about 100 times faster than the other ones found here.
On my trusty Athlon II X4 system, it handles the Linux Kernel repository with its 5,622,155 objects in just over a minute.

The Base Script

git rev-list --objects --all \
| git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \
| awk '/^blob/ {print substr($0,6)}' \
| sort --numeric-sort --key=2 \
| cut --complement --characters=13-40 \
| numfmt --field=2 --to=iec-i --suffix=B --padding=7 --round=nearest

When you run above code, you will get nice human-readable output like this:

...
0d99bb931299  530KiB path/to/some-image.jpg
2ba44098e28f   12MiB path/to/hires-image.png
bd1741ddce0d   63MiB path/to/some-video-1080p.mp4

Fast File Removal

Suppose you then want to remove the files a and b from every commit reachable from HEAD, you can use this command:

git filter-branch --index-filter 'git rm --cached --ignore-unmatch a b' HEAD

MAX(DATE) - SQL ORACLE

select * from 
  (SELECT MEMBSHIP_ID
   FROM user_payment WHERE user_id=1
   order by paym_date desc) 
where rownum=1;

Checking if a string can be converted to float in Python

This regex will check for scientific floating point numbers:

^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$

However, I believe that your best bet is to use the parser in a try.

How to check Oracle database for long running queries

You can generate an AWR (automatic workload repository) report from the database.

Run from the SQL*Plus command line:

SQL> @$ORACLE_HOME/rdbms/admin/awrrpt.sql

Read the document related to how to generate & understand an AWR report. It will give a complete view of database performance and resource issues. Once we are familiar with the AWR report it will be helpful to find Top SQL which is consuming resources.

Also, in the 12C EM Express UI we can generate an AWR.

Remove portion of a string after a certain character

How about using explode:

$input = 'Posted On April 6th By Some Dude';
$result = explode(' By',$input);
return $result[0];

Advantages:

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:

RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);

There, &rect is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.

The code should create a dynamic variable:

RectInvoice *rect =  new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);

There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.

Cheers

Initialize 2D array

Shorter way is do it as follows:

private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

how to do "press enter to exit" in batch

@echo off
echo somethink
echo Press enter to exit
set /p input=

How to fully delete a git repository created with init?

You can create an alias for it. I am using ZSH shell with Oh-my-Zsh and here is an handy alias:

# delete and re-init git
# usage: just type 'gdelinit' in a local repository
alias gdelinit="trash .git && git init"

I am using Trash to trash the .git folder since using rm is really dangerous:

trash .git

Then I am re-initializing the git repo:

git init

html "data-" attribute as javascript parameter

HTML:

<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this)">

JavaScript:

function fun(obj) {
    var uid= $(obj).attr('data-uid');
    var name= $(obj).attr('data-name');
    var value= $(obj).attr('data-value');
}

but I'm using jQuery.

Getting a union of two arrays in JavaScript

ES2015 version

Array.prototype.diff = function(a) {return this.filter(i => a.indexOf(i) < 0)};

Array.prototype.union = function(a) {return [...this.diff(a), ...a]}

What is the difference between application server and web server?

The main difference between Web server and application server is that web server is meant to serve static pages e.g. HTML and CSS, while Application Server is responsible for generating dynamic content by executing server side code e.g. JSP, Servlet or EJB.

Which one should i use?
Once you know the difference between web and application server and web containers, it's easy to figure out when to use them. You need a web server like Apache HTTPD if you are serving static web pages. If you have a Java application with just JSP and Servlet to generate dynamic content then you need web containers like Tomcat or Jetty. While, if you have Java EE application using EJB, distributed transaction, messaging and other fancy features than you need a full fledged application server like JBoss, WebSphere or Oracle's WebLogic.

Web container is a part of Web Server and the Web Server is a part of Application Server.

Application Server

Web Server is composed of web container, while Application Server is composed of web container as well as EJB container.

Python conversion from binary string to hexadecimal

Assuming they are grouped by 4 and separated by whitespace. This preserves the leading 0.

b = '0000 0100 1000 1101'
h = ''.join(hex(int(a, 2))[2:] for a in b.split())

CSS horizontal centering of a fixed div?

Here's another two-div solution. Tried to keep it concise and not hardcoded. First, the expectable html:

<div id="outer">
  <div id="inner">
    content
  </div>
</div>

The principle behind the following css is to position some side of "outer", then use the fact that it assumes the size of "inner" to relatively shift the latter.

#outer {
  position: fixed;
  left: 50%;          // % of window
}
#inner {
  position: relative;
  left: -50%;         // % of outer (which auto-matches inner width)
}

This approach is similar to Quentin's, but inner can be of variable size.

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

I'm running the very latest Laravel 5 dev release, and if you've changed the namespace you'll need to call your seed class like this:

$this->call('\todoparrot\TodolistTableSeeder');

Obviously you'll need to replace todoparrot with your designated namespace. Otherwise I receive the same error indicated in the original question.

LD_LIBRARY_PATH vs LIBRARY_PATH

LD_LIBRARY_PATH is searched when the program starts, LIBRARY_PATH is searched at link time.

caveat from comments:

Java HTML Parsing

Jericho: http://jericho.htmlparser.net/docs/index.html

Easy to use, supports not well formed HTML, a lot of examples.

Flask - Calling python function on button OnClick event

You can simply do this with help of AJAX... Here is a example which calls a python function which prints hello without redirecting or refreshing the page.

In app.py put below code segment.

#rendering the HTML page which has the button
@app.route('/json')
def json():
    return render_template('json.html')

#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
    print ("Hello")
    return ("nothing")

And your json.html page should look like below.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
        $(function() {
          $('a#test').on('click', function(e) {
            e.preventDefault()
            $.getJSON('/background_process_test',
                function(data) {
              //do nothing
            });
            return false;
          });
        });
</script>


//button
<div class='container'>
    <h3>Test</h3>
        <form>
            <a href=# id=test><button class='btn btn-default'>Test</button></a>
        </form>

</div>

Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.

How to test the type of a thrown exception in Jest

Try:

expect(t).rejects.toThrow()

What is MVC and what are the advantages of it?

Jeff has a post about it, otherwise I found some useful documents on Apple's website, in Cocoa tutorials (this one for example).

How to remove an app with active device admin enabled on Android?

Go to SETTINGS->Location and Security-> Device Administrator and deselect the admin which you want to uninstall.

Now uninstall the application. If it still says you need to deactivate the application before uninstalling, you may need to Force Stop the application before uninstalling.

CSS content generation before or after 'input' elements

Use tags label and our method for =, is bound to input. If follow the rules of the form, and avoid confusion with tags, use the following:

<style type="text/css">
    label.lab:before { content: 'input: '; }
</style>

or compare (short code):

<style type="text/css">
    div label { content: 'input: '; color: red; }
</style>

form....

<label class="lab" for="single"></label><input name="n" id="single" ...><label for="single"> - simle</label>

or compare (short code):

<div><label></label><input name="n" ...></div>

How to create a function in SQL Server

This will work for most of the website names :

SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....

How to hide first section header in UITableView (grouped style)

The answer was very funny for me and my team, and worked like a charm

  • In the Interface Builder, Just move the tableview under another view in the view hierarchy.

REASON:

We observed that this happens only for the First View in the View Hierarchy, if this first view is a UITableView. So, all other similar UITableViews do not have this annoying section, except the first. We Tried moving the UITableView out of the first place in the view hierarchy, and everything was working as expected.

Time part of a DateTime Field in SQL

SELECT DISTINCT   
                 CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108)  
FROM  
      CONSOLIDATED_LIST AS A  
WHERE   
      CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108) BETWEEN '15:00:00' AND '15:45:00'

Get viewport/window height in ReactJS

class AppComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {height: props.height};
  }

  componentWillMount(){
    this.setState({height: window.innerHeight + 'px'});
  }

  render() {
    // render your component...
  }
}

Set the props

AppComponent.propTypes = {
 height:React.PropTypes.string
};

AppComponent.defaultProps = {
 height:'500px'
};

viewport height is now available as {this.state.height} in rendering template

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

Actually you can set custom text to that little blue button. In the xml file just use

android:imeActionLabel="whatever"

on your EditText.

Or in the java file use

etEditText.setImeActionLabel("whatever", EditorInfo.IME_ACTION_DONE);

I arbitrarily choose IME_ACTION_DONE as an example of what should go in the second parameter for this function. A full list of these actions can be found here.

It should be noted that this will not cause text to appear on all keyboards on all devices. Some keyboards do not support text on that button (e.g. swiftkey). And some devices don't support it either. A good rule is, if you see text already on the button, this will change it to whatever you'd want.

What are the true benefits of ExpandoObject?

var obj = new Dictionary<string, object>;
...
Console.WriteLine(obj["MyString"]);

I think that only works because everything has a ToString(), otherwise you'd have to know the type that it was and cast the 'object' to that type.


Some of these are useful more often than others, I'm trying to be thorough.

  1. It may be far more natural to access a collection, in this case what is effectively a "dictionary", using the more direct dot notation.

  2. It seems as if this could be used as a really nice Tuple. You can still call your members "Item1", "Item2" etc... but now you don't have to, it's also mutable, unlike a Tuple. This does have the huge drawback of lack of intellisense support.

  3. You may be uncomfortable with "member names as strings", as is the feel with the dictionary, you may feel it is too like "executing strings", and it may lead to naming conventions getting coded in, and dealing with working with morphemes and syllables when code is trying understand how to use members :-P

  4. Can you assign a value to an ExpandoObject itself or just it's members? Compare and contrast with dynamic/dynamic[], use whichever best suits your needs.

  5. I don't think dynamic/dynamic[] works in a foreach loop, you have to use var, but possibly you can use ExpandoObject.

  6. You cannot use dynamic as a data member in a class, perhaps because it's at least sort of like a keyword, hopefully you can with ExpandoObject.

  7. I expect it "is" an ExpandoObject, might be useful to label very generic things apart, with code that differentiates based on types where there is lots of dynamic stuff being used.


Be nice if you could drill down multiple levels at once.

var e = new ExpandoObject();
e.position.x = 5;
etc...

Thats not the best possible example, imagine elegant uses as appropriate in your own projects.

It's a shame you cannot have code build some of these and push the results to intellisense. I'm not sure how this would work though.

Be nice if they could have a value as well as members.

var fifteen = new ExpandoObject();
fifteen = 15;
fifteen.tens = 1;
fifteen.units = 5;
fifteen.ToString() = "fifteen";
etc...

How can I stream webcam video with C#?

Another option to stream images from a webcam to a browser is via mjpeg. This is just a series of jpeg images that most modern browsers support as part of the tag. Here's a sample server written in c#:

https://www.codeproject.com/articles/371955/motion-jpeg-streaming-server

This works well over a LAN, but not as well over the internet as mjpeg is not as effcient as other video codecs (h264, VP8 etc..)

How to debug a Flask app

Use loggers and print statements in the Development Environment, you can go for sentry in case of production environments.

Convert list to tuple in Python

Expanding on eumiro's comment, normally tuple(l) will convert a list l into a tuple:

In [1]: l = [4,5,6]

In [2]: tuple
Out[2]: <type 'tuple'>

In [3]: tuple(l)
Out[3]: (4, 5, 6)

However, if you've redefined tuple to be a tuple rather than the type tuple:

In [4]: tuple = tuple(l)

In [5]: tuple
Out[5]: (4, 5, 6)

then you get a TypeError since the tuple itself is not callable:

In [6]: tuple(l)
TypeError: 'tuple' object is not callable

You can recover the original definition for tuple by quitting and restarting your interpreter, or (thanks to @glglgl):

In [6]: del tuple

In [7]: tuple
Out[7]: <type 'tuple'>

How do I create a folder in VB if it doesn't exist?

Just do this:

        Dim sPath As String = "Folder path here"
    If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then
        My.Computer.FileSystem.CreateDirectory(sPath + "/<Folder name>")
    Else
        'Something else happens, because the folder exists
    End If

I declared the folder path as a String (sPath) so that way if you do use it multiple times it can be changed easily but also it can be changed through the program itself.

Hope it helps!

-nfell2009

How can I redirect a php page to another php page?

<?php  
header('Location: http://www.google.com'); //Send browser to http://www.google.com
?>  

Is the practice of returning a C++ reference variable evil?

    Class Set {
    int *ptr;
    int size;

    public: 
    Set(){
     size =0;
         }

     Set(int size) {
      this->size = size;
      ptr = new int [size];
     }

    int& getPtr(int i) {
     return ptr[i];  // bad practice 
     }
  };

getPtr function can access dynamic memory after deletion or even a null object. Which can cause Bad Access Exceptions. Instead getter and setter should be implemented and size verified before returning.

SQL DROP TABLE foreign key constraint

In SQL Server Management Studio 2008 (R2) and newer, you can Right Click on the

DB -> Tasks -> Generate Scripts

  • Select the tables you want to DROP.

  • Select "Save to new query window".

  • Click on the Advanced button.

  • Set Script DROP and CREATE to Script DROP.

  • Set Script Foreign Keys to True.

  • Click OK.

  • Click Next -> Next -> Finish.

  • View the script and then Execute.

SQL Server: Importing database from .mdf?

To perform this operation see the next images:

enter image description here

and next step is add *.mdf file,

very important, the .mdf file must be located in C:......\MSSQL12.SQLEXPRESS\MSSQL\DATA

enter image description here

Now remove the log file

enter image description here

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

How to set the opacity/alpha of a UIImage?

I realize this is quite late, but I needed something like this so I whipped up a quick and dirty method to do this.

+ (UIImage *) image:(UIImage *)image withAlpha:(CGFloat)alpha{

    // Create a pixel buffer in an easy to use format
    CGImageRef imageRef = [image CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    UInt8 * m_PixelBuf = malloc(sizeof(UInt8) * height * width * 4);

    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(m_PixelBuf, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    //alter the alpha
    int length = height * width * 4;
    for (int i=0; i<length; i+=4)
    {
        m_PixelBuf[i+3] =  255*alpha;
    }


    //create a new image
    CGContextRef ctx = CGBitmapContextCreate(m_PixelBuf, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    CGImageRef newImgRef = CGBitmapContextCreateImage(ctx);  
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(ctx);  
    free(m_PixelBuf);

    UIImage *finalImage = [UIImage imageWithCGImage:newImgRef];
    CGImageRelease(newImgRef);  

    return finalImage;
}

Generate Json schema from XML schema (XSD)

Disclaimer: I'm the author of jgeXml.

jgexml has Node.js based utility xsd2json which does a transformation between an XML schema (XSD) and a JSON schema file.

As with other options, it's not a 1:1 conversion, and you may need to hand-edit the output to improve the JSON schema validation, but it has been used to represent a complex XML schema inside an OpenAPI (swagger) definition.

A sample of the purchaseorder.xsd given in another answer is rendered as:

"PurchaseOrderType": {
  "type": "object",
  "properties": {
    "shipTo": {
      "$ref": "#/definitions/USAddress"
    },
    "billTo": {
      "$ref": "#/definitions/USAddress"
    },
    "comment": {
      "$ref": "#/definitions/comment"
    },
    "items": {
      "$ref": "#/definitions/Items"
    },
    "orderDate": {
      "type": "string",
      "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}.*$"
    }
  },

The source was not found, but some or all event logs could not be searched

For me just worked iisreset (run cmd as administrator -> iisreset). Maybe somebody could give it a try.

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

You have to change androidx.constraintlayout.widget.ConstraintLayout to RelativeLayout.

What are some examples of commonly used practices for naming git branches?

Why does it take three branches/merges for every task? Can you explain more about that?

If you use a bug tracking system you can use the bug number as part of the branch name. This will keep the branch names unique, and you can prefix them with a short and descriptive word or two to keep them human readable, like "ResizeWindow-43523". It also helps make things easier when you go to clean up branches, since you can look up the associated bug. This is how I usually name my branches.

Since these branches are eventually getting merged back into master, you should be safe deleting them after you merge. Unless you're merging with --squash, the entire history of the branch will still exist should you ever need it.

Keytool is not recognized as an internal or external command

Make sure JAVA_HOME is set and the path in environment variables. The PATH should be able to find the keytools.exe

Open “Windows search” and search for "Environment Variables"

Under “System variables” click the “New…” button and enter JAVA_HOME as “Variable name” and the path to your Java JDK directory under “Variable value” it should be similar to this C:\Program Files\Java\jre1.8.0_231

How to find list of possible words from a letter matrix [Boggle Solver]

I know I'm super late but I made one of these a while ago in PHP - just for fun too...

http://www.lostsockdesign.com.au/sandbox/boggle/index.php?letters=fxieamloewbxastu Found 75 words (133 pts) in 0.90108 seconds

F.........X..I..............E............... A......................................M..............................L............................O............................... E....................W............................B..........................X A..................S..................................................T.................U....

Gives some indication of what the program is actually doing - each letter is where it starts looking through the patterns while each '.' shows a path that it has tried to take. The more '.' there are the further it has searched.

Let me know if you want the code... it is a horrible mix of PHP and HTML that was never meant to see the light of day so I dare not post it here :P

NSString property: copy or retain?

Surely putting 'copy' on a property declaration flies in the face of using an object-oriented environment where objects on the heap are passed by reference - one of the benefits you get here is that, when changing an object, all references to that object see the latest changes. A lot of languages supply 'ref' or similar keywords to allow value types (i.e. structures on the stack) to benefit from the same behaviour. Personally, I'd use copy sparingly, and if I felt that a property value should be protected from changes made to the object it was assigned from, I could call that object's copy method during the assignment, e.g.:

p.name = [someName copy];

Of course, when designing the object that contains that property, only you will know whether the design benefits from a pattern where assignments take copies - Cocoawithlove.com has the following to say:

"You should use a copy accessor when the setter parameter may be mutable but you can't have the internal state of a property changing without warning" - so the judgement as to whether you can stand the value to change unexpectedly is all your own. Imagine this scenario:

//person object has details of an individual you're assigning to a contact list.

Contact *contact = [[[Contact alloc] init] autorelease];
contact.name = person.name;

//person changes name
[[person name] setString:@"new name"];
//now both person.name and contact.name are in sync.

In this case, without using copy, our contact object takes the new value automatically; if we did use it, though, we'd have to manually make sure that changes were detected and synced. In this case, retain semantics might be desirable; in another, copy might be more appropriate.

Using CSS :before and :after pseudo-elements with inline CSS?

No you cant target the pseudo-classes or pseudo-elements in inline-css as David Thomas said. For more details see this answer by BoltClock about Pseudo-classes

No. The style attribute only defines style properties for a given HTML element. Pseudo-classes are a member of the family of selectors, which don't occur in the attribute .....

We can also write use same for the pseudo-elements

No. The style attribute only defines style properties for a given HTML element. Pseudo-classes and pseudo-elements the are a member of the family of selectors, which don't occur in the attribute so you cant style them inline.

How to set a primary key in MongoDB?

Simple you can use

db.collectionName.createIndex({urfield:1},{unique:true});

firefox proxy settings via command line

Firefox? I don't think you can. IE is another story though..

Failed to load resource: the server responded with a status of 404 (Not Found)

If your URL is:

http://127.0.0.1:8080/binding/

Update the below property in the index.html

<base href="/binding/">

In short, you need to check the locations of the files.

XPath - Selecting elements that equal a value

The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.

This explains the "strange results".

"Better" results can be obtained using the expressions below:

//*[text() = 'qwerty']

The above selects every element in the document that has at least one text-node child with value 'qwerty'.

//*[text() = 'qwerty' and not(text()[2])]

The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.

Matrix Multiplication in pure Python?

When I had to do some matrix arithmetic I defined a new class to help. Within such a class you can define magic methods like __add__, or, in your use-case, __matmul__, allowing you to define x = a @ b or a @= b rather than matrixMult(a,b). __matmul__ was added in Python 3.5 per PEP 465.

I have included some code which implements this below (I excluded the prohibitively long __init__ method, which essentially creates a two-dimensional list self.mat and a tuple self.order according to what is passed to it)

class Matrix:
    def __matmul__(self, multiplier):
        if self.order[1] != multiplier.order[0]:
            raise ValueError("The multiplier was non-conformable under multiplication.")
        return [[sum(a*b for a,b in zip(srow,mcol)) for mcol in zip(*multiplier.mat)] for srow in self.mat]

    def __imatmul__(self, multiplier):
        self.mat = self @ multiplier
        return self.mat

    def __rmatmul__(self, multiplicand):
        if multiplicand.order[1] != self.order[0]:
            raise ValueError("The multiplier was non-conformable under multiplication.")
        return [[sum(a*b for a,b in zip(mrow,scol)) for scol in zip(*self.mat)] for mrow in multiplicand.mat]

Note:

  • __rmatmul__ is used if b @ a is called and b does not implement __matmul__ (e.g. if I wanted to implement premultiplying by a 2D list)
  • __imatmul__ is required for a @= b to work correctly;
  • If a matrix is non-conformable under multiplication it means that it cannot be multiplied, usually because it has more or less rows than there are columns in the multiplicand

Best way to check if a Data Table has a null value in it

Try comparing the value of the column to the DBNull.Value value to filter and manage null values in whatever way you see fit.

foreach(DataRow row in table.Rows)
{
    object value = row["ColumnName"];
    if (value == DBNull.Value)
        // do something
    else
        // do something else
}

More information about the DBNull class


If you want to check if a null value exists in the table you can use this method:

public static bool HasNull(this DataTable table)
{
    foreach (DataColumn column in table.Columns)
    {
        if (table.Rows.OfType<DataRow>().Any(r => r.IsNull(column)))
            return true;
    }

    return false;
}

which will let you write this:

table.HasNull();

How to get address location from latitude and longitude in Google Map.?

Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.

https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY

Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.

Click here to get an API key

Wait until page is loaded with Selenium WebDriver for Python

Solution for ajax pages that continuously load data. The previews methods stated do not work. What we can do instead is grab the page dom and hash it and compare old and new hash values together over a delta time.

import time
from selenium import webdriver

def page_has_loaded(driver, sleep_time = 2):
    '''
    Waits for page to completely load by comparing current page hash values.
    '''

    def get_page_hash(driver):
        '''
        Returns html dom hash
        '''
        # can find element by either 'html' tag or by the html 'root' id
        dom = driver.find_element_by_tag_name('html').get_attribute('innerHTML')
        # dom = driver.find_element_by_id('root').get_attribute('innerHTML')
        dom_hash = hash(dom.encode('utf-8'))
        return dom_hash

    page_hash = 'empty'
    page_hash_new = ''
    
    # comparing old and new page DOM hash together to verify the page is fully loaded
    while page_hash != page_hash_new: 
        page_hash = get_page_hash(driver)
        time.sleep(sleep_time)
        page_hash_new = get_page_hash(driver)
        print('<page_has_loaded> - page not loaded')

    print('<page_has_loaded> - page loaded: {}'.format(driver.current_url))

Open Form2 from Form1, close Form1 from Form2

if you just want to close form1 from form2 without closing form2 as well in the process, as the title suggests, then you could pass a reference to form 1 along to form 2 when you create it and use that to close form 1

for example you could add a

public class Form2 : Form
{
    Form2(Form1 parentForm):base()
    {
        this.parentForm = parentForm;
    }

    Form1 parentForm;
    .....
}

field and constructor to Form2

if you want to first close form2 and then form1 as the text of the question suggests, I'd go with Justins answer of returning an appropriate result to form1 on upon closing form2

Checking if a variable is an integer in PHP

/!\ Best anwser is not correct, is_numeric() returns true for integer AND all numeric forms like "9.1"

For integer only you can use the unfriendly preg_match('/^\d+$/', $var) or the explicit and 2 times faster comparison :

if ((int) $var == $var) {
    // $var is an integer
}

PS: i know this is an old post but still the third in google looking for "php is integer"

REST URI convention - Singular or plural name of resource while creating it

See Google's API Design Guide: Resource Names for another take on naming resources.

The guide requires collections to be named with plurals.

|--------------------------+---------------+-------------------+---------------+--------------|
| API Service Name         | Collection ID | Resource ID       | Collection ID | Resource ID  |
|--------------------------+---------------+-------------------+---------------+--------------|
| //mail.googleapis.com    | /users        | /[email protected] | /settings     | /customFrom  |
| //storage.googleapis.com | /buckets      | /bucket-id        | /objects      | /object-id   |
|--------------------------+---------------+-------------------+---------------+--------------|

It's worthwhile reading if you're thinking about this subject.

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

Code to loop through all records in MS Access

You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm

My own standard loop looks something like this:

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")

'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst 'Unnecessary in this case, but still a good habit
    Do Until rs.EOF = True
        'Perform an edit
        rs.Edit
        rs!VendorYN = True
        rs("VendorYN") = True 'The other way to refer to a field
        rs.Update

        'Save contact name into a variable
        sContactName = rs!FirstName & " " & rs!LastName

        'Move to the next record. Don't ever forget to do this.
        rs.MoveNext
    Loop
Else
    MsgBox "There are no records in the recordset."
End If

MsgBox "Finished looping through records."

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up

jQuery hyperlinks - href value?

I know this is old but wow, there's such an easy solution.

remove the "href" entirely and just add a class that does the following:

.no-href { cursor:pointer: }

And that's it!

Difference between View and ViewGroup in Android

ViewGroup is itself a View that works as a container for other views. It extends the functionality of View class in order to provide efficient ways to layout the child views.

For example, LinearLayout is a ViewGroup that lets you define the orientation in which you want child views to be laid, that's all you need to do and LinearLayout will take care of the rest.

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

Docker can't connect to docker daemon

To fix, you need to issue the following commands in the terminal. I'll explain each step:

# Uninstall Docker from apt packages
$ sudo apt-get remove docker docker.io

# Remove it from the libraries just to be
# sure it's gone forever
$ sudo rm -rf /var/lib/docker/*

Now, if you want to simplify things and get more time, you can run my init script with the parameter installDocker:

# Pull the init script from GitHub
$ wget https://github.com/dminca/dotfiles/blob/master/init

# Add rights to run the script
$ chmod 755 init

# Just run the script with the installDocker parameter
$ ./init installDocker

A reboot is optional, but I suggest you do it to be sure all runs smoothly.

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

You may try .removeAttribute("required") for those elements which are hidden at the time of window load. as it is quite probable that the element in question is marked hidden due to javascript (tabbed forms)

e.g.

if(document.getElementById('hidden_field_choice_selector_parent_element'.value==true){
    document.getElementById('hidden_field').removeAttribute("required");        
}

This should do the task.

It worked for me... cheers

Can I disable a CSS :hover effect via JavaScript?

I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch().

function touch() {
  if ('ontouchstart' in document.documentElement) {
    for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
      var sheet = document.styleSheets[sheetI];
      if (sheet.cssRules) {
        for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
          var rule = sheet.cssRules[ruleI];

          if (rule.selectorText) {
            rule.selectorText = rule.selectorText.replace(':hover', ':active');
          }
        }
      }
    }
  }
}

What is a lambda expression in C++11?

One problem it solves: Code simpler than lambda for a call in constructor that uses an output parameter function for initializing a const member

You can initialize a const member of your class, with a call to a function that sets its value by giving back its output as an output parameter.

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

How to remove space from string?

You can also use echo to remove blank spaces, either at the beginning or at the end of the string, but also repeating spaces inside the string.

$ myVar="    kokor    iiij     ook      "
$ echo "$myVar"
    kokor    iiij     ook      
$ myVar=`echo $myVar`
$
$ # myVar is not set to "kokor iiij ook"
$ echo "$myVar"
kokor iiij ook

How do I convert a dictionary to a JSON String in C#?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, List<int>> foo = new Dictionary<int, List<int>>();

            foo.Add(1, new List<int>( new int[] { 1, 2, 3, 4 }));
            foo.Add(2, new List<int>(new int[] { 2, 3, 4, 1 }));
            foo.Add(3, new List<int>(new int[] { 3, 4, 1, 2 }));
            foo.Add(4, new List<int>(new int[] { 4, 1, 2, 3 }));

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<int, List<int>>));

            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, foo);
                Console.WriteLine(Encoding.Default.GetString(ms.ToArray()));
            }
        }
    }
}

This will write to the console:

[{\"Key\":1,\"Value\":[1,2,3,4]},{\"Key\":2,\"Value\":[2,3,4,1]},{\"Key\":3,\"Value\":[3,4,1,2]},{\"Key\":4,\"Value\":[4,1,2,3]}]

Adding backslashes without escaping [Python]

printing a list can also cause this problem (im new in python, so it confused me a bit too):

>>>myList = ['\\']
>>>print myList
['\\']
>>>print ''.join(myList)
\ 

similarly:

>>>myList = ['\&']
>>>print myList
['\\&']
>>>print ''.join(myList)
\&

Get the latest record from mongodb collection

Yet another way of getting the last item from a MongoDB Collection (don't mind about the examples):

> db.collection.find().sort({'_id':-1}).limit(1)

Normal Projection

> db.Sports.find()
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2017", "Body" : "Again, the Pats won the Super Bowl." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }

Sorted Projection ( _id: reverse order )

> db.Sports.find().sort({'_id':-1})
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2018", "Body" : "Again, the Pats won the Super Bowl" }

sort({'_id':-1}), defines a projection in descending order of all documents, based on their _ids.

Sorted Projection ( _id: reverse order ): getting the latest (last) document from a collection.

> db.Sports.find().sort({'_id':-1}).limit(1)
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }

Difference between HashMap and Map in Java..?

Map is an interface; HashMap is a particular implementation of that interface.

HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.

How to calculate a logistic sigmoid function in Python?

Below is the python function to do the same.

def sigmoid(x) :
    return 1.0/(1+np.exp(-x))

How to query a MS-Access Table from MS-Excel (2010) using VBA

All you need is a ADODB.Connection

Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset   ' Microsoft ActiveX Data Objects Library

Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"

Set rs = cnn.Execute(SQLQuery) ' Retrieve the data

Why won't bundler install JSON gem?

If the recommended answer didn't help because you are already using a newer version of bundler. Try the solution that worked for me.

Delete everything inside your vendor folder. Add a line to your gemfile

gem 'json', '1.8.0'

Then run - bundle update json.

It seems to be an issue with 1.8.1 so going back to 1.8.0 did the trick for me.

java how to use classes in other package?

You have to provide the full path that you want to import.

import com.my.stuff.main.Main;
import com.my.stuff.second.*;

So, in your main class, you'd have:

package com.my.stuff.main

import com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION

class Main {
   public static void main(String[] args) {
      Second second = new Second();
      second.x();  
   }
}

EDIT: adding example in response to Shawn D's comment

There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:

class Main {
    void function() {
        int x = my.package.heirarchy.Foo.aStaticMethod();

        another.package.heirarchy.Baz b = new another.package.heirarchy.Bax();
    }
}

Alternatively, this is useful when you want to differentiate between two classes with the same short name:

class Main {
    void function() {
        java.util.Date utilDate = ...;
        java.sql.Date sqlDate = ...;
    }
}

How to grep Git commit diffs or contents for a certain word?

If you want search for sensitive data in order to remove it from your git history (which is the reason why I landed here), there are tools for that. Github as a dedicated help page for that issue.

Here is the gist of the article:

The BFG Repo-Cleaner is a faster, simpler alternative to git filter-branch for removing unwanted data. For example, to remove your file with sensitive data and leave your latest commit untouched), run:

bfg --delete-files YOUR-FILE-WITH-SENSITIVE-DATA

To replace all text listed in passwords.txt wherever it can be found in your repository's history, run:

bfg --replace-text passwords.txt

See the BFG Repo-Cleaner's documentation for full usage and download instructions.

Run a JAR file from the command line and specify classpath

You can do these in unix shell:

java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

You can do these in windows powershell:

java -cp "MyJar.jar;lib\*" com.somepackage.subpackage.Main

How to open a Bootstrap modal window using jQuery?

I tried several methods which failed, but the below worked for me like a charm:

$('#myModal').appendTo("body").modal('show');

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

You don't need to muck about with extracting parts of the date. Just cast it to a date using to_date and the format in which its stored, then cast that date to a char in the format you want. Like this:

select to_char(to_date('1/10/2011','mm/dd/yyyy'),'mm-dd-yyyy') from dual

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Just wanted to point out another reason this error can be thrown is if you defined a string resource for one translation of your app but did not provide a default string resource.

Example of the Issue:

As you can see below, I had a string resource for a Spanish string "get_started". It can still be referenced in code, but if the phone is not in Spanish it will have no resource to load and crash when calling getString().

values-es/strings.xml

<string name="get_started">SIGUIENTE</string>

Reference to resource

textView.setText(getString(R.string.get_started)

Logcat:

06-11 11:46:37.835    7007-7007/? E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.app.test PID: 7007
android.content.res.Resources$NotFoundException: String resource ID #0x7f0700fd
        at android.content.res.Resources.getText(Resources.java:299)
        at android.content.res.Resources.getString(Resources.java:385)
        at com.juvomobileinc.tigousa.ui.signin.SignInFragment$4.onClick(SignInFragment.java:188)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution to the Issue

Preventing this is quite simple, just make sure that you always have a default string resource in values/strings.xml so that if the phone is in another language it will always have a resource to fall back to.

values/strings.xml

<string name="get_started">Get Started</string>

values-en/strings.xml

<string name="get_started">Get Started</string>

values-es/strings.xml

<string name="get_started">Siguiente</string>

values-de/strings.xml

<string name="get_started">Ioslegen</string>

How to completely remove a dialog on close

I use this function in all my js projects

You call it: hideAndResetModals("#IdModalDialog")

You define if:

function hideAndResetModals(modalID)
{
    $(modalID).modal('hide');
    clearValidation(modalID); //You implement it if you need it. If not, you can remote this line
    $(modalID).on('hidden.bs.modal', function () 
    {
        $(modalID).find('form').trigger('reset');  
    });
}

Animate element to auto height with jQuery

If all you are wanting is to show and hide say a div, then this code will let you use jQuery animate. You can have jQuery animate the majority of the height you wish or you can trick animate by animating to 0px. jQuery just needs a height set by jQuery to convert it to auto. So the .animate adds the style="" to the element that .css(height:auto) converts.

The cleanest way I have seen this work is to animate to around the height you expect, then let it set auto and it can look very seamless when done right. You can even animate past what you expect and it will snap back. Animating to 0px at a duration of 0 just simply drops the element height to its auto height. To the human eye, it looks animated anyway. Enjoy..

    jQuery("div").animate({
         height: "0px"/*or height of your choice*/
    }, {
         duration: 0,/*or speed of your choice*/
         queue: false, 
         specialEasing: {
             height: "easeInCirc"
        },
         complete: function() {
             jQuery(this).css({height:"auto"});
        }
    });

Sorry I know this is an old post, but I felt this would be relevant to users seeking this functionality still with jQuery who come across this post.

What's the right way to create a date in Java?

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

How would you make a comma-separated string from a list of strings?

Unless I'm missing something, ','.join(foo) should do what you're asking for.

>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'

(edit: and as jmanning2k points out,

','.join([str(x) for x in foo])

is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas -- at that point, you need the full power of the csv module, as Douglas points out in his answer.)

Setting Inheritance and Propagation flags with set-acl and powershell

Here's the MSDN page describing the flags and what is the result of their various combinations.

Flag combinations => Propagation results
=========================================
No Flags => Target folder.
ObjectInherit => Target folder, child object (file), grandchild object (file).
ObjectInherit and NoPropagateInherit => Target folder, child object (file).
ObjectInherit and InheritOnly => Child object (file), grandchild object (file).
ObjectInherit, InheritOnly, and NoPropagateInherit => Child object (file).
ContainerInherit => Target folder, child folder, grandchild folder.
ContainerInherit, and NoPropagateInherit => Target folder, child folder.
ContainerInherit, and InheritOnly => Child folder, grandchild folder.
ContainerInherit, InheritOnly, and NoPropagateInherit => Child folder.
ContainerInherit, and ObjectInherit => Target folder, child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, and NoPropagateInherit => Target folder, child folder, child object (file).
ContainerInherit, ObjectInherit, and InheritOnly => Child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, NoPropagateInherit, InheritOnly => Child folder, child object (file).

To have it apply the permissions to the directory, as well as all child directories and files recursively, you'll want to use these flags:

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit 
PropagationFlags.None

So the specific code change you need to make for your example is:

$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None

How to export data as CSV format from SQL Server using sqlcmd?

You can do it in a hackish way. Careful using the sqlcmd hack. If the data has double quotes or commas you will run into trouble.

You can use a simple script to do it properly:

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Data Exporter                                                 '
'                                                               '
' Description: Allows the output of data to CSV file from a SQL '
'       statement to either Oracle, SQL Server, or MySQL        '
' Author: C. Peter Chen, http://dev-notes.com                   '
' Version Tracker:                                              '
'       1.0   20080414 Original version                         '
'   1.1   20080807 Added email functionality                '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
option explicit
dim dbType, dbHost, dbName, dbUser, dbPass, outputFile, email, subj, body, smtp, smtpPort, sqlstr

'''''''''''''''''
' Configuration '
'''''''''''''''''
dbType = "oracle"                 ' Valid values: "oracle", "sqlserver", "mysql"
dbHost = "dbhost"                 ' Hostname of the database server
dbName = "dbname"                 ' Name of the database/SID
dbUser = "username"               ' Name of the user
dbPass = "password"               ' Password of the above-named user
outputFile = "c:\output.csv"      ' Path and file name of the output CSV file
email = "[email protected]"           ' Enter email here should you wish to email the CSV file (as attachment); if no email, leave it as empty string ""
  subj = "Email Subject"          ' The subject of your email; required only if you send the CSV over email
  body = "Put a message here!"    ' The body of your email; required only if you send the CSV over email
  smtp = "mail.server.com"        ' Name of your SMTP server; required only if you send the CSV over email
  smtpPort = 25                   ' SMTP port used by your server, usually 25; required only if you send the CSV over email
sqlStr = "select user from dual"  ' SQL statement you wish to execute
'''''''''''''''''''''
' End Configuration '
'''''''''''''''''''''



dim fso, conn

'Create filesystem object 
set fso = CreateObject("Scripting.FileSystemObject")

'Database connection info
set Conn = CreateObject("ADODB.connection")
Conn.ConnectionTimeout = 30
Conn.CommandTimeout = 30
if dbType = "oracle" then
    conn.open("Provider=MSDAORA.1;User ID=" & dbUser & ";Password=" & dbPass & ";Data Source=" & dbName & ";Persist Security Info=False")
elseif dbType = "sqlserver" then
    conn.open("Driver={SQL Server};Server=" & dbHost & ";Database=" & dbName & ";Uid=" & dbUser & ";Pwd=" & dbPass & ";")
elseif dbType = "mysql" then
    conn.open("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=" & dbHost & ";PORT=3306;DATABASE=" & dbName & "; UID=" & dbUser & "; PASSWORD=" & dbPass & "; OPTION=3")
end if

' Subprocedure to generate data.  Two parameters:
'   1. fPath=where to create the file
'   2. sqlstr=the database query
sub MakeDataFile(fPath, sqlstr)
    dim a, showList, intcount
    set a = fso.createtextfile(fPath)

    set showList = conn.execute(sqlstr)
    for intcount = 0 to showList.fields.count -1
        if intcount <> showList.fields.count-1 then
            a.write """" & showList.fields(intcount).name & ""","
        else
            a.write """" & showList.fields(intcount).name & """"
        end if
    next
    a.writeline ""

    do while not showList.eof
        for intcount = 0 to showList.fields.count - 1
            if intcount <> showList.fields.count - 1 then
                a.write """" & showList.fields(intcount).value & ""","
            else
                a.write """" & showList.fields(intcount).value & """"
            end if
        next
        a.writeline ""
        showList.movenext
    loop
    showList.close
    set showList = nothing

    set a = nothing
end sub

' Call the subprocedure
call MakeDataFile(outputFile,sqlstr)

' Close
set fso = nothing
conn.close
set conn = nothing

if email <> "" then
    dim objMessage
    Set objMessage = CreateObject("CDO.Message")
    objMessage.Subject = "Test Email from vbs"
    objMessage.From = email
    objMessage.To = email
    objMessage.TextBody = "Please see attached file."
    objMessage.AddAttachment outputFile

    objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
    objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = smtpPort

objMessage.Configuration.Fields.Update

    objMessage.Send
end if

'You're all done!!  Enjoy the file created.
msgbox("Data Writer Done!")

Source: Writing SQL output to CSV with VBScript.

What does %~dp0 mean, and how does it work?

Calling

for /?

in the command-line gives help about this syntax (which can be used outside FOR, too, this is just the place where help can be found).

In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

The modifiers can be combined to get compound results:

%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
               environment variable for %I and expands to the
               drive letter and path of the first one found.
%~ftzaI     - expands %I to a DIR like output line

In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.

There are different letters you can use like f for "full path name", d for drive letter, p for path, and they can be combined. %~ is the beginning for each of those sequences and a number I denotes it works on the parameter %I (where %0 is the complete name of the batch file, just like you assumed).

How to call a Python function from Node.js

Example for people who are from Python background and want to integrate their machine learning model in the Node.js application:

It uses the child_process core module:

const express = require('express')
const app = express()

app.get('/', (req, res) => {

    const { spawn } = require('child_process');
    const pyProg = spawn('python', ['./../pypy.py']);

    pyProg.stdout.on('data', function(data) {

        console.log(data.toString());
        res.write(data);
        res.end('end');
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

It doesn't require sys module in your Python script.

Below is a more modular way of performing the task using Promise:

const express = require('express')
const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./../pypy.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(fromRunpy) {
        console.log(fromRunpy.toString());
        res.end(fromRunpy);
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

Android ImageView Fixing Image Size

In your case you need to

  1. Fix the ImageView's size. You need to use dp unit so that it will look the same in all devices.
  2. Set android:scaleType to fitXY

Below is an example:

<ImageView
    android:id="@+id/photo"
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:src="@drawable/iclauncher" 
    android:scaleType="fitXY"/>

For more information regarding ImageView scaleType please refer to the developer website.

How to I say Is Not Null in VBA

Use Not IsNull(Fields!W_O_Count.Value)

Calculate number of hours between 2 dates in PHP

This is working in my project. I think, This will be helpful for you.

If Date is in past then invert will 1.
If Date is in future then invert will 0.

$defaultDate = date('Y-m-d');   
$datetime1   = new DateTime('2013-03-10');  
$datetime2   = new DateTime($defaultDate);  
$interval    = $datetime1->diff($datetime2);  
$days        = $interval->format('%a');
$invert      = $interval->invert;

Pythonically add header to a csv file

You just add one additional row before you execute the loop. This row contains your CSV file header name.

schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:    
     writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
     writer.writerow([g for g in schema])   
#Data add in csv file       
     for x in xrange(rows):
         writer.writerow([g() for g in generators])

How to validate phone number in laravel 5.2?

There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)

How to show progress bar while loading, using ajax

_x000D_
_x000D_
$(document).ready(function () { _x000D_
 $(document).ajaxStart(function () {_x000D_
        $('#wait').show();_x000D_
    });_x000D_
    $(document).ajaxStop(function () {_x000D_
        $('#wait').hide();_x000D_
    });_x000D_
    $(document).ajaxError(function () {_x000D_
        $('#wait').hide();_x000D_
    });   _x000D_
});
_x000D_
<div id="wait" style="display: none; width: 100%; height: 100%; top: 100px; left: 0px; position: fixed; z-index: 10000; text-align: center;">_x000D_
            <img src="../images/loading_blue2.gif" width="45" height="45" alt="Loading..." style="position: fixed; top: 50%; left: 50%;" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Should I learn C before learning C++?

I love this question - it's like asking "what should I learn first, snowboarding or skiing"? I think it depends if you want to snowboard or to ski. If you want to do both, you have to learn both.

In both sports, you slide down a hill on snow using devices that are sufficiently similar to provoke this question. However, they are also sufficiently different so that learning one does not help you much with the other. Same thing with C and C++. While they appear to be languages sufficiently similar in syntax, the mind set that you need for writing OO code vs procedural code is sufficiently different so that you pretty much have to start from the beginning, whatever language you learn second.

Http Basic Authentication in Java using HttpClient?

Thanks for all answers above, but for me, I can not find Base64Encoder class, so I sort out my way anyway.

public static void main(String[] args) {
    try {
        DefaultHttpClient Client = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet("https://httpbin.org/basic-auth/user/passwd");
        String encoding = DatatypeConverter.printBase64Binary("user:passwd".getBytes("UTF-8"));
        httpGet.setHeader("Authorization", "Basic " + encoding);

        HttpResponse response = Client.execute(httpGet);

        System.out.println("response = " + response);

        BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder responseString = new StringBuilder();
        String line = "";
        while ((line = breader.readLine()) != null) {
            responseString.append(line);
        }
        breader.close();
        String repsonseStr = responseString.toString();

        System.out.println("repsonseStr = " + repsonseStr);

    } catch (IOException e) {
        e.printStackTrace();
    }

}

One more thing, I also tried

Base64.encodeBase64String("user:passwd".getBytes());

It does NOT work due to it return a string almost same with

DatatypeConverter.printBase64Binary()

but end with "\r\n", then server will return "bad request".

Also following code is working as well, actually I sort out this first, but for some reason, it does NOT work in some cloud environment (sae.sina.com.cn if you want to know, it is a chinese cloud service). so have to use the http header instead of HttpClient credentials.

public static void main(String[] args) {
    try {
        DefaultHttpClient Client = new DefaultHttpClient();
        Client.getCredentialsProvider().setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials("user", "passwd")
        );

        HttpGet httpGet = new HttpGet("https://httpbin.org/basic-auth/user/passwd");
        HttpResponse response = Client.execute(httpGet);

        System.out.println("response = " + response);

        BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder responseString = new StringBuilder();
        String line = "";
        while ((line = breader.readLine()) != null) {
            responseString.append(line);
        }
        breader.close();
        String responseStr = responseString.toString();
        System.out.println("responseStr = " + responseStr);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

I also encountered this exception with error message,

java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(Unknown Source)
at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.BufferedWriter.write(Unknown Source)
at java.io.Writer.write(Unknown Source)

and found that some strange bug occurs when trying to use

BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath));

to write a String "orazg 54" cast from a generic type in a class.

//key is of generic type <Key extends Comparable<Key>>
writer.write(item.getKey() + "\t" + item.getValue() + "\n");

This String is of length 9 containing chars with the following code points:

111 114 97 122 103 9 53 52 10

However, if the BufferedWriter in the class is replaced with:

FileOutputStream outputStream = new FileOutputStream(filePath);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));

it can successfully write this String without exceptions. In addition, if I write the same String create from the characters it still works OK.

String string = new String(new char[] {111, 114, 97, 122, 103, 9, 53, 52, 10});
BufferedWriter writer = Files.newBufferedWriter(Paths.get("a.txt"));
writer.write(string);
writer.close();

Previously I have never encountered any Exception when using the first BufferedWriter to write any Strings. It's a strange bug that occurs to BufferedWriter created from java.nio.file.Files.newBufferedWriter(path, options)

(13: Permission denied) while connecting to upstream:[nginx]

  1. Check the user in /etc/nginx/nginx.conf
  2. Change ownership to user.
sudo chown -R nginx:nginx /var/lib/nginx

Now see the magic.

How to disable EditText in Android

Just set focusable property of your edittext to "false" and you are done.

<EditText
        android:id="@+id/EditTextInput"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:gravity="right"
        android:cursorVisible="true">
    </EditText>

Below options doesn't work

In code:

editText.setEnabled(false); Or, in XML: android:editable="false"

How to insert a text at the beginning of a file?

Use subshell:

echo "$(echo -n 'hello'; cat filename)" > filename

Unfortunately, command substitution will remove newlines at the end of file. So as to keep them one can use:

echo -n "hello" | cat - filename > /tmp/filename.tmp
mv /tmp/filename.tmp filename

Neither grouping nor command substitution is needed.

PHP check if date between two dates

function get_format($df) {

    $str = '';
    $str .= ($df->invert == 1) ? ' - ' : '';
    if ($df->y > 0) {
        // years
        $str .= ($df->y > 1) ? $df->y . ' Years ' : $df->y . ' Year ';
    } if ($df->m > 0) {
        // month
        $str .= ($df->m > 1) ? $df->m . ' Months ' : $df->m . ' Month ';
    } if ($df->d > 0) {
        // days
        $str .= ($df->d > 1) ? $df->d . ' Days ' : $df->d . ' Day ';
    } 

    echo $str;
}

$yr=$year;
$dates=$dor;
$myyear='+'.$yr.' years';
$new_date = date('Y-m-d', strtotime($myyear, strtotime($dates)));
$date1 = new DateTime("$new_date");
$date2 = new DateTime("now");
$diff = $date2->diff($date1);

Oracle client ORA-12541: TNS:no listener

I also faced the same problem but I resolved the issue by starting the TNS listener in control panel -> administrative tools -> services ->oracle TNS listener start.I am using windows Xp and Toad to connect to Oracle.

JavaScript unit test tools for TDD

MochiKit has a testing framework called SimpleTest that seems to have caught on. Here's a blog post from the original author.

adb uninstall failed

If You use Xiomi Device then You need to Login in MI Account.

After Successful Registration you can install and Uninstall via ADB.

Run CSS3 animation only once (at page loading)

It can be done with a little bit of extra overhead.

Simply wrap your link in a div, and separate the animation.

the html ..

<div class="animateOnce">
    <a class="animateOnHover">me!</a>
</div>

.. and the css ..

.animateOnce {
    animation: splash 1s normal forwards ease-in-out;
}

.animateOnHover:hover {
    animation: hover 1s infinite alternate ease-in-out;
}

How to redirect to another page using PHP

header won't work for all

Use below simple code

<?php
        echo "<script> location.href='new_url'; </script>";
        exit;
?>

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

You may also get this warning for MS Fakes assemblies which isn't as easy to resolve since the f.csproj is build on command. Luckily the Fakes xml allows you to add it in there.

How do I write the 'cd' command in a makefile?

Here's a cute trick to deal with directories and make. Instead of using multiline strings, or "cd ;" on each command, define a simple chdir function as so:

CHDIR_SHELL := $(SHELL)
define chdir
   $(eval _D=$(firstword $(1) $(@D)))
   $(info $(MAKE): cd $(_D)) $(eval SHELL = cd $(_D); $(CHDIR_SHELL))
endef

Then all you have to do is call it in your rule as so:

all:
          $(call chdir,some_dir)
          echo "I'm now always in some_dir"
          gcc -Wall -o myTest myTest.c

You can even do the following:

some_dir/myTest:
          $(call chdir)
          echo "I'm now always in some_dir"
          gcc -Wall -o myTest myTest.c

PHP exec() vs system() vs passthru()

It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.

  • exec executes a command and passes output to the caller (or returns it in an optional variable).

  • passthru is similar to the exec() function in that it executes a command . This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser.

  • system executes an external program and displays the output, but only the last line.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

Counting the occurrences / frequency of array elements

Its easy with filter

In this example we simply assign count, the length of the array filtered by the key you're looking for

let array = [{name: "steve", age: 22}, {name: "bob", age: 30}]

let count = array.filter(obj => obj.name === obj.name).length

console.log(count)

more on JS Filiters here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

How to get the sizes of the tables of a MySQL database?

select x.dbname as db_name, x.table_name as table_name, x.bytesize as the_size from
  (select
     table_schema as dbname,
     sum(index_length+data_length) as bytesize,
     table_name
   from
     information_schema.tables
   group by table_schema
  ) x
where
  x.bytesize > 999999
order by x.bytesize desc;

Handle Button click inside a row in RecyclerView

Just wanted to add another solution if you already have a recycler touch listener and want to handle all of the touch events in it rather than dealing with the button touch event separately in the view holder. The key thing this adapted version of the class does is return the button view in the onItemClick() callback when it's tapped, as opposed to the item container. You can then test for the view being a button, and carry out a different action. Note, long tapping on the button is interpreted as a long tap on the whole row still.

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener
{
    public static interface OnItemClickListener
    {
        public void onItemClick(View view, int position);
        public void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;
    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
    {
        mListener = listener;

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
        {
            @Override
            public boolean onSingleTapUp(MotionEvent e)
            {
                // Important: x and y are translated coordinates here
                final ViewGroup childViewGroup = (ViewGroup) recyclerView.findChildViewUnder(e.getX(), e.getY());

                if (childViewGroup != null && mListener != null) {
                    final List<View> viewHierarchy = new ArrayList<View>();
                    // Important: x and y are raw screen coordinates here
                    getViewHierarchyUnderChild(childViewGroup, e.getRawX(), e.getRawY(), viewHierarchy);

                    View touchedView = childViewGroup;
                    if (viewHierarchy.size() > 0) {
                        touchedView = viewHierarchy.get(0);
                    }
                    mListener.onItemClick(touchedView, recyclerView.getChildPosition(childViewGroup));
                    return true;
                }

                return false;
            }

            @Override
            public void onLongPress(MotionEvent e)
            {
                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

                if(childView != null && mListener != null)
                {
                    mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
                }
            }
        });
    }

    public void getViewHierarchyUnderChild(ViewGroup root, float x, float y, List<View> viewHierarchy) {
        int[] location = new int[2];
        final int childCount = root.getChildCount();

        for (int i = 0; i < childCount; ++i) {
            final View child = root.getChildAt(i);
            child.getLocationOnScreen(location);
            final int childLeft = location[0], childRight = childLeft + child.getWidth();
            final int childTop = location[1], childBottom = childTop + child.getHeight();

            if (child.isShown() && x >= childLeft && x <= childRight && y >= childTop && y <= childBottom) {
                viewHierarchy.add(0, child);
            }
            if (child instanceof ViewGroup) {
                getViewHierarchyUnderChild((ViewGroup) child, x, y, viewHierarchy);
            }
        }
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
    {
        mGestureDetector.onTouchEvent(e);

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

Then using it from activity / fragment:

recyclerView.addOnItemTouchListener(createItemClickListener(recyclerView));

    public RecyclerItemClickListener createItemClickListener(final RecyclerView recyclerView) {
        return new RecyclerItemClickListener (context, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (view instanceof AppCompatButton) {
                    // ... tapped on the button, so go do something
                } else {
                    // ... tapped on the item container (row), so do something different
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
            }
        });
    }

Can iterators be reset in Python?

Yes, if you use numpy.nditer to build your iterator.

>>> lst = [1,2,3,4,5]
>>> itr = numpy.nditer([lst])
>>> itr.next()
1
>>> itr.next()
2
>>> itr.finished
False
>>> itr.reset()
>>> itr.next()
1

Simple division in Java - is this a bug or a feature?

You've used integers in the expression 7/10, and integer 7 divided by integer 10 is zero.

What you're expecting is floating point division. Any of the following would evaluate the way you expected:

7.0 / 10
7 / 10.0
7.0 / 10.0
7 / (double) 10

How can I determine if a variable is 'undefined' or 'null'?

Probably the shortest way to do this is:

if(EmpName == null) { /* DO SOMETHING */ };

Here is proof:

_x000D_
_x000D_
function check(EmpName) {_x000D_
  if(EmpName == null) { return true; };_x000D_
  return false;_x000D_
}_x000D_
_x000D_
var log = (t,a) => console.log(`${t} -> ${check(a)}`);_x000D_
_x000D_
log('null', null);_x000D_
log('undefined', undefined);_x000D_
log('NaN', NaN);_x000D_
log('""', "");_x000D_
log('{}', {});_x000D_
log('[]', []);_x000D_
log('[1]', [1]);_x000D_
log('[0]', [0]);_x000D_
log('[[]]', [[]]);_x000D_
log('true', true);_x000D_
log('false', false);_x000D_
log('"true"', "true");_x000D_
log('"false"', "false");_x000D_
log('Infinity', Infinity);_x000D_
log('-Infinity', -Infinity);_x000D_
log('1', 1);_x000D_
log('0', 0);_x000D_
log('-1', -1);_x000D_
log('"1"', "1");_x000D_
log('"0"', "0");_x000D_
log('"-1"', "-1");_x000D_
_x000D_
// "void 0" case_x000D_
console.log('---\n"true" is:', true);_x000D_
console.log('"void 0" is:', void 0);_x000D_
log(void 0,void 0); // "void 0" is "undefined" 
_x000D_
_x000D_
_x000D_

And here are more details about == (source here)

Enter image description here

BONUS: reason why === is more clear than == (look on agc answer)

Enter image description here

This action could not be completed. Try Again (-22421)

Just try exporting the iPA file and then upload that exported iPA file with application loader. It will solve your problem.

What does the error "arguments imply differing number of rows: x, y" mean?

I had the same error message so I went googling a bit I managed to fix it with the following code.

df<-data.frame(words = unlist(words))

words is a character list.

This just in case somebody else needs the output to be a data frame.

Why do people say that Ruby is slow?

Ruby is slower than C++ at a number of easily measurable tasks (e.g., doing code that is heavily dependent on floating point). This is not very surprising, but enough justification for some people to say that “Ruby is Slow” without qualification. They don't count the fact that it is far easier and safer to write Ruby code than C++.

The best fix is to use targeted modules written in another language (e.g., C, C++, Fortran) in your Ruby code. Those can do the heavy lifting and your scripts can focus on higher level coordination issues.

JSON.stringify output to div in pretty print way

If this is really for a user, better than just outputting text, you can use a library like this one https://github.com/padolsey/prettyprint.js to output it as an HTML table.

CSS no text wrap

Use the css property overflow . For example:

  .item{
    width : 100px;
    overflow:hidden;
  }

The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.

I hope this helps.

Having links relative to root?

A root-relative URL starts with a / character, to look something like <a href="/directoryInRoot/fileName.html">link text</a>.

The link you posted: <a href="fruits/index.html">Back to Fruits List</a> is linking to an html file located in a directory named fruits, the directory being in the same directory as the html page in which this link appears.

To make it a root-relative URL, change it to:

<a href="/fruits/index.html">Back to Fruits List</a>

Edited in response to question, in comments, from OP:

So doing / will make it relative to www.example.com, is there a way to specify what the root is, e.g what if i want the root to be www.example.com/fruits in www.example.com/fruits/apples/apple.html?

Yes, prefacing the URL, in the href or src attributes, with a / will make the path relative to the root directory. For example, given the html page at www.example.com/fruits/apples.html, the a of href="/vegetables/carrots.html" will link to the page www.example.com/vegetables/carrots.html.

The base tag element allows you to specify the base-uri for that page (though the base tag would have to be added to every page in which it was necessary for to use a specific base, for this I'll simply cite the W3's example:

For example, given the following BASE declaration and A declaration:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
 <HEAD>
   <TITLE>Our Products</TITLE>
   <BASE href="http://www.aviary.com/products/intro.html">
 </HEAD>

 <BODY>
   <P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?
 </BODY>
</HTML>

the relative URI "../cages/birds.gif" would resolve to:

http://www.aviary.com/cages/birds.gif

Example quoted from: http://www.w3.org/TR/html401/struct/links.html#h-12.4.

Suggested reading:

MAC addresses in JavaScript

Nope. The reason ActiveX can do it is because ActiveX is a little application that runs on the client's machine.

I would imagine access to such information via JavaScript would be a security vulnerability.

Returning string from C function

word is on the stack and goes out of scope as soon as getStr() returns. You are invoking undefined behavior.

Accessing an SQLite Database in Swift

I too was looking for some way to interact with SQLite the same way I was used to doing previously in Objective-C. Admittedly, because of C compatibility, I just used the straight C API.

As no wrapper currently exists for SQLite in Swift and the SQLiteDB code mentioned above goes a bit higher level and assumes certain usage, I decided to create a wrapper and get a bit familiar with Swift in the process. You can find it here: https://github.com/chrismsimpson/SwiftSQLite.

var db = SQLiteDatabase();
db.open("/path/to/database.sqlite");

var statement = SQLiteStatement(database: db);

if ( statement.prepare("SELECT * FROM tableName WHERE Id = ?") != .Ok )
{
    /* handle error */
}

statement.bindInt(1, value: 123);

if ( statement.step() == .Row )
{
    /* do something with statement */
    var id:Int = statement.getIntAt(0)
    var stringValue:String? = statement.getStringAt(1)
    var boolValue:Bool = statement.getBoolAt(2)
    var dateValue:NSDate? = statement.getDateAt(3)
}

statement.finalizeStatement(); /* not called finalize() due to destructor/language keyword */

How to append the output to a file?

Use >> to append:

command >> file

Tricks to manage the available memory in an R session

For both speed and memory purposes, when building a large data frame via some complex series of steps, I'll periodically flush it (the in-progress data set being built) to disk, appending to anything that came before, and then restart it. This way the intermediate steps are only working on smallish data frames (which is good as, e.g., rbind slows down considerably with larger objects). The entire data set can be read back in at the end of the process, when all the intermediate objects have been removed.

dfinal <- NULL
first <- TRUE
tempfile <- "dfinal_temp.csv"
for( i in bigloop ) {
    if( !i %% 10000 ) { 
        print( i, "; flushing to disk..." )
        write.table( dfinal, file=tempfile, append=!first, col.names=first )
        first <- FALSE
        dfinal <- NULL   # nuke it
    }

    # ... complex operations here that add data to 'dfinal' data frame  
}
print( "Loop done; flushing to disk and re-reading entire data set..." )
write.table( dfinal, file=tempfile, append=TRUE, col.names=FALSE )
dfinal <- read.table( tempfile )

Edit existing excel workbooks and sheets with xlrd and xlwt

Here's another way of doing the code above using the openpyxl module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.

from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')

How do I hide anchor text without hiding the anchor?

I have followed the best answer of Loktar and it worked very well. The only problem I had was with Chrome (my current version is 27.0.1453.94 m). The problem I had was that it seems Chrome is aware that the text in the link is not visible and it puts the link a little bit lower then it is supposed to be (something like margin-top, but it is not possible to change it). This happens with all the ways in which we make the text invisible: - line-height: 0; - font-size: 0; - text-indent:-9999px;

I was able to fix this problem by adjusting the vertical-align of the link like this:

vertical-align: 25px;

I hope this is helpful

Attach Authorization header for all axios requests

Similarly, we have a function to set or delete the token from calls like this:

import axios from 'axios';

export default function setAuthToken(token) {
  axios.defaults.headers.common['Authorization'] = '';
  delete axios.defaults.headers.common['Authorization'];

  if (token) {
    axios.defaults.headers.common['Authorization'] = `${token}`;
  }
}

We always clean the existing token at initialization, then establish the received one.

How to convert buffered image to image and vice-versa?

BufferedImage is a subclass of Image. You don't need to do any conversion.

Python memory leaks

I tried out most options mentioned previously but found this small and intuitive package to be the best: pympler

It's quite straight forward to trace objects that were not garbage-collected, check this small example:

install package via pip install pympler

from pympler.tracker import SummaryTracker
tracker = SummaryTracker()

# ... some code you want to investigate ...

tracker.print_diff()

The output shows you all the objects that have been added, plus the memory they consumed.

Sample output:

                                 types |   # objects |   total size
====================================== | =========== | ============
                                  list |        1095 |    160.78 KB
                                   str |        1093 |     66.33 KB
                                   int |         120 |      2.81 KB
                                  dict |           3 |       840 B
      frame (codename: create_summary) |           1 |       560 B
          frame (codename: print_diff) |           1 |       480 B

This package provides a number of more features. Check pympler's documentation, in particular the section Identifying memory leaks.

How can I display just a portion of an image in HTML/CSS?

One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want.

check output from CalledProcessError

This will return true only if host responds to ping. Works on windows and linux

def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    NB on windows ping returns true for success and host unreachable
    """
    param = '-n' if platform.system().lower()=='windows' else '-c'
    result = False
    try:
        out = subprocess.check_output(['ping', param, '1', host])
        #ping exit code 0
        if 'Reply from {}'.format(host) in str(out):
            result = True          
    except  subprocess.CalledProcessError:
        #ping exit code not 0
            result = False
    #print(str(out))
    return result

VIM Disable Automatic Newline At End Of File

I think I've found a better solution than the accepted answer. The alternative solutions weren't working for me and I didn't want to have to work in binary mode all the time. Fortunately this seems to get the job done and I haven't encountered any nasty side-effects yet: preserve missing end-of-line at end of text files. I just added the whole thing to my ~/.vimrc.

How do I request a file but not save it with Wget?

Curl does that by default without any parameters or flags, I would use it for your purposes:

curl $url > /dev/null 2>&1

Curl is more about streams and wget is more about copying sites based on this comparison.

How to remove old and unused Docker images

@VonC already gave a very nice answer, but for completeness here is a little script I have been using---and which also nukes any errand Docker processes should you have some:

#!/bin/bash

imgs=$(docker images | awk '/<none>/ { print $3 }')
if [ "${imgs}" != "" ]; then
   echo docker rmi ${imgs}
   docker rmi ${imgs}
else
   echo "No images to remove"
fi

procs=$(docker ps -a -q --no-trunc)
if [ "${procs}" != "" ]; then
   echo docker rm ${procs}
   docker rm ${procs}
else
   echo "No processes to purge"
fi

How to increase executionTimeout for a long-running query?

You can set executionTimeout in web.config to support the longer execution time.

executionTimeout specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. MSDN

<httpRuntime  executionTimeout = "300" />

This make execution timeout to five minutes.

Optional Int32 attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging. The default is 110 seconds, Reference.

ComboBox SelectedItem vs SelectedValue

The ComboBox control inherits from the ListControl control.

The SelectedItem property is a proper member of the ComboBox control. The event that is fired on change is ComboBox.SelectionChangeCommitted

ComboBox.SelectionChangeCommitted

Occurs when the selected item has changed and that change is displayed in the ComboBox.

The SelectedValue property is inherited from the ListControl control. As such, this property will fire the ListControl.SelectedValueChanged event.

ListControl.SelectedValueChanged

Occurs when the SelectedValue property changes.

That said, they won't fire the INotifyPropertyChanged.PropertyChanged event the same, but they will anyway. The only difference is in the firing event. SelectedValueChanged is fired as soon as a new selection is made from the list part of the ComboBox, and SelectedItemChanged is fired when the item is displayed in the TextBox portion of the ComboBox.

In short, they both represent something in the list part of the ComboBox. So, when binding either property, the result is the same, since the PropertyChanged event is fired in either case. And since they both represent an element from the list, the they are probably treated the same.

Does this help?

EDIT #1

Assuming that the list part of the ComboBox represents a property (as I can't confirm since I didn't write the control), binding either of SelectedItem or SelectedValue affects the same collection inside the control. Then, when this property is changed, the same occurs in the end. The INotifyPropertryPropertyChanged.PropertyChanged event is fired on the same property.

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.

Hope, it will help you.

Converting Integer to String with comma for thousands

here's a solution for those of you who can't access "numberformat" nor "String.format" (using a limited version of java inside a framework). Hope it's useful.

number= 123456789;
thousandsSeparator=",";
myNumberString=number.toString();   
numberLength=myNumberString.length;
howManySeparators=Math.floor((numberLength-1)/3)
formattedString=myNumberString.substring(0,numberLength-(howManySeparators*3))
while (howManySeparators>0)    {
formattedString=formattedString+thousandsSeparator+myNumberString.substring(numberLength-(howManySeparators*3),numberLength-((howManySeparators-1)*3));
howManySeparators=howManySeparators-1;    }

formattedString

How can I replace text with CSS?

This isn't really possible without tricks. Here is a way that works by replacing the text with an image of text.

.pvw-title{
    text-indent: -9999px;
    background-image: url(text_image.png)
}

This type of thing is typically done with JavaScript. Here is how it can be done with jQuery:

$('.pvw-title').text('new text');

Specified cast is not valid.. how to resolve this

If you are expecting double, decimal, float, integer why not use the one which accomodates all namely decimal (128 bits are enough for most numbers you are looking at).

instead of (double)value use decimal.Parse(value.ToString()) or Convert.ToDecimal(value)

Is there a "previous sibling" selector?

I had a similar problem and found out that all problem of this nature can be solved as follows:

  1. give all your items a style.
  2. give your selected item a style.
  3. give next items a style using + or ~.

and this way you'll be able to style your current, previous items(all items overridden with current and next items) and your next items.

example:

/* all items (will be styled as previous) */
li {
  color: blue;
}

/* the item i want to distinguish */
li.milk {
  color: red;
}

/* next items */
li ~ li  {
  color: green;
}


<ul>
  <li>Tea</li>
  <li class="milk">Milk</li>
  <li>Juice</li>
  <li>others</li>
</ul>

Hope it helps someone.

How to get the data-id attribute?

Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will NOT be reflected in the data() jQuery function. You have to adjust it via data() function as well.

<a data-id="123">link</a>

js:

$(this).data("id") // returns 123
$(this).attr("data-id", "321"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "321")
$(this).data("id") // NOW we have 321

How to get the Facebook user id using the access token

in FacebookSDK v2.1 (I can't check older version). We have

NSString *currentUserFBID = [FBSession activeSession].accessTokenData.userID;

However according to the comment in FacebookSDK

@discussion This may not be populated for login behaviours such as the iOS system account.

So may be you should check if it is available, and then whether use it, or call the request to get the user id

How to install a specific version of package using Composer?

As @alucic mentioned, use:

composer require vendor/package:version

or you can use:

composer update vendor/package:version

You should probably review this StackOverflow post about differences between composer install and composer update.

Related to question about version numbers, you can review Composer documentation on versions, but here in short:

  • Tilde Version Range (~) - ~1.2.3 is equivalent to >=1.2.3 <1.3.0
  • Caret Version Range (^) - ^1.2.3 is equivalent to >=1.2.3 <2.0.0

So, with Tilde you will get automatic updates of patches but minor and major versions will not be updated. However, if you use Caret you will get patches and minor versions, but you will not get major (breaking changes) versions.

Tilde Version is considered a "safer" approach, but if you are using reliable dependencies (well-maintained libraries) you should not have any problems with Caret Version (because minor changes should not be breaking changes.

Is Tomcat running?

Why grep ps, when the pid has been written to the $CATALINA_PID file?

I have a cron'd checker script which sends out an email when tomcat is down:

kill -0 `cat $CATALINA_PID` > /dev/null 2>&1
if [ $? -gt 0 ]
then
    echo "Check tomcat" | mailx -s "Tomcat not running" [email protected]
fi

I guess you could also use wget to check the health of your tomcat. If you have a diagnostics page with user load etc, you could fetch it periodically and parse it to determine if anything is going wrong.

process.start() arguments

Not really a direct answer, but I'd highly recommend using LINQPad for this kind of "exploratory" C# programming.

I have the following as a saved "query" in LINQPad:

var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c echo Foo && echo Bar";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardOutput.ReadToEnd().Dump();

Feel free to adapt as needed.

How do I reverse an int array in Java?

public void display(){
  String x[]=new String [5];
  for(int i = 4 ; i > = 0 ; i-- ){//runs backwards

    //i is the nums running backwards therefore its printing from       
    //highest element to the lowest(ie the back of the array to the front) as i decrements

    System.out.println(x[i]);
  }
}

Making Enter key on an HTML form submit instead of activating button

You can use jQuery:

$(function() {
    $("form input").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('button[type=submit] .default').click();
            return false;
        } else {
            return true;
        }
    });
});

How to get Android GPS location

Worked a day for this project. It maybe useful for u. I compressed and combined both Network and GPS. Plug and play directly in MainActivity.java (There are some DIY function for display result)

 ///////////////////////////////////
////////// LOCATION PACK //////////
// 
//  locationManager: (LocationManager) for getting LOCATION_SERVICE
//  osLocation: (Location) getting location data via standard method
//  dataLocation: class type storage locztion data
//    x,y: (Double) Longtitude, Latitude
//  location: (dataLocation) variable contain absolute location info. Autoupdate after run locationStart();
//  AutoLocation: class help getting provider info
//  tmLocation: (Timer) for running update location over time
//  LocationStart(int interval): start getting location data with setting interval time cycle in milisecond
//  LocationStart(): LocationStart(500)
//  LocationStop(): stop getting location data
//
//  EX:
//    LocationStart(); cycleF(new Runnable() {public void run(){bodyM.text("LOCATION \nLatitude: " + location.y+ "\nLongitude: " + location.x).show();}},500);
//

LocationManager locationManager;
Location osLocation;
public class dataLocation {double x,y;}
dataLocation location=new dataLocation();
public class AutoLocation extends Activity implements LocationListener {
    @Override public void onLocationChanged(Location p1){}
    @Override public void onStatusChanged(String p1, int p2, Bundle p3){}
    @Override public void onProviderEnabled(String p1){}
    @Override public void onProviderDisabled(String p1){}
    public Location getLocation(String provider) {
        if (locationManager.isProviderEnabled(provider)) {
            locationManager.requestLocationUpdates(provider,0,0,this);
            if (locationManager != null) {
                osLocation = locationManager.getLastKnownLocation(provider);
                return osLocation;
            }
        }
        return null;
    }
}
Timer tmLocation=new Timer();
public void LocationStart(int interval){
    locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
    final AutoLocation autoLocation = new AutoLocation();
    tmLocation=cycleF(new Runnable() {public void run(){ 
                Location nwLocation = autoLocation.getLocation(LocationManager.NETWORK_PROVIDER);
                if (nwLocation != null) {
                    location.y = nwLocation.getLatitude();
                    location.x = nwLocation.getLongitude();
                } else {
                    //bodym.text("NETWORK_LOCATION is loading...").show();
                }
                Location gpsLocation = autoLocation.getLocation(LocationManager.GPS_PROVIDER);
                if (gpsLocation != null) {
                    location.y = gpsLocation.getLatitude();
                    location.x = gpsLocation.getLongitude();    
                } else {
                    //bodym.text("GPS_LOCATION is loading...").show();
                }   
            }}, interval);
}
public void LocationStart(){LocationStart(500);};
public void LocationStop(){stopCycleF(tmLocation);}

//////////
///END//// LOCATION PACK //////////
//////////


/////////////////////////////
////////// RUNTIME //////////
//
// Need library:
//  import java.util.*;
//
// delayF(r,d): execute runnable r after d millisecond
//   Halt by execute the return: final Runnable rn=delayF(...); (new Handler()).post(rn);
// cycleF(r,i): execute r repeatedly with i millisecond each cycle
// stopCycleF(t): halt execute cycleF via the Timer return of cycleF
// 
// EX:
//   delayF(new Runnable(){public void run(){ sig("Hi"); }},2000);
//   final Runnable rn=delayF(new Runnable(){public void run(){ sig("Hi"); }},3000);
//     delayF(new Runnable(){public void run(){ (new Handler()).post(rn);sig("Hello"); }},1000);
//   final Timer tm=cycleF(new Runnable() {public void run(){ sig("Neverend"); }}, 1000);
//     delayF(new Runnable(){public void run(){ stopCycleF(tm);sig("Ended"); }},7000);
//
public static Runnable delayF(final Runnable r, long delay) {
    final Handler h = new Handler();
    h.postDelayed(r, delay);
    return new Runnable(){
        @Override
        public void run(){h.removeCallbacks(r);}
    };
}
public static Timer cycleF(final Runnable r, long interval) {
    final Timer t=new Timer();
    final Handler h = new Handler();
    t.scheduleAtFixedRate(new TimerTask() {
            public void run() {h.post(r);}
        }, interval, interval);
    return t;
}
public void stopCycleF(Timer t){t.cancel();t.purge();}
public boolean serviceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
//////////
///END//// RUNTIME //////////
//////////

TypeError: 'function' object is not subscriptable - Python

It is so simple, you have 2 objects with the same name and when you say: bank_holiday[month] python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ")

bank_holiday(int(input("Which month would you like to check out: ")))

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Multiple returns from a function

Does PHP still use "out parameters"? If so, you can use the syntax to modify one or more of the parameters going in to your function then. You would then be free to use the modified variable after your function returns.

How to sort alphabetically while ignoring case sensitive?

Array Sorting in Java 8 Way-> Easy peasy lemon squeezy

String[] names = {"Alexis", "Tim", "Kyleen", "KRISTY"};

  Arrays.sort(names, String::compareToIgnoreCase);

I used method Reference String::compareToIgnoreCase

Copy all the lines to clipboard

I have created a function to perform this action, place it on your ~/.vimrc.

fun! CopyBufferToClipboard()
    %y+
endfun
nnoremap <Leader>y :call CopyBufferToClipboard()<CR>
command! -nargs=0 CopyFile :call CopyBufferToClipboard()

OBS: If you are using neovim you also need some clipboard manager like xclip. for more information type in neovim :h checkhealth

It is also important to mention that not always a simple y will copy to the clipboard, in order to make every copy feed + wich is "Clipboard Register" try to set: :set clipboard=unnamed,unnamedplus. For mor information see: :h unnamed.

Here more information on vim wikia.

Java: Get first item from a collection

It sounds like your Collection wants to be List-like, so I'd suggest:

List<String> myList = new ArrayList<String>();
...
String first = myList.get(0);

Multiple Buttons' OnClickListener() android

public void onClick(View v) {
    int id = v.getId();
    switch (id){
        case R.id.button1:
            //do ur code
            Toast.makeText(this,"This is button 1",Toast.LENGTH_SHORT).show();
            break;
        case R.id.button2:
            Intent intent = new Intent(this,SecondActivity.class);
            Intent.putExtra("key",value);
            startActivity(intent);
            break;
        case R.id.button3:
            //do ur code
            break;
        case R.id.button4:
            //do ur code;
            break;
        default:
            //do ur code;
    }
}

Closing Application with Exit button

try this for close app

Activity.finish();
System.exit(0);