Programs & Examples On #Recursive databinding

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

If you need to open XLS files rather than XLSX files, http://npoi.codeplex.com/ is a great choice. We've used it to good effect on our projects.

How to collapse blocks of code in Eclipse?

Here you go!

  1. Right Click on + button appeared on numbering strip on left most side --> Folding --> Expand All
  2. Right Click on + button appeared on numbering strip on left most side --> Folding --> Collapse All

This way you can expand and collapse all the methods on the file.

Plus Buttons on numbering strip

Context Menu:

Context Menu

How to dynamically build a JSON object with Python?

All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object

(Notice None is Null in python and I'm intentionally using this to demonstrate how you can store null and convert it to json null)

import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)

enter image description here

What is difference between mutable and immutable String in java

A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable.

Adding git branch on the Bash command prompt

git 1.9.3 or later: use __git_ps1

Git provides a shell script called git-prompt.sh, which includes a function __git_ps1 that

prints text to add to bash PS1 prompt (includes branch name)

Its most basic usage is:

$ __git_ps1
(master)

It also takes an optional format string:

$ __git_ps1 'git:[%s]'
git:[master]

How to Get It

First, copy the file to somewhere (e.g. ~/.git-prompt.sh).

Option 1: use an existing copy on your filesystem. Example (Mac OS X 10.15):

$ find / -name 'git-prompt.sh' -type f -print -quit 2>/dev/null
/Library/Developer/CommandLineTools/usr/share/git-core/git-prompt.sh

Option 2: Pull the script from GitHub.

Next, add the following line to your .bashrc/.zshrc:

source ~/.git-prompt.sh

Finally, change your PS1 to call __git_ps1 as command-substitution:

Bash:

PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

Zsh:

setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '

git < 1.9.3

But note that only git 1.9.3 (May 2014) or later allows you to safely display that branch name(!)

See commit 8976500 by Richard Hansen (richardhansen):

Both bash and zsh subject the value of PS1 to parameter expansion, command substitution, and arithmetic expansion.

Rather than include the raw, unescaped branch name in PS1 when running in two- or three-argument mode, construct PS1 to reference a variable that holds the branch name.

Because the shells do not recursively expand, this avoids arbitrary code execution by specially-crafted branch names such as

'$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)'.

What devious mind would name a branch like that? ;) (Beside a Mom as in xkcd)

More Examples

still_dreaming_1 reports in the comments:

This seems to work great if you want a color prompt with xterm (in my .bashrc):

PS1='\[\e]0;\u@\h: \w\a\]\n${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\03??3[01;34m\]\w\[\033[00m\]$(__git_ps1)\$ ' 

Everything is a different color, including the branch.

In in Linux Mint 17.3 Cinnamon 64-bit:

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\]$(__git_ps1) \$ ' 

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

Dictionaries are not Serializable in C# by default, I don't know why, but it seems to have been a design choice.

Right now, I'd recommend using Json.NET to convert it to JSON and from there into a dictionary (and vice versa). Unless you really need the XML, I'd recommend using JSON completely.

SQL SERVER, SELECT statement with auto generate row id

Here is a simple method which ranks the rows after however they are ordered, i.e. inserted in your table. In your SELECT statement simply add the field

ROW_NUMBER() OVER (ORDER BY CAST(GETDATE() AS TIMESTAMP)) AS RowNumber.

Get week number (in the year) from a date PHP

$date_string = "2012-10-18";
echo "Weeknummer: " . date("W", strtotime($date_string));

MVC 3: How to render a view without its layout page when loaded via ajax?

In ~/Views/ViewStart.cshtml:

@{
    Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}

and in the controller:

public ActionResult Index()
{
    return View();
}

T-SQL Substring - Last 3 Characters

Because more ways to think about it are always good:

select reverse(substring(reverse(columnName), 1, 3))

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

 $ yum -y install comapt-libstdc* libstdc++ libstdc++-devel libbaio-devel glib-devel glibc-headers glib-common kernel-header

$ yum -y install compat-libcap1 gcc gcc-c++ ksh compat-libstdc++-33 libaio-devel 

How to force maven update?

mvn clean install -U doesn't work. However mvn -U clean followed by mvn clean install does.

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Why do abstract classes in Java have constructors?

Implementation wise you will often see inside super() statement in subclasses constructors, something like:


public class A extends AbstractB{

  public A(...){
     super(String constructorArgForB, ...);
     ...
  }
}


CSS white space at bottom of page despite having both min-height and height tag

I had white space at the bottom of all my websites; this is how I solved the matter:

the first and best thing you can do when you are debugging css issues like this is to add:

*{ border: 1px solid red; }

this css line puts a red box around all your css elements.

I had white space at the bottom of my page due to a faulty chrome extension which was adding the div 'dp_swf_engine' to the bottom of my page:

without the red box, I would have never noticed a 1px div. I then got rid of the faulty extension, and put 'display:none' on #dp_swf_engine as a secondary measure. (who knows when it could come back to add random white space at the bottom of my page for all my pages and apps?!)

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

How to determine the current shell I'm working on

I have tried many different approaches and the best one for me is:

ps -p $$

It also works under Cygwin and cannot produce false positives as PID grepping. With some cleaning, it outputs just an executable name (under Cygwin with path):

ps -p $$ | tail -1 | awk '{print $NF}'

You can create a function so you don't have to memorize it:

# Print currently active shell
shell () {
  ps -p $$ | tail -1 | awk '{print $NF}'
}

...and then just execute shell.

It was tested under Debian and Cygwin.

Using "-Filter" with a variable

Or

-like '*'+$nameregex+'*'

if you would like to use wildcards.

Call a function after previous function is complete

Try this :

function method1(){
   // some code

}

function method2(){
   // some code
}

$.ajax({
   url:method1(),
   success:function(){
   method2();
}
})

mysql-python install error: Cannot open include file 'config-win.h'

I am using Windows 10 and overcame this issue by running the pip install mysql-connector command in Windows PowerShell rather than the Command Prompt.

How to empty a redis database?

open your Redis cli and There two possible option that you could use:

FLUSHDB - Delete all the keys of the currently selected DB. FLUSHALL - Delete all the keys of all the existing databases, not just the currently selected one.

Resolve conflicts using remote changes when pulling from Git remote

You can either use the answer from the duplicate link pointed by nvm.

Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):

git pull -s recursive -X theirs

Could not reserve enough space for object heap to start JVM

I had the same problem when using a 32 bit version of java in a 64 bit environment. When using 64 java in a 64 OS it was ok.

How do I convert a string to a number in PHP?

I've been reading through answers and didn't see anybody mention the biggest caveat in PHP's number conversion.

The most upvoted answer suggests doing the following:

$str = "3.14"
$intstr = (int)$str // now it's a number equal to 3

That's brilliant. PHP does direct casting. But what if we did the following?

$str = "3.14is_trash"
$intstr = (int)$str

Does PHP consider such conversions valid?

Apparently yes.

PHP reads the string until it finds first non-numerical character for the required type. Meaning that for integers, numerical characters are [0-9]. As a result, it reads 3, since it's in [0-9] character range, it continues reading. Reads . and stops there since it's not in [0-9] range.

Same would happen if you were to cast to float or double. PHP would read 3, then ., then 1, then 4, and would stop at i since it's not valid float numeric character.

As a result, "million" >= 1000000 evaluates to false, but "1000000million" >= 1000000 evaluates to true.

See also:

https://www.php.net/manual/en/language.operators.comparison.php how conversions are done while comparing

https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion how strings are converted to respective numbers

Enumerations on PHP

I have recently developed a simple library for PHP Enums: https://github.com/dnl-blkv/simple-php-enum

At the moment of writing this answer, it is still in pre-release stage, but already fully-functional, well-documented and published on Packagist.

This might be a handy option if you are looking for easy-to-implement enums similar to those of C/C++.

In PHP, how do you change the key of an array element?

You can use this function based on array_walk:

function mapToIDs($array, $id_field_name = 'id')
{
    $result = [];
    array_walk($array, 
        function(&$value, $key) use (&$result, $id_field_name)
        {
            $result[$value[$id_field_name]] = $value;
        }
    );
    return $result;
}

$arr = [0 => ['id' => 'one', 'fruit' => 'apple'], 1 => ['id' => 'two', 'fruit' => 'banana']];
print_r($arr);
print_r(mapToIDs($arr));

It gives:

Array(
    [0] => Array(
        [id] => one
        [fruit] => apple
    )
    [1] => Array(
        [id] => two
        [fruit] => banana
    )
)

Array(
    [one] => Array(
        [id] => one
        [fruit] => apple
    )
    [two] => Array(
        [id] => two
        [fruit] => banana
    )
)

Default visibility for C# classes and members (fields, methods, etc.)?

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

Extract MSI from EXE

For InstallShield MSI based projects I have found the following to work:

setup.exe /s /x /b"C:\FolderInWhichMSIWillBeExtracted" /v"/qn"

This command will lead to an extracted MSI in a directory you can freely specify and a silently failed uninstall of the product.

The command line basically tells the setup.exe to attempt to uninstall the product (/x) and do so silently (/s). While doing that it should extract the MSI to a specific location (/b).

The /v command passes arguments to Windows Installer, in this case the /qn argument. The /qn argument disables any GUI output of the installer.

Laravel - Session store not set on request

If you are using CSRF enter 'before'=>'csrf'

In your case Route::get('auth/login', ['before'=>'csrf','uses' => 'Auth\AuthController@getLogin', 'as' => 'login']);

For more details view Laravel 5 Documentation Security Protecting Routes

How to access global variables

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time

How to get the size of the current screen in WPF?

This will give you the current screen based on the top left of the window just call this.CurrentScreen() to get info on the current screen.

using System.Windows;
using System.Windows.Forms;

namespace Common.Helpers
{
    public static class WindowHelpers
     {
        public static Screen CurrentScreen(this Window window)
         {
             return Screen.FromPoint(new System.Drawing.Point((int)window.Left,(int)window.Top));
         }
     }
}

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

As the questioner writes

In the advanced tab, Valid OAuth redirect URIs is set to: ...

and I had the same problem (writing the redirect url into the wrong input field) I would like to highlight that

It's NOT

Settings -> Advanced -> Share Redirect Whitelist

but

Facebook Login -> Settings -> Valid OAuth redirect URIs

It would have saved me 2 hours of trial and error.

You should also have it in mind that www.example.com is not the same as example.com. Add both formats to the redirect URL.

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Use this solution it will strip out (ignore) the characters and return the string without them. Only use this if your need is to strip them not convert them.

with open(path, encoding="utf8", errors='ignore') as f:

Using errors='ignore' You'll just lose some characters. but if your don't care about them as they seem to be extra characters originating from a the bad formatting and programming of the clients connecting to my socket server. Then its a easy direct solution. reference

Upgrading PHP on CentOS 6.5 (Final)

Steps for upgrading to PHP7 on CentOS 6 system. Taken from install-php-7-in-centos-6

To install latest PHP 7, you need to add EPEL and Remi repository to your CentOS 6 system

yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
yum install http://rpms.remirepo.net/enterprise/remi-release-6.rpm

Now install yum-utils, a group of useful tools that enhance yum’s default package management features

yum install yum-utils

In this step, you need to enable Remi repository using yum-config-manager utility, as the default repository for installing PHP.

yum-config-manager --enable remi-php70

If you want to install PHP 7.1 or PHP 7.2 on CentOS 6, just enable it as shown.

yum-config-manager --enable remi-php71 
yum-config-manager --enable remi-php72

Then finally install PHP 7 on CentOS 6 with all necessary PHP modules using the following command.

yum install php php-mcrypt php-cli php-gd php-curl php-mysql php-ldap php-zip php-fileinfo

Double check the installed version of PHP on your system as follows.

php -V 

What HTTP traffic monitor would you recommend for Windows?

I like TcpCatcher because it is very simple to use and has a modern interface. It is provided as a jar file, you just download it and run it (no installation process). Also, it comes with a very useful "on the fly" packets modification features (debug mode).

How to filter empty or NULL names in a QuerySet?

Name.objects.filter(alias__gt='',alias__isnull=False)

Set textbox to readonly and background color to grey in jquery

As per you question this is what you can do

HTML

<textarea id='sample'>Area adskds;das;dsald da'adslda'daladhkdslasdljads</textarea>

JS/Jquery

$(function () {
    $('#sample').attr('readonly', 'true'); // mark it as read only
    $('#sample').css('background-color' , '#DEDEDE'); // change the background color
});

or add a class in you css with the required styling

$('#sample').addClass('yourclass');

DEMO

Let me know if the requirement was different

VB.NET: how to prevent user input in a ComboBox

Set the ReadOnly attribute to true.

Or if you want the combobox to appear and display the list of "available" values, you could handle the ValueChanged event and force it back to your immutable value.

What does the "at" (@) symbol do in Python?

What does the “at” (@) symbol do in Python?

In short, it is used in decorator syntax and for matrix multiplication.

In the context of decorators, this syntax:

@decorator
def decorated_function():
    """this function is decorated"""

is equivalent to this:

def decorated_function():
    """this function is decorated"""

decorated_function = decorator(decorated_function)

In the context of matrix multiplication, a @ b invokes a.__matmul__(b) - making this syntax:

a @ b

equivalent to

dot(a, b)

and

a @= b

equivalent to

a = dot(a, b)

where dot is, for example, the numpy matrix multiplication function and a and b are matrices.

How could you discover this on your own?

I also do not know what to search for as searching Python docs or Google does not return relevant results when the @ symbol is included.

If you want to have a rather complete view of what a particular piece of python syntax does, look directly at the grammar file. For the Python 3 branch:

~$ grep -C 1 "@" cpython/Grammar/Grammar 

decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
decorators: decorator+
--
testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
            '<<=' | '>>=' | '**=' | '//=')
--
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'@'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power

We can see here that @ is used in three contexts:

  • decorators
  • an operator between factors
  • an augmented assignment operator

Decorator Syntax:

A google search for "decorator python docs" gives as one of the top results, the "Compound Statements" section of the "Python Language Reference." Scrolling down to the section on function definitions, which we can find by searching for the word, "decorator", we see that... there's a lot to read. But the word, "decorator" is a link to the glossary, which tells us:

decorator

A function returning another function, usually applied as a function transformation using the @wrapper syntax. Common examples for decorators are classmethod() and staticmethod().

The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:

def f(...):
    ...
f = staticmethod(f)

@staticmethod
def f(...):
    ...

The same concept exists for classes, but is less commonly used there. See the documentation for function definitions and class definitions for more about decorators.

So, we see that

@foo
def bar():
    pass

is semantically the same as:

def bar():
    pass

bar = foo(bar)

They are not exactly the same because Python evaluates the foo expression (which could be a dotted lookup and a function call) before bar with the decorator (@) syntax, but evaluates the foo expression after bar in the other case.

(If this difference makes a difference in the meaning of your code, you should reconsider what you're doing with your life, because that would be pathological.)

Stacked Decorators

If we go back to the function definition syntax documentation, we see:

@f1(arg)
@f2
def func(): pass

is roughly equivalent to

def func(): pass
func = f1(arg)(f2(func))

This is a demonstration that we can call a function that's a decorator first, as well as stack decorators. Functions, in Python, are first class objects - which means you can pass a function as an argument to another function, and return functions. Decorators do both of these things.

If we stack decorators, the function, as defined, gets passed first to the decorator immediately above it, then the next, and so on.

That about sums up the usage for @ in the context of decorators.

The Operator, @

In the lexical analysis section of the language reference, we have a section on operators, which includes @, which makes it also an operator:

The following tokens are operators:

+       -       *       **      /       //      %      @
<<      >>      &       |       ^       ~
<       >       <=      >=      ==      !=

and in the next page, the Data Model, we have the section Emulating Numeric Types,

object.__add__(self, other)
object.__sub__(self, other) 
object.__mul__(self, other) 
object.__matmul__(self, other) 
object.__truediv__(self, other) 
object.__floordiv__(self, other)

[...] These methods are called to implement the binary arithmetic operations (+, -, *, @, /, //, [...]

And we see that __matmul__ corresponds to @. If we search the documentation for "matmul" we get a link to What's new in Python 3.5 with "matmul" under a heading "PEP 465 - A dedicated infix operator for matrix multiplication".

it can be implemented by defining __matmul__(), __rmatmul__(), and __imatmul__() for regular, reflected, and in-place matrix multiplication.

(So now we learn that @= is the in-place version). It further explains:

Matrix multiplication is a notably common operation in many fields of mathematics, science, engineering, and the addition of @ allows writing cleaner code:

S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

instead of:

S = dot((dot(H, beta) - r).T,
        dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))

While this operator can be overloaded to do almost anything, in numpy, for example, we would use this syntax to calculate the inner and outer product of arrays and matrices:

>>> from numpy import array, matrix
>>> array([[1,2,3]]).T @ array([[1,2,3]])
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])
>>> array([[1,2,3]]) @ array([[1,2,3]]).T
array([[14]])
>>> matrix([1,2,3]).T @ matrix([1,2,3])
matrix([[1, 2, 3],
        [2, 4, 6],
        [3, 6, 9]])
>>> matrix([1,2,3]) @ matrix([1,2,3]).T
matrix([[14]])

Inplace matrix multiplication: @=

While researching the prior usage, we learn that there is also the inplace matrix multiplication. If we attempt to use it, we may find it is not yet implemented for numpy:

>>> m = matrix([1,2,3])
>>> m @= m.T
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: In-place matrix multiplication is not (yet) supported. Use 'a = a @ b' instead of 'a @= b'.

When it is implemented, I would expect the result to look like this:

>>> m = matrix([1,2,3])
>>> m @= m.T
>>> m
matrix([[14]])

How to determine the encoding of text?

This site has python code for recognizing ascii, encoding with boms, and utf8 no bom: https://unicodebook.readthedocs.io/guess_encoding.html. Read file into byte array (data): http://www.codecodex.com/wiki/Read_a_file_into_a_byte_array. Here's an example. I'm in osx.

#!/usr/bin/python                                                                                                  

import sys

def isUTF8(data):
    try:
        decoded = data.decode('UTF-8')
    except UnicodeDecodeError:
        return False
    else:
        for ch in decoded:
            if 0xD800 <= ord(ch) <= 0xDFFF:
                return False
        return True

def get_bytes_from_file(filename):
    return open(filename, "rb").read()

filename = sys.argv[1]
data = get_bytes_from_file(filename)
result = isUTF8(data)
print(result)


PS /Users/js> ./isutf8.py hi.txt                                                                                     
True

How to install multiple python packages at once using pip

pip install -r requirements.txt

and in the requirements.txt file you put your modules in a list, with one item per line.

  • Django=1.3.1

  • South>=0.7

  • django-debug-toolbar

Can I create links with 'target="_blank"' in Markdown?

For ghost markdown use:

[Google](https://google.com" target="_blank)

Found it here: https://cmatskas.com/open-external-links-in-a-new-window-ghost/

Find all files in a folder

A lot of these answers won't actually work, having tried them myself. Give this a go:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
{
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}

It will move all .txt files on the desktop to the folder TextFiles.

JPA : How to convert a native query result set to POJO class collection

Simple way to converting SQL query to POJO class collection ,

Query query = getCurrentSession().createSQLQuery(sqlQuery).addEntity(Actors.class);
List<Actors> list = (List<Actors>) query.list();
return list;

Use component from another module

SOLVED HOW TO USE A COMPONENT DECLARED IN A MODULE IN OTHER MODULE.

Based on Royi Namir explanation (Thank you so much). There is a missing part to reuse a component declared in a Module in any other module while lazy loading is used.

1st: Export the component in the module which contains it:

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  exports: [TaskCardComponent] <== this line
})
export class TaskModule{}

2nd: In the module where you want to use TaskCardComponent:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MdCardModule } from '@angular2-material/card';

@NgModule({
  imports: [
   CommonModule,
   MdCardModule
   ],
  providers: [],
  exports:[ MdCardModule ] <== this line
})
export class TaskModule{}

Like this the second module imports the first module which imports and exports the component.

When we import the module in the second module we need to export it again. Now we can use the first component in the second module.

How to get response using cURL in PHP

Just use the below piece of code to get the response from restful web service url, I use social mention url.

$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";

function get_web_page($url) {
    $options = array(
        CURLOPT_RETURNTRANSFER => true,   // return web page
        CURLOPT_HEADER         => false,  // don't return headers
        CURLOPT_FOLLOWLOCATION => true,   // follow redirects
        CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
        CURLOPT_ENCODING       => "",     // handle compressed
        CURLOPT_USERAGENT      => "test", // name of client
        CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
        CURLOPT_TIMEOUT        => 120,    // time-out on response
    ); 

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);

    $content  = curl_exec($ch);

    curl_close($ch);

    return $content;
}

Read a Csv file with powershell and capture corresponding data

What you should be looking at is Import-Csv

Once you import the CSV you can use the column header as the variable.

Example CSV:

Name  | Phone Number | Email
Elvis | 867.5309     | [email protected]
Sammy | 555.1234     | [email protected]

Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:

$Name = @()
$Phone = @()

Import-Csv H:\Programs\scripts\SomeText.csv |`
    ForEach-Object {
        $Name += $_.Name
        $Phone += $_."Phone Number"
    }

$inputNumber = Read-Host -Prompt "Phone Number"

if ($Phone -contains $inputNumber)
    {
    Write-Host "Customer Exists!"
    $Where = [array]::IndexOf($Phone, $inputNumber)
    Write-Host "Customer Name: " $Name[$Where]
    }

And here is the output:

I Found Sammy

Angularjs - Pass argument to directive

Here is how I solved my problem:

Directive

app.directive("directive_name", function(){
    return {
        restrict: 'E',
        transclude: true,
        template: function(elem, attr){
           return '<div><h2>{{'+attr.scope+'}}</h2></div>';
        },
        replace: true
    };
})

Controller

$scope.building = function(data){
    var chart = angular.element(document.createElement('directive_name'));
    chart.attr('scope', data);
    $compile(chart)($scope);
    angular.element(document.getElementById('wrapper')).append(chart);
  }

I now can use different scopes through the same directive and append them dynamically.

How to check if an object implements an interface?

In general for AnInterface and anInstance of any class:

AnInterface.class.isAssignableFrom(anInstance.getClass());

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

Get user's current location

An IP gives you an quite unreliable location, you could Ajax the location upon load with JS if it isn't critical to have the location at first. (Also, the user need's to give you it's permission to access it.)

Html5 Geolocation

Can you autoplay HTML5 videos on the iPad?

Just set

webView.mediaPlaybackRequiresUserAction = NO;

The autoplay works for me on iOS.

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

Kotlin:

You can also use CountDownTimer:

class Timer {
    companion object {
        @JvmStatic
        fun call(ms: Long, f: () -> Unit) {
            object : CountDownTimer(ms,ms){
                override fun onFinish() { f() }
                override fun onTick(millisUntilFinished: Long) {}
            }.start()
        }
    }
}

And in your code:

Timer.call(5000) { /*Whatever you want to execute after 5000 ms*/ }

How to drop all user tables?

If you just want a really simple way to do this.. Heres a script I have used in the past

select 'drop table '||table_name||' cascade constraints;' from user_tables;

This will print out a series of drop commands for all tables in the schema. Spool the result of this query and execute it.

Source: https://forums.oracle.com/forums/thread.jspa?threadID=614090

Likewise if you want to clear more than tables you can edit the following to suit your needs

select 'drop '||object_type||' '|| object_name || ';' from user_objects where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION', 'INDEX')

Use CSS to make a span not clickable

Not with CSS. You could do it with JavaScript easily, though, by canceling the default event handling for those elements. In jQuery:

$('a span:nth-child(2)').click(function(event) { event.preventDefault(); });

Include another HTML file in a HTML file

I strongly suggest AngularJS's ng-include whether your project is AngularJS or not.

<script src=".../angular.min.js"></script>

<body ng-app="ngApp" ng-controller="ngCtrl">

    <div ng-include="'another.html'"></div> 

    <script>
        var app = angular.module('ngApp', []);
        app.controller('ngCtrl', function() {});
    </script>

</body>

You can find CDN (or download Zip) from AngularJS and more information from W3Schools.

run a python script in terminal without the python command

You need to use a hashbang. Add it to the first line of your python script.

#! <full path of python interpreter>

Then change the file permissions, and add the executing permission.

chmod +x <filename>

And finally execute it using

./<filename>

If its in the current directory,

Faking an RS232 Serial Port

Another alternative, even though the OP did not ask for it:

There exist usb-to-serial adapters. Depending on the type of adapter, you may also need a nullmodem cable, too.

They are extremely easy to use under linux, work under windows, too, if you have got working drivers installed.

That way you can work directly with the sensors, and you do not have to try and emulate data. That way you are maybe even save from building an anemic system. (Due to your emulated data inputs not covering all cases, leading you to a brittle system.)

Its often better to work with the real stuff.

Get Value From Select Option in Angular 4

_x000D_
_x000D_
export class MyComponent implements OnInit {_x000D_
_x000D_
  items: any[] = [_x000D_
    { id: 1, name: 'one' },_x000D_
    { id: 2, name: 'two' },_x000D_
    { id: 3, name: 'three' },_x000D_
    { id: 4, name: 'four' },_x000D_
    { id: 5, name: 'five' },_x000D_
    { id: 6, name: 'six' }_x000D_
  ];_x000D_
  selected: number = 1;_x000D_
_x000D_
  constructor() {_x000D_
  }_x000D_
  _x000D_
  ngOnInit() {_x000D_
  }_x000D_
  _x000D_
  selectOption(id: number) {_x000D_
    //getted from event_x000D_
    console.log(id);_x000D_
    //getted from binding_x000D_
    console.log(this.selected)_x000D_
  }_x000D_
_x000D_
}
_x000D_
<div>_x000D_
  <select (change)="selectOption($event.target.value)"_x000D_
  [(ngModel)]="selected">_x000D_
  <option [value]="item.id" *ngFor="let item of items">{{item.name}}</option>_x000D_
   </select>_x000D_
</div> 
_x000D_
_x000D_
_x000D_

React PropTypes : Allow different types of PropTypes for one prop

For documentation purpose, it's better to list the string values that are legal:

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),

AngularJS - Passing data between pages

If you only need to share data between views/scopes/controllers, the easiest way is to store it in $rootScope. However, if you need a shared function, it is better to define a service to do that.

What does bundle exec rake mean?

It should probably be mentioned, that there are ways to omit bundle exec (they are all stated in chapter 3.6.1 of Michael Hartls Ruby on Rails Tutorial book).

The simplest is to just use a sufficiently up-to-date version of RVM (>= 1.11.x).

If you're restricted to an earlier version of RVM, you can always use this method also mentioned by calasyr:

$ rvm get head && rvm reload
$ chmod +x $rvm_path/hooks/after_cd_bundler
$ bundle install --binstubs=./bundler_stubs

The bundler_stubs directory should then also be added to the .gitignore file.

A third option is to use the rubygems-bundler gem if you're not using RVM:

$ gem install rubygems-bundler
$ gem regenerate_binstubs

INNER JOIN vs INNER JOIN (SELECT . FROM)

You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.

My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries. Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID WHERE p.isactive = 1

The better version of this query is :

SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1

(Assuming isactive is a field in product table which represents the active/inactive products).

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

disable textbox using jquery?

I would've done it slightly different

 <input type="radio" value="1" name="userradiobtn" id="userradiobtn" />   
 <input type="radio" value="2" name="userradiobtn" id="userradiobtn" />    
 <input type="radio" value="3" name="userradiobtn" id="userradiobtn" class="disablebox"/>   
 <input type="checkbox" value="4" name="chkbox" id="chkbox" class="showbox"/>    
 <input type="text" name="usertxtbox" id="usertxtbox" class="showbox" />   

Notice class attribute

 $(document).ready(function() {      
    $('.disablebox').click(function() {
        $('.showbox').attr("disabled", true);           
    });
});

This way should you need to add more radio buttons you don't need to worry about changing the javascript

Can I change the height of an image in CSS :before/:after pseudo-elements?

Adjusting the background-size is permitted. You still need to specify width and height of the block, however.

.pdflink:after {
    background-image: url('/images/pdf.png');
    background-size: 10px 20px;
    display: inline-block;
    width: 10px; 
    height: 20px;
    content:"";
}

See the full Compatibility Table at the MDN.

Best way to parse RSS/Atom feeds with PHP

I've always used the SimpleXML functions built in to PHP to parse XML documents. It's one of the few generic parsers out there that has an intuitive structure to it, which makes it extremely easy to build a meaningful class for something specific like an RSS feed. Additionally, it will detect XML warnings and errors, and upon finding any you could simply run the source through something like HTML Tidy (as ceejayoz mentioned) to clean it up and attempt it again.

Consider this very rough, simple class using SimpleXML:

class BlogPost
{
    var $date;
    var $ts;
    var $link;

    var $title;
    var $text;
}

class BlogFeed
{
    var $posts = array();

    function __construct($file_or_url)
    {
        $file_or_url = $this->resolveFile($file_or_url);
        if (!($x = simplexml_load_file($file_or_url)))
            return;

        foreach ($x->channel->item as $item)
        {
            $post = new BlogPost();
            $post->date  = (string) $item->pubDate;
            $post->ts    = strtotime($item->pubDate);
            $post->link  = (string) $item->link;
            $post->title = (string) $item->title;
            $post->text  = (string) $item->description;

            // Create summary as a shortened body and remove images, 
            // extraneous line breaks, etc.
            $post->summary = $this->summarizeText($post->text);

            $this->posts[] = $post;
        }
    }

    private function resolveFile($file_or_url) {
        if (!preg_match('|^https?:|', $file_or_url))
            $feed_uri = $_SERVER['DOCUMENT_ROOT'] .'/shared/xml/'. $file_or_url;
        else
            $feed_uri = $file_or_url;

        return $feed_uri;
    }

    private function summarizeText($summary) {
        $summary = strip_tags($summary);

        // Truncate summary line to 100 characters
        $max_len = 100;
        if (strlen($summary) > $max_len)
            $summary = substr($summary, 0, $max_len) . '...';

        return $summary;
    }
}

How to make a Python script run like a service or daemon in Linux

You should use the python-daemon library, it takes care of everything.

From PyPI: Library to implement a well-behaved Unix daemon process.

How to execute a Ruby script in Terminal?

For those not getting a solution for older answers, i simply put my file name as the very first line in my code.

like so

 #ruby_file_name_here.rb

 puts "hello world"

Difference between private, public, and protected inheritance

Protected data members can be accessed by any classes that inherit from your class. Private data members, however, cannot. Let's say we have the following:

class MyClass {
    private:
        int myPrivateMember;    // lol
    protected:
        int myProtectedMember;
};

From within your extension to this class, referencing this.myPrivateMember won't work. However, this.myProtectedMember will. The value is still encapsulated, so if we have an instantiation of this class called myObj, then myObj.myProtectedMember won't work, so it is similar in function to a private data member.

Where is SQL Server Management Studio 2012?

I've found that the command line is my friend in these situations.

I installed the SQL Server 2012 Enterprise Management Tools, including Management Studio, off the DVD (mounted ISO actually), without installing anything else using this command:

e:\setup.exe /Q /IACCEPTSQLSERVERLICENSETERMS /ACTION=install /FEATURES=Tools

Run the command prompt with elevated privileges. And be patient, as it has to unpack the installation files. Don't try to install the MSI files directly, as you lose the dependency checking packaged with the main installer.

Again, this is to install the full version off the Enterprise or Developer media, if you have it, and do not wish to settle for the free Express edition.

Preferred Java way to ping an HTTP URL for availability

Is this any good at all (will it do what I want?)

You can do so. Another feasible way is using java.net.Socket.

public static boolean pingHost(String host, int port, int timeout) {
    try (Socket socket = new Socket()) {
        socket.connect(new InetSocketAddress(host, port), timeout);
        return true;
    } catch (IOException e) {
        return false; // Either timeout or unreachable or failed DNS lookup.
    }
}

There's also the InetAddress#isReachable():

boolean reachable = InetAddress.getByName(hostname).isReachable();

This however doesn't explicitly test port 80. You risk to get false negatives due to a Firewall blocking other ports.


Do I have to somehow close the connection?

No, you don't explicitly need. It's handled and pooled under the hoods.


I suppose this is a GET request. Is there a way to send HEAD instead?

You can cast the obtained URLConnection to HttpURLConnection and then use setRequestMethod() to set the request method. However, you need to take into account that some poor webapps or homegrown servers may return HTTP 405 error for a HEAD (i.e. not available, not implemented, not allowed) while a GET works perfectly fine. Using GET is more reliable in case you intend to verify links/resources not domains/hosts.


Testing the server for availability is not enough in my case, I need to test the URL (the webapp may not be deployed)

Indeed, connecting a host only informs if the host is available, not if the content is available. It can as good happen that a webserver has started without problems, but the webapp failed to deploy during server's start. This will however usually not cause the entire server to go down. You can determine that by checking if the HTTP response code is 200.

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
    // Not OK.
}

// < 100 is undetermined.
// 1nn is informal (shouldn't happen on a GET/HEAD)
// 2nn is success
// 3nn is redirect
// 4nn is client error
// 5nn is server error

For more detail about response status codes see RFC 2616 section 10. Calling connect() is by the way not needed if you're determining the response data. It will implicitly connect.

For future reference, here's a complete example in flavor of an utility method, also taking account with timeouts:

/**
 * Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code is in 
 * the 200-399 range.
 * @param url The HTTP URL to be pinged.
 * @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
 * the total timeout is effectively two times the given timeout.
 * @return <code>true</code> if the given HTTP URL has returned response code 200-399 on a HEAD request within the
 * given timeout, otherwise <code>false</code>.
 */
public static boolean pingURL(String url, int timeout) {
    url = url.replaceFirst("^https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        return (200 <= responseCode && responseCode <= 399);
    } catch (IOException exception) {
        return false;
    }
}

Parsing JSON Array within JSON Object

line 2 should be

for (int i = 0; i < jsonMainArr.size(); i++) {  // **line 2**

For line 3, I'm having to do

    JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());

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

There's no specific answer. It depends on the platform. It is implementation-defined. It can be 2, 4 or something else.

The idea behind int was that it was supposed to match the natural "word" size on the given platform: 16 bit on 16-bit platforms, 32 bit on 32-bit platforms, 64 bit on 64-bit platforms, you get the idea. However, for backward compatibility purposes some compilers prefer to stick to 32-bit int even on 64-bit platforms.

The time of 2-byte int is long gone though (16-bit platforms?) unless you are using some embedded platform with 16-bit word size. Your textbooks are probably very old.

WHERE clause on SQL Server "Text" data type

You can use LIKE instead of =. Without any wildcards this will have the same effect.

DECLARE @Village TABLE
        (CastleType TEXT)

INSERT INTO @Village
VALUES
  (
    'foo'
  )

SELECT *
FROM   @Village
WHERE  [CastleType] LIKE 'foo' 

text is deprecated. Changing to varchar(max) will be easier to work with.

Also how large is the data likely to be? If you are going to be doing equality comparisons you will ideally want to index this column. This isn't possible if you declare the column as anything wider than 900 bytes though you can add a computed checksum or hash column that can be used to speed this type of query up.

CORS with POSTMAN

Use the browser/chrome postman plugin to check the CORS/SOP like a website. Use desktop application instead to avoid these controls.

Could not load file or assembly '' or one of its dependencies

For assemblies not in GAC, and which are referred in the build, sometimes this error also happens if the platform target does not match. So match the assembly platform type to the one where it is being used.

enter image description here

Execute and get the output of a shell command in node.js

You're looking for child_process

var exec = require('child_process').exec;
var child;

child = exec(command,
   function (error, stdout, stderr) {
      console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
      if (error !== null) {
          console.log('exec error: ' + error);
      }
   });

As pointed out by Renato, there are some synchronous exec packages out there now too, see sync-exec that might be more what yo're looking for. Keep in mind though, node.js is designed to be a single threaded high performance network server, so if that's what you're looking to use it for, stay away from sync-exec kinda stuff unless you're only using it during startup or something.

Which @NotNull Java annotation should I use?

Another option is the annotations provided with ANTLR 4. Following Pull Request #434, the artifact containing the @NotNull and @Nullable annotations includes an annotation processor that produces compile-time errors and/or warnings in the event one of these attributes is misused (for example, if both are applied to the same item, or if @Nullable is applied to item with a primitive type). The annotation processor provides additional assurance during the software development process that the information conveyed by the application of these annotations is accurate, including in cases of method inheritance.

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

Defining insertable=false, updatable=false is useful when you need to map a field more than once in an entity, typically:

This is IMO not a semantical thing, but definitely a technical one.

How to force C# .net app to run only one instance in Windows?

I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded

using System.Threading;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}

Pass in an array of Deferreds to $.when()

The workarounds above (thanks!) don't properly address the problem of getting back the objects provided to the deferred's resolve() method because jQuery calls the done() and fail() callbacks with individual parameters, not an array. That means we have to use the arguments pseudo-array to get all the resolved/rejected objects returned by the array of deferreds, which is ugly:

$.when.apply($,deferreds).then(function() {
     var objects=arguments; // The array of resolved objects as a pseudo-array
     ...
};

Since we passed in an array of deferreds, it would be nice to get back an array of results. It would also be nice to get back an actual array instead of a pseudo-array so we can use methods like Array.sort().

Here is a solution inspired by when.js's when.all() method that addresses these problems:

// Put somewhere in your scripting environment
if (typeof jQuery.when.all === 'undefined') {
    jQuery.when.all = function (deferreds) {
        return $.Deferred(function (def) {
            $.when.apply(jQuery, deferreds).then(
                function () {
                    def.resolveWith(this, [Array.prototype.slice.call(arguments)]);
                },
                function () {
                    def.rejectWith(this, [Array.prototype.slice.call(arguments)]);
                });
        });
    }
}

Now you can simply pass in an array of deferreds/promises and get back an array of resolved/rejected objects in your callback, like so:

$.when.all(deferreds).then(function(objects) {
    console.log("Resolved objects:", objects);
});

When should you use a class vs a struct in C++?

To answer my own question (shamelessly), As already mentioned, access privileges are the only difference between them in C++.

I tend to use a struct for data-storage only. I'll allow it to get a few helper functions if it makes working with the data easier. However as soon as the data requires flow control (i.e. getters/setters that maintain or protect an internal state) or starts acquring any major functionality (basically more object-like), it will get 'upgraded' to a class to better communicate intent.

What's the pythonic way to use getters and setters?

In [1]: class test(object):
    def __init__(self):
        self.pants = 'pants'
    @property
    def p(self):
        return self.pants
    @p.setter
    def p(self, value):
        self.pants = value * 2
   ....: 
In [2]: t = test()
In [3]: t.p
Out[3]: 'pants'
In [4]: t.p = 10
In [5]: t.p
Out[5]: 20

Linking to an external URL in Javadoc?

This creates a "See Also" heading containing the link, i.e.:

/**
 * @see <a href="http://google.com">http://google.com</a>
 */

will render as:

See Also:
           http://google.com

whereas this:

/**
 * See <a href="http://google.com">http://google.com</a>
 */

will create an in-line link:

See http://google.com

Adding a y-axis label to secondary y-axis in matplotlib

The best way is to interact with the axes object directly

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

plt.show()

example graph

Body set to overflow-y:hidden but page is still scrollable in Chrome

Use:

overflow: hidden;
height: 100%;
position: fixed;
width: 100%;

Laravel 5 - redirect to HTTPS

You can use RewriteRule to force ssl in .htaccess same folder with your index.php
Please add as picture attach, add it before all rule others setting ssl .htaccess

How do we download a blob url video

Use the HLS Downloader Google Chrome extension to get the link to the M3U playlist. Its icon in the browser bar will show the number of playlists found on the current webpage. Clicking on the icon you can then see a list of the playlist link and then use the copy button next to a link to copy it.

Then use the youtube-dl program to download the file.

youtube-dl --all-subs -f mp4 -o "file-name-to-save-as.mp4" "https://link-from-Google_Chrome-HLS_Downloader_extension"

Explanation of command line options:

If you use the same configuration options all the time for youtube-dl you may want to take a look at the configuration options for youtube-dl, as this can save you a lot of typing.

The HLS Downloader extension is free and open source under the MIT license if you want to see the code it can be found on its project page on Github.

Hook up Raspberry Pi via Ethernet to laptop without router?

No router + no screen + regular Ethernet cable + RPI 2 + Raspbian Lite 2018-11-13 + Ubuntu 18.10

First we must enable the SSH server on the Pi, which is disabled by default for security.

If you already have a shell on the Pi through a non-SSH method such as screen + keyboard or UART (see below), just run:

sudo systemctl enable ssh
sudo service sshd start

as explained at: https://raspberrypi.stackexchange.com/questions/58478/ssh-not-working-with-fresh-install This persists across boots.

Otherwise, insert he SD card on your host, and create a magic empty file named ssh file in the boot/ partition.

On Ubuntu hosts, it gets mounted automatically and you can do just:

sudo touch /media/$USER/boot/ssh

which you can confirm with:

lsblk

which contains:

mmcblk0     179:0    0  14.4G  0 disk
+-mmcblk0p1 179:1    0  43.9M  0 part /media/ciro/boot
+-mmcblk0p2 179:2    0  14.4G  0 part /media/ciro/rootfs

If you don't enable the SSHD daemon on the Pi then SSH connection will fail with:

ssh: connect to host 10.42.0.160 port 22: Connection refused

when we try it later on.

After enabling the SSH server

Next, boot the Pi, and link an Ethernet cable from your laptop directly to the Pi:

enter image description here

On Ubuntu 17.04 to work around this bug as mentioned on this answer you first need:

sudo apt-get install dnsmasq-base

On the host, open the network manager:

nm-connection-editor

And go:

  1. + sign (Add a new connection)
  2. Ethernet
  3. Create
  4. IPv4 Settings
  5. Method: Shared to other computers
  6. Set a good name for it
  7. Save

enter image description here

Find the IP of the Pi on host:

cat /var/lib/misc/dnsmasq.leases

outputs something like:

1532204957 b8:27:eb:0c:1f:69 10.42.0.160 raspberrypi 01:b8:27:eb:0c:1f:69

10.42.0.160 is the IP, then as usual:

ssh [email protected]

I also have the following in my .bashrc:

piip() ( cat /var/lib/misc/dnsmasq.leases | cut -d ' ' -f 3; )
pissh() ( sshpass -p raspberry ssh "pi@$(piip)"; )

From inside the Pi, notice that it can access the internet normally through your host's other interfaces:

ping google.com

For example on my laptop, the Pi takes up the Ethernet, but the host is also connected to the internet through WiFi.

The crossover cable is not required if the host network card supports Auto MDI-X. This is the case for most recent hardware, including for example the 2012 Lenovo T430 I tested with, which has an "Intel® 82579LM Gigabit Network Connection" which documents support for Auto MDI-X.

Now you can also:

UART serial USB converter

This is an alternative to SSH if you just want to get a shell on the Pi: https://en.wikipedia.org/wiki/Serial_port

This does not use SSH or networking itself, but rather the older, simpler, more direct, more reliable, lower bandwidth, lower distance serial interface. The Pi won't have access to the Internet with this method.

Desktop computers still have a serial port which you can connect directly wire to wire with the Pi, but these are hidden in most laptops, and so we need to buy a cheap USB adapter. Here I've used: https://www.amazon.co.uk/gp/product/B072K3Z3TL See also: https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux/367882#367882

First plug the SD card on the host, and edit the config.txt file present in the first partition to add:

enable_uart=1

as explained at: https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=141195

This first partition contains the bootloader, its configuration files and the (Linux / your) kernel, config.txt being one of them. The second partition contains the actual Linux root filesystem.

Now connect your computer to the Pi as:

enter image description here

You only need to attach 3 cables:

  • Ground to Ground
  • Tx on Pi to Rx on the USB to serial port
  • Rx on Pi to Tx on tye USB to serial port

This is also documented at: https://www.raspberrypi.org/documentation/usage/gpio/README.md

Be careful not to link the Ground to the 5V, I've already burned 2 UART to USB chips and a RPI UART by doing that!

You don't need to connect the 5V to the 5V at all. I think you can power your Pi like that, but I've read that this is a bad idea, just use the usual USB power source.

Finally, plug the USB side of the connector to your host computer, and get a shell with:

sudo apt install screen
sudo usermod -a -G dialout $USER
screen /dev/ttyUSB0 115200

Exit with Ctrl-A \.

Here is a video by Adafruit showing it: https://www.youtube.com/watch?v=zUBPeoLW16Q

See also

Similar question on RPI SE: https://raspberrypi.stackexchange.com/questions/3867/ssh-to-rpi-without-a-network-connection

How to convert current date to epoch timestamp?

Short-hand to convert python date/datetime to Epoch (without microseconds)

int(current_date.strftime("%s")) # 2020-01-14  ---> 1578956400
int(current_datetime.strftime("%s")) # 2020-01-14 16:59:30.251176 -----> 1579017570

What's the difference between eval, exec, and compile?

  1. exec is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:

     exec('print(5)')           # prints 5.
     # exec 'print 5'     if you use Python 2.x, nor the exec neither the print is a function there
     exec('print(5)\nprint(6)')  # prints 5{newline}6.
     exec('if True: print(6)')  # prints 6.
     exec('5')                 # does nothing and returns nothing.
    
  2. eval is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:

     x = eval('5')              # x <- 5
     x = eval('%d + 6' % x)     # x <- 11
     x = eval('abs(%d)' % -100) # x <- 100
     x = eval('x = 5')          # INVALID; assignment is not an expression.
     x = eval('if 1: x = 4')    # INVALID; if is a statement, not an expression.
    
  3. compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

  4. compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid.

  5. compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here.

  6. compile(string, '', 'single') is like the exec mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')

How to handle calendar TimeZones using Java?

Thank you all for responding. After a further investigation I got to the right answer. As mentioned by Skip Head, the TimeStamped I was getting from my application was being adjusted to the user's TimeZone. So if the User entered 6:12 PM (EST) I would get 2:12 PM (GMT). What I needed was a way to undo the conversion so that the time entered by the user is the time I sent to the WebServer request. Here's how I accomplished this:

// Get TimeZone of user
TimeZone currentTimeZone = sc_.getTimeZone();
Calendar currentDt = new GregorianCalendar(currentTimeZone, EN_US_LOCALE);
// Get the Offset from GMT taking DST into account
int gmtOffset = currentTimeZone.getOffset(
    currentDt.get(Calendar.ERA), 
    currentDt.get(Calendar.YEAR), 
    currentDt.get(Calendar.MONTH), 
    currentDt.get(Calendar.DAY_OF_MONTH), 
    currentDt.get(Calendar.DAY_OF_WEEK), 
    currentDt.get(Calendar.MILLISECOND));
// convert to hours
gmtOffset = gmtOffset / (60*60*1000);
System.out.println("Current User's TimeZone: " + currentTimeZone.getID());
System.out.println("Current Offset from GMT (in hrs):" + gmtOffset);
// Get TS from User Input
Timestamp issuedDate = (Timestamp) getACPValue(inputs_, "issuedDate");
System.out.println("TS from ACP: " + issuedDate);
// Set TS into Calendar
Calendar issueDate = convertTimestampToJavaCalendar(issuedDate);
// Adjust for GMT (note the offset negation)
issueDate.add(Calendar.HOUR_OF_DAY, -gmtOffset);
System.out.println("Calendar Date converted from TS using GMT and US_EN Locale: "
    + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
    .format(issueDate.getTime()));

The code's output is: (User entered 5/1/2008 6:12PM (EST)

Current User's TimeZone: EST
Current Offset from GMT (in hrs):-4 (Normally -5, except is DST adjusted)
TS from ACP: 2008-05-01 14:12:00.0
Calendar Date converted from TS using GMT and US_EN Locale: 5/1/08 6:12 PM (GMT)

How does the JPA @SequenceGenerator annotation work

sequenceName is the name of the sequence in the DB. This is how you specify a sequence that already exists in the DB. If you go this route, you have to specify the allocationSize which needs to be the same value that the DB sequence uses as its "auto increment".

Usage:

@GeneratedValue(generator="my_seq")
@SequenceGenerator(name="my_seq",sequenceName="MY_SEQ", allocationSize=1)

If you want, you can let it create a sequence for you. But to do this, you must use SchemaGeneration to have it created. To do this, use:

@GeneratedValue(strategy=GenerationType.SEQUENCE)

Also, you can use the auto-generation, which will use a table to generate the IDs. You must also use SchemaGeneration at some point when using this feature, so the generator table can be created. To do this, use:

@GeneratedValue(strategy=GenerationType.AUTO)

How to determine device screen size category (small, normal, large, xlarge) using code?

Couldn't you do this using a string resource and enums? You can define a string resource that had the name of the screen size, such as SMALL, MEDIUM, or LARGE. Then you could use the value of the string resource to create an instance of the enum.

  1. Define an Enum in your code for the different screen sizes you care about.

    public Enum ScreenSize {
        SMALL,
        MEDIUM,
        LARGE,;
    }
    
  2. Define a string resource, say screensize, whose value will be either SMALL, MEDIUM, or LARGE.

    <string name="screensize">MEDIUM</string>
    
  3. Put a copy of screensize in a string resource in each dimension you care about.
    For example, <string name="screensize">MEDIUM</string> would go in values-sw600dp/strings.xml and values-medium/strings.xml and <string name="screensize">LARGE</string> would go in sw720dp/strings.xml and values-large/strings.xml.
  4. In code, write
    ScreenSize size = ScreenSize.valueOf(getReources().getString(R.string.screensize);

Android Studio 3.0 Execution failed for task: unable to merge dex

I Have Done and fixed this issue by just doing this jobs in my code

Open ->build.gradle Change value from

compile 'com.google.code.gson:gson:2.6.1'

to

compile 'com.google.code.gson:gson:2.8.2'

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

Simulating Button click in javascript

Or you can use what JQuery alreay made for you:

http://jqueryui.com/datepicker/#icon-trigger

It's what you are trying to achieve isn't it?

Sorting a list with stream.sorted() in Java

It seems to be working fine:

List<BigDecimal> list = Arrays.asList(new BigDecimal("24.455"), new BigDecimal("23.455"), new BigDecimal("28.455"), new BigDecimal("20.455"));
System.out.println("Unsorted list: " + list);
final List<BigDecimal> sortedList = list.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList());
System.out.println("Sorted list: " + sortedList);

Example Input/Output

Unsorted list: [24.455, 23.455, 28.455, 20.455]
Sorted list: [20.455, 23.455, 24.455, 28.455]

Are you sure you are not verifying list instead of sortedList [in above example] i.e. you are storing the result of stream() in a new List object and verifying that object?

Removing header column from pandas dataframe

Haven't seen this solution yet so here's how I did it without using read_csv:

df.rename(columns={'A':'','B':''})

If you rename all your column names to empty strings your table will return without a header.

And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:

df_dict = dict.fromkeys(df.columns, '')
df.rename(columns = df_dict)

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I am posting my answer because I suspect there might be someone out there for whom the above solutions might not have worked.

So, you are getting a warning,

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server: (project name)' did not find a matching property.

Rather than disabling this warning by checking that option in Server configuration (I did try that) I would suggest you do this:

  1. First close all the existing projects by right clicking in Project explorer.
  2. Remove all the projects already synchronized with the server.
  3. Remove the server and redeploy it.
  4. Create a new dynamic project, do nothing yet just try running this on the server.
  5. Check the console, do you get the warning now. (My case I didn't get any).
    This means that something is wrong with your project not with eclipse or the server.
  6. Now restart the server. Don't run any app yet.
    You probably know that the Tomcat container loads up context of all the synchronized apps at the start.
  7. It will load context of any already synchronized app.
  8. Here is the catch, if there is really something wrong in your project it will show the stack trace of the exceptions.Look carefully and you will find where is the bug in your app.

Now if you successfully found that there is a bug in your app, the probable place would be look for a web.xml file which the container uses for loading the app. In my case I had misspelled a name in servlet mapping which made me debug meaninglessly for 3 hours. Your problem might be someplace else.

And another thing, if you have many apps synchronized with the server,there is a possibility some other app's context might be the source of problem. Try debugging one by one.

How to create a fixed sidebar layout with Bootstrap 4?

I used this in my code:

<div class="sticky-top h-100">
    <nav id="sidebar" class="vh-100">
        ....

this cause your sidebar height become 100% and fixed at top.

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

How to add jQuery code into HTML Page

Make sure that you embedd the jQuery library into your page by adding the below shown line into your <head> block:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

I have same error. Problem was that branch was deleted, released. But in PhpStorm I still could see it in remote branches. I could checkout as local branch. And then doing git pull was giving this error.

So need to check if this brnach really exists remotely.

How to manually send HTTP POST requests from Firefox or Chrome browser?

I think that @Benny Neugebauer comment on the OP question about the Fetch API should be presented here as an answer since the OP was looking for a functionality in Chrome to manually create HTTP POST requests and that exactly what the fetch command do.

There is a nice simple example of the Fetch API here

// Make sure you run it from the domain 'https://jsonplaceholder.typicode.com/'. (cross-origin-policy)
fetch('https://jsonplaceholder.typicode.com/posts',{method: 'POST', headers: {'test': 'TestPost'} })
  .then(response => response.json())
  .then(json => console.log(json))

Some of the advantages of the fetch command are really precious: Its simple, short, fast, available and even as a console command it stored on your chrome console and can be used later.

The simplicity of pressing F12, write the command in the console tab (or press the up key if you used it before) then press enter, see it pending and returning the response is what making it really useful for simple post requests tests.

Of course, The main disadvantage here is that unlike Postman, This wont pass the cross-origin-policy but still I find it very useful for testing in local environment or other environments where I can enable CORS manually.

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

With adb, you can install GApps and ARM Support zips without a drag & drop. emuking from XDA Developers has instructions for it:

I used 4.2.2, which is acceptable for my testing purposes. I then extracted both zip's "/system/..." folders to a folder on my desktop. In cmd prompt I used the following commands (step 1 is optional and for verification that adb is working):

  1. adb devices
  2. adb remount
  3. adb push "C:\Users\John\Desktop\GenyF_cked\system" /system

You'll have to change the folder name in "adb push" line to where you actually extracted both zip files. After doing it, I recommend you to "adb reboot" the device.

Can I disable a CSS :hover effect via JavaScript?

You can manipulate the stylesheets and stylesheet rules themselves with javascript

var sheetCount = document.styleSheets.length;
var lastSheet = document.styleSheets[sheetCount-1];
var ruleCount;
if (lastSheet.cssRules) { // Firefox uses 'cssRules'
    ruleCount = lastSheet.cssRules.length;
}
else if (lastSheet.rules) { / /IE uses 'rules'
    ruleCount = lastSheet.rules.length;
}
var newRule = "a:hover { text-decoration: none !important; color: #000 !important; }";
// insert as the last rule in the last sheet so it
// overrides (not overwrites) previous definitions
lastSheet.insertRule(newRule, ruleCount);

Making the attributes !important and making this the very last CSS definition should override any previous definition, unless one is more specifically targeted. You may have to insert more rules in that case.

URL Encode a string in jQuery for an AJAX request

encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:

  $.ajax({
    cache: false,
    type: "POST",
    url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
    data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
    dataType: "HTML",
    success: function (data) {
    },
    error: function (xhr, ajaxOptions, thrownError) {
    }
  });

Convert java.time.LocalDate into java.util.Date type

Simple

public Date convertFrom(LocalDate date) {
    return java.sql.Timestamp.valueOf(date.atStartOfDay());
}

Dynamically add child components in React

Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

Rails: Can't verify CSRF token authenticity when making a POST request

The simplest solution for the problem is do standard things in your controller or you can directely put it into ApplicationController

class ApplicationController < ActionController::Base protect_from_forgery with: :exception, prepend: true end

How to check if multiple array keys exists

Here is a solution that's scalable, even if you want to check for a large number of keys:

<?php

// The values in this arrays contains the names of the indexes (keys) 
// that should exist in the data array
$required = array('key1', 'key2', 'key3');

$data = array(
    'key1' => 10,
    'key2' => 20,
    'key3' => 30,
    'key4' => 40,
);

if (count(array_intersect_key(array_flip($required), $data)) === count($required)) {
    // All required keys exist!
}

jquery, domain, get URL

You don't need jQuery for this, as simple javascript will suffice:

alert(document.domain);

See it in action:

_x000D_
_x000D_
console.log("Output;");  _x000D_
console.log(location.hostname);_x000D_
console.log(document.domain);_x000D_
alert(window.location.hostname)_x000D_
_x000D_
console.log("document.URL : "+document.URL);_x000D_
console.log("document.location.href : "+document.location.href);_x000D_
console.log("document.location.origin : "+document.location.origin);_x000D_
console.log("document.location.hostname : "+document.location.hostname);_x000D_
console.log("document.location.host : "+document.location.host);_x000D_
console.log("document.location.pathname : "+document.location.pathname);
_x000D_
_x000D_
_x000D_

For further domain-related values, check out the properties of window.location online. You may find that location.host is a better option, as its content could differ from document.domain. For instance, the url http://192.168.1.80:8080 will have only the ipaddress in document.domain, but both the ipaddress and port number in location.host.

How do I execute cmd commands through a batch file?

cmd /k cd c:\ is the right answer

IIS7 Permissions Overview - ApplicationPoolIdentity

Just to add to the confusion, the (Windows Explorer) Effective Permissions dialog doesn't work for these logins. I have a site "Umbo4" using pass-through authentication, and looked at the user's Effective Permissions in the site root folder. The Check Names test resolved the name "IIS AppPool\Umbo4", but the Effective Permissions shows that the user had no permissions at all on the folder (all checkboxes unchecked).

I then excluded this user from the folder explicitly, using the Explorer Security tab. This resulted in the site failing with a HTTP 500.19 error, as expected. The Effective Permissions however looked exactly as before.

How do I unset an element in an array in javascript?

Don't use delete as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array.

If you know the key you should use splice i.e.

myArray.splice(key, 1);

For someone in Steven's position you can try something like this:

for (var key in myArray) {
    if (key == 'bar') {
        myArray.splice(key, 1);
    }
}

or

for (var key in myArray) {
    if (myArray[key] == 'bar') {
        myArray.splice(key, 1);
    }
}

What is the $$hashKey added to my JSON.stringify result

If you are using Angular 1.3 or above, I recommend that you use "track by" in your ng-repeat. Angular doesn't add a "$$hashKey" property to the objects in your array if you use "track by". You also get performance benefits, if something in your array changes, angular doesn't recreate the entire DOM structure for your ng-repeat, it instead recreates the part of the DOM for the values in your array that have changed.

How can I show figures separately in matplotlib?

None of the above solutions seems to work in my case, with matplotlib 3.1.0 and Python 3.7.3. Either both the figures show up on calling show() or none show up in different answers posted above.

Building upon @Ivan's answer, and taking hint from here, the following seemed to work well for me:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1) # Creates figure fig and add an axes, ax.
fig2, ax2 = plt.subplots(1) # Another figure

ax.plot(range(20)) #Add a straight line to the axes of the first figure.
ax2.plot(range(100)) #Add a straight line to the axes of the first figure.

# plt.close(fig) # For not showing fig
plt.close(fig2) # For not showing fig2
plt.show()

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

my code, and it works for IE6:

<style>
#container {margin:0 auto; width:100%;}
#header { height:100px; background:#9c6; margin-bottom:5px;}
#mainContent { height:500px; margin-bottom:5px;}
#sidebar { float:left; width:100px; height:500px; background:#cf9;}
#content { margin-left:100px; height:500px; background:#ffa;}

</style>

<div id="container">
  <div id="header">header</div>
  <div id="mainContent">
    <div id="sidebar">left</div>
    <div id="content">right 100% - 100px</div>
  <span style="display:none"></span></div>
</div>

enter image description here

There is no tracking information for the current branch

I was trying the above examples and couldn't get them to sync with a (non-master) branch I had created on a different computer. For background, I created this repository on computer A (git v 1.8) and then cloned the repository onto computer B (git 2.14). I made all my changes on comp B, but when I tried to pull the changes onto computer A I was unable to do so, getting the same above error. Similar to the above solutions, I had to do:

git branch --set-upstream-to=origin/<my_repository_name> 
git pull

slightly different but hopefully helps someone

Complex numbers usage in python

The following example for complex numbers should be self explanatory including the error message at the end

>>> x=complex(1,2)
>>> print x
(1+2j)
>>> y=complex(3,4)
>>> print y
(3+4j)
>>> z=x+y
>>> print x
(1+2j)
>>> print z
(4+6j)
>>> z=x*y
>>> print z
(-5+10j)
>>> z=x/y
>>> print z
(0.44+0.08j)
>>> print x.conjugate()
(1-2j)
>>> print x.imag
2.0
>>> print x.real
1.0
>>> print x>y

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y
False
>>> 

WPF Check box: Check changed handling

That you can handle the checked and unchecked events seperately doesn't mean you have to. If you don't want to follow the MVVM pattern you can simply attach the same handler to both events and you have your change signal:

<CheckBox Checked="CheckBoxChanged" Unchecked="CheckBoxChanged"/>

and in Code-behind;

private void CheckBoxChanged(object sender, RoutedEventArgs e)
{
  MessageBox.Show("Eureka, it changed!");
}

Please note that WPF strongly encourages the MVVM pattern utilizing INotifyPropertyChanged and/or DependencyProperties for a reason. This is something that works, not something I would like to encourage as good programming habit.

.ssh directory not being created

Is there a step missing?

Yes. You need to create the directory:

mkdir ${HOME}/.ssh

Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:

% chmod 700 ~/.ssh

Should the .ssh dir be generated when I use the ssh-keygen command?

No. This command generates an SSH key pair but will fail if it cannot write to the required directory:

% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.

Once you've created your keys, you should also restrict who can read those key files to just yourself:

% chmod -R go-wrx ~/.ssh/*

Best way to parseDouble with comma as decimal separator?

This is the static method I use in my own code:

public static double sGetDecimalStringAnyLocaleAsDouble (String value) {

    if (value == null) {
        Log.e("CORE", "Null value!");
        return 0.0;
    }

    Locale theLocale = Locale.getDefault();
    NumberFormat numberFormat = DecimalFormat.getInstance(theLocale);
    Number theNumber;
    try {
        theNumber = numberFormat.parse(value);
        return theNumber.doubleValue();
    } catch (ParseException e) {
        // The string value might be either 99.99 or 99,99, depending on Locale.
        // We can deal with this safely, by forcing to be a point for the decimal separator, and then using Double.valueOf ...
        //http://stackoverflow.com/questions/4323599/best-way-to-parsedouble-with-comma-as-decimal-separator
        String valueWithDot = value.replaceAll(",",".");

        try {
          return Double.valueOf(valueWithDot);
        } catch (NumberFormatException e2)  {
            // This happens if we're trying (say) to parse a string that isn't a number, as though it were a number!
            // If this happens, it should only be due to application logic problems.
            // In this case, the safest thing to do is return 0, having first fired-off a log warning.
            Log.w("CORE", "Warning: Value is not a number" + value);
            return 0.0;
        }
    }
}

How to add multiple font files for the same font?

nowadays,2017-12-17. I don't find any description about Font-property-order‘s necessity in spec. And I test in chrome always works whatever the order is.

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-weight: 900;
  src: url('#{$fa-font-path}/fa-solid-900.eot');
  src: url('#{$fa-font-path}/fa-solid-900.eot?#iefix') format('embedded-opentype'),
  url('#{$fa-font-path}/fa-solid-900.woff2') format('woff2'),
  url('#{$fa-font-path}/fa-solid-900.woff') format('woff'),
  url('#{$fa-font-path}/fa-solid-900.ttf') format('truetype'),
  url('#{$fa-font-path}/fa-solid-900.svg#fontawesome') format('svg');
}

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-weight: 400;
  src: url('#{$fa-font-path}/fa-regular-400.eot');
  src: url('#{$fa-font-path}/fa-regular-400.eot?#iefix') format('embedded-opentype'),
  url('#{$fa-font-path}/fa-regular-400.woff2') format('woff2'),
  url('#{$fa-font-path}/fa-regular-400.woff') format('woff'),
  url('#{$fa-font-path}/fa-regular-400.ttf') format('truetype'),
  url('#{$fa-font-path}/fa-regular-400.svg#fontawesome') format('svg');
}

Spring - download response as a file

You can't download a file through an XHR request (which is how Angular makes it's requests). See Why threre is no way to download file using ajax request? You either need to go to the URL via $window.open or do the iframe trick shown here: JavaScript/jQuery to download file via POST with JSON data

UITextField text change event

  1. KVO solutions do not work

KVO does NOT work in iOS for controls: http://stackoverflow.com/a/6352525/1402846 https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/KVO.html

  1. In the observing class, you do this:

Given that you know the text view you want to watch:

var watchedTextView: UITextView!

Do this:

NotificationCenter.default.addObserver(
    self,
    selector: #selector(changed),
    name: UITextView.textDidChangeNotification,
    object: watchedTextView)

However, be careful with that:

  • it's likely you only want to call that once, so do not call it in, for example, layoutSubviews

  • it's quite difficult to know when to best call it during your bring-up process. It will depend on your situation. Unfortunately there is no standard, locked-in solution

  • for example you usually certainly can not call it at init time, since of course watchedTextView may not exist yet

.

  1. the next problem is that ...

None of the notifications are called when text is changed programmatically.

This is a huge, age-old, and stupid, nuisance in iOS engineering.

Controls simply do not - end of story - call the notifcations when the .text property is changed programmatically.

This is insanely annoying because of course - obviously - every app ever made sets the text programmatically, such as clearing the field after the user posts, etc.

You have to subclass the text view (or similar control) like this:

class NonIdioticTextView: UIITextView {

    override var text: String! {
        // boilerplate code needed to make watchers work properly:
        get {
            return super.text
        }
        set {
            super.text = newValue
            NotificationCenter.default.post(
                name: UITextView.textDidChangeNotification,
                object: self)
        }

    }

}

(Tip - don't forget the super call has to come before ! the post call.)

There is no solution available, unless, you fix the control by subclassing as shown just above. That is the only solution.

Note that the notification

UITextView.textDidChangeNotification

results in

func textViewDidChangeSelection(_ textView: UITextView) 

being called.

(Not textViewDidChange .)

How do I get the max and min values from a set of numbers entered?

//for excluding zero
public class SmallestInt {

    public static void main(String[] args) {

        Scanner input= new Scanner(System.in);

        System.out.println("enter number");
        int val=input.nextInt();
        int min=val;

        //String notNull;

        while(input.hasNextInt()==true)
        {
            val=input.nextInt();
            if(val<min)
                min=val;
        }
        System.out.println("min is: "+min);
    }
}

How do you make websites with Java?

I'd suggest OOWeb to act as an HTTP server and a templating engine like Velocity to generate HTML. I also second Esko's suggestion of Wicket. Both solutions are considerably simpler than the average setup.

What does flex: 1 mean?

Here is the explanation:

https://www.w3.org/TR/css-flexbox-1/#flex-common

flex: <positive-number>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the free space in the flex container. If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.

Therefore flex:1 is equivalent to flex: 1 1 0

How do you tell if caps lock is on using JavaScript?

In jQuery,

$('#example').keypress(function(e) { 
    var s = String.fromCharCode( e.which );
    if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
        alert('caps is on');
    }
});

Avoid the mistake, like the backspace key, s.toLowerCase() !== s is needed.

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

Verify if file exists or not in C#

You can determine whether a specified file exists using the Exists method of the File class in the System.IO namespace:

bool System.IO.File.Exists(string path)

You can find the documentation here on MSDN.

Example:

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string resumeFile = @"c:\ResumesArchive\923823.txt";
        string newFile = @"c:\ResumesImport\newResume.txt";
        if (File.Exists(resumeFile))
        {
            File.Copy(resumeFile, newFile);
        }
        else
        {
            Console.WriteLine("Resume file does not exist.");
        }
    }
}

how to realize countifs function (excel) in R

Easy peasy. Your data frame will look like this:

df <- data.frame(sex=c('M','F','M'),
                 occupation=c('Student','Analyst','Analyst'))

You can then do the equivalent of a COUNTIF by first specifying the IF part, like so:

df$sex == 'M'

This will give you a boolean vector, i.e. a vector of TRUE and FALSE. What you want is to count the observations for which the condition is TRUE. Since in R TRUE and FALSE double as 1 and 0 you can simply sum() over the boolean vector. The equivalent of COUNTIF(sex='M') is therefore

sum(df$sex == 'M')

Should there be rows in which the sex is not specified the above will give back NA. In that case, if you just want to ignore the missing observations use

sum(df$sex == 'M', na.rm=TRUE)

VBA (Excel) Initialize Entire Array without Looping

Fancy way to put @rdhs answer in a function:

Function arrayZero(size As Integer)
  arrayZero = Evaluate("=IF(ISERROR(Transpose(A1:A" & size & ")), 0, 0)")
End Function

And use like this:

myArray = arrayZero(15)

What does the C++ standard state the size of int, long type to be?

unsigned char bits = sizeof(X) << 3;

where X is a char,int,long etc.. will give you size of X in bits.

Why am I getting the message, "fatal: This operation must be run in a work tree?"

Create a bare GIT repository

A small rant: git is unable to create a normal bare repository by itself. Stupid git indeed.

To be precise, it is not possible to clone empty repositories. So an empty repository is a useless repository. Indeed, you normally create an empty repository and immediately fill it:

git init
git add .

However, git add is not possible when you create a bare repository:

git --bare init
git add .

gives an error "fatal: This operation must be run in a work tree".

You can't check it out either:

Initialized empty Git repository in /home/user/myrepos/.git/
fatal: http://repository.example.org/projects/myrepos.git/info/refs not found: did you run git update-server-info on the server?

git --bare init
git update-server-info # this creates the info/refs file
chown -R <user>:<group> . # make sure others can update the repository

The solution is to create another repository elsewhere, add a file in that repository and, push it to the bare repository.

mkdir temp; cd temp
git init
touch .gitignore
git add .gitignore
git commit -m "Initial commit"
git push (url or path of bare repository) master
cd ..; rm -rf temp

hope this can help u

Parse JSON String into a Particular Object Prototype in JavaScript

The current answers contain a lot of hand-rolled or library code. This is not necessary.

  1. Use JSON.parse('{"a":1}') to create a plain object.

  2. Use one of the standardized functions to set the prototype:

    • Object.assign(new Foo, { a: 1 })
    • Object.setPrototypeOf({ a: 1 }, Foo.prototype)

Matplotlib color according to class labels

A simple solution is to assign color for each class. This way, we can control how each color is for each class. For example:

arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 3, 3, 4, 4]
labl = [0, 1, 1, 0, 0]
color= ['red' if l == 0 else 'green' for l in labl]
plt.scatter(arr1, arr2, color=color)

Encode URL in JavaScript?

Elegant way

In my humble opinion the most elegant way to encode query params is to create an object with params like

const queryParams = { param1: 'value1', param2: 'value2' }

and then encode it using:

const queryString = new URLSearchParams(queryParams).toString()

as mentioned in this answer: https://stackoverflow.com/a/53171438/7284582

C# password TextBox in a ASP.net website

@JohnHartsock: You can also write type="password". It's acceptable in aspx.

<asp:TextBox ID="txtBox" type="password" runat="server"/>

Best Practice for Forcing Garbage Collection in C#

However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead...

IMHO, this is similar to saying "If you can prove that your program will never have any bugs in the future, then go ahead..."

In all seriousness, forcing the GC is useful for debugging/testing purposes. If you feel like you need to do it at any other times, then either you are mistaken, or your program has been built wrong. Either way, the solution is not forcing the GC...

Origin http://localhost is not allowed by Access-Control-Allow-Origin

You've got two ways to go forward:

JSONP


If this API supports JSONP, the easiest way to fix this issue is to add &callback to the end of the URL. You can also try &callback=. If that doesn't work, it means the API does not support JSONP, so you must try the other solution.

Proxy Script


You can create a proxy script on the same domain as your website in order to avoid the cross-origin issues. This will only work with HTTP URLs, not HTTPS URLs, but it shouldn't be too difficult to modify if you need that.

<?php
// File Name: proxy.php
if (!isset($_GET['url'])) {
    die(); // Don't do anything if we don't have a URL to work with
}
$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file system
echo file_get_contents($url); // You should probably use cURL. The concept is the same though

Then you just call this script with jQuery. Be sure to urlencode the URL.

$.ajax({
    url      : 'proxy.php?url=http%3A%2F%2Fapi.master18.tiket.com%2Fsearch%2Fautocomplete%2Fhotel%3Fq%3Dmah%26token%3D90d2fad44172390b11527557e6250e50%26secretkey%3D83e2f0484edbd2ad6fc9888c1e30ea44%26output%3Djson',
    type     : 'GET',
    dataType : 'json'
}).done(function(data) {
    console.log(data.results.result[1].category); // Do whatever you want here
});

The Why


You're getting this error because of XMLHttpRequest same origin policy, which basically boils down to a restriction of ajax requests to URLs with a different port, domain or protocol. This restriction is in place to prevent cross-site scripting (XSS) attacks.

More Information

Our solutions by pass these problems in different ways.

JSONP uses the ability to point script tags at JSON (wrapped in a javascript function) in order to receive the JSON. The JSONP page is interpreted as javascript, and executed. The JSON is passed to your specified function.

The proxy script works by tricking the browser, as you're actually requesting a page on the same origin as your page. The actual cross-origin requests happen server-side.

How can I set response header on express.js assets

There is at least one middleware on npm for handling CORS in Express: cors. [see @mscdex answer]

This is how to set custom response headers, from the ExpressJS DOC

res.set(field, [value])

Set header field to value

res.set('Content-Type', 'text/plain');

or pass an object to set multiple fields at once.

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  'ETag': '12345'
})

Aliased as

res.header(field, [value])

Strange out of memory issue while loading an image to a Bitmap object

Best practices to avoid memory leaks or OOM for bitmap

  1. Do not keep bitmap references for long-lived to a Context / Activity.
  2. If you are using a large bitmap as background or something in your application then don’t pull the full image into the main memory. You can use the insample size property of bitmap to bring the size your screen needs.
  3. Clean bitmap reference once no longer use.

What is the difference between a static and const variable?

static keyword defines the scope of variables whereas const keyword defines the value of variable that can't be changed during program execution

django import error - No module named core.management

I fixed this problem by changing #PATH="$VIRTUAL_ENV/bin:$PATH" to PATH="$PATH:$VIRTUAL_ENV/bin" For reasons not obvious to me the python executable in the virtualenv dir does not see django but the normally installed python does.

Get filename and path from URI from mediastore

Here you get the name of the file

String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};
                    Uri uri = data.getData();
                    String fileName = null;
                    ContentResolver cr = getActivity().getApplicationContext().getContentResolver();

                    Cursor metaCursor = cr.query(uri,
                            projection, null, null, null);
                    if (metaCursor != null) {
                        try {
                            if (metaCursor.moveToFirst()) {
                                fileName = metaCursor.getString(0);
                            }
                        } finally {
                            metaCursor.close();
                        }
                    }

How do I start a process from C#?

As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class...

using System.Diagnostics;
...
Process.Start("process.exe");

The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish.

using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.

This method allows far more control than I've mentioned.

System.loadLibrary(...) couldn't find native library in my case

You could just change ABI to use older builds:

defaultConfig {
    ...

    ndk {
        abiFilters 'armeabi-v7a'
    }
    ...
}

You should also use deprecated NDK by adding this line to gradle.properties:

android.useDeprecatedNdk=true

How can I solve a connection pool problem between ASP.NET and SQL Server?

I wasn't thinking this was my issue at first but in running through this list I discovered that it didn't cover what my issues was.

My issue was that I had a bug in which it tried to write the same record numerous times using entity framework. It shouldn't have been doing this; it was my bug. Take a look at the data you are writing. My thoughts are that SQL was busy writing a record, possibly locking and creating the timeout. After I fixed the area of code that was attempting to write the record multiple in sequential attempts, the error went away.

What regular expression will match valid international phone numbers?

It works pretty well with 00xx and +xx:

^(?:00|\+)(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$

How does strtok() split the string into tokens in C?

For those who are still having hard time understanding this strtok() function, take a look at this pythontutor example, it is a great tool to visualize your C (or C++, Python ...) code.

In case the link got broken, paste in:

#include <stdio.h>
#include <string.h>

int main()
{
    char s[] = "Hello, my name is? Matthew! Hey.";
    char* p;
    for (char *p = strtok(s," ,?!."); p != NULL; p = strtok(NULL, " ,?!.")) {
      puts(p);
    }
    return 0;
}

Credits go to Anders K.

How to prevent SIGPIPEs (or handle them properly)

Under a modern POSIX system (i.e. Linux), you can use the sigprocmask() function.

#include <signal.h>

void block_signal(int signal_to_block /* i.e. SIGPIPE */ )
{
    sigset_t set;
    sigset_t old_state;

    // get the current state
    //
    sigprocmask(SIG_BLOCK, NULL, &old_state);

    // add signal_to_block to that existing state
    //
    set = old_state;
    sigaddset(&set, signal_to_block);

    // block that signal also
    //
    sigprocmask(SIG_BLOCK, &set, NULL);

    // ... deal with old_state if required ...
}

If you want to restore the previous state later, make sure to save the old_state somewhere safe. If you call that function multiple times, you need to either use a stack or only save the first or last old_state... or maybe have a function which removes a specific blocked signal.

For more info read the man page.

Where is the Java SDK folder in my computer? Ubuntu 12.04

In generally, java gets installed at /usr/lib/jvm . That is where my sun jdk is installed. check if it is same for open jdk also.

How to grep for two words existing on the same line?

you could use awk. like this...

cat <yourFile> | awk '/word1/ && /word2/'

Order is not important. So if you have a file and...

a file named , file1 contains:

word1 is in this file as well as word2
word2 is in this file as well as word1
word4 is in this file as well as word1
word5 is in this file as well as word2

then,

/tmp$ cat file1| awk '/word1/ && /word2/'

will result in,

word1 is in this file as well as word2
word2 is in this file as well as word1

yes, awk is slower.

Running .sh scripts in Git Bash

Let's say you have a script script.sh. To run it (using Git Bash), you do the following: [a] Add a "sh-bang" line on the first line (e.g. #!/bin/bash) and then [b]:

# Use ./ (or any valid dir spec):
./script.sh

Note: chmod +x does nothing to a script's executability on Git Bash. It won't hurt to run it, but it won't accomplish anything either.

How to get df linux command output always in GB

If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:

alias df-gb='df -BG'

So if you type:

df-gb

into a terminal, you'll get your intended output of the disk usage in GB.

EDIT: or even use just df -h to get it in a standard, human readable format.

http://www.thegeekstuff.com/2012/05/df-examples/

Add Header and Footer for PDF using iTextsharp

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using DataLayer;

namespace DataMngt.MyCode
{
    public class HeaderFooter : PdfPageEventHelper
    {
        #region Startup_Stuff

        private string[] _headerLines;
        private string _footerLine;

        private DefineFont _boldFont;
        private DefineFont _normalFont;

        private iTextSharp.text.Font fontTxtBold;
        private iTextSharp.text.Font fontTxtRegular;

        private int _fontPointSize = 0;

        private bool hasFooter = false;
        private bool hasHeader = false;

        private int _headerWidth = 0;
        private int _headerHeight = 0;

        private int _footerWidth = 0;
        private int _footerHeight = 0;

        private int _leftMargin = 0;
        private int _rightMargin = 0;
        private int _topMargin = 0;
        private int _bottomMargin = 0;

        private PageNumbers NumberSettings;

        private DateTime runTime = DateTime.Now;             

        public enum PageNumbers
        {
            None,
            HeaderPlacement,
            FooterPlacement
        }

        // This is the contentbyte object of the writer
        PdfContentByte cb;

        PdfTemplate headerTemplate;
        PdfTemplate footerTemplate;

        public string[] headerLines
        {
            get
            {
                return _headerLines;
            }
            set
            {
                _headerLines = value;
                hasHeader = true;
            }
        }

        public string footerLine
        {
            get
            {
                return _footerLine;
            }
            set
            {
                _footerLine = value;
                hasFooter = true;
            }
        }

        public DefineFont boldFont
        {
            get
            {
                return _boldFont;
            }
            set
            {
                _boldFont = value;
            }
        }

        public DefineFont normalFont
        {
            get
            {
                return _normalFont;
            }
            set
            {
                _normalFont = value;
            }
        }

        public int fontPointSize
        {
            get
            {
                return _fontPointSize;
            }
            set
            {
                _fontPointSize = value;
            }
        }

        public int leftMargin
        {
            get
            {
                return _leftMargin;
            }
            set
            {
                _leftMargin = value;
            }
        }

        public int rightMargin
        {
            get
            {
                return _rightMargin;
            }
            set
            {
                _rightMargin = value;
            }
        }

        public int topMargin
        {
            get
            {
                return _topMargin;
            }
            set
            {
                _topMargin = value;
            }
        }

        public int bottomMargin
        {
            get
            {
                return _bottomMargin;
            }
            set
            {
                _bottomMargin = value;
            }
        }

        public int headerheight
        {
            get
            {
                return _headerHeight;
            }
        }

        public int footerHeight
        {
            get
            {
                return _footerHeight;
            }
        }

        public PageNumbers PageNumberSettings
        {
            get
            {
                return NumberSettings;
            }

            set
            {
                NumberSettings = value;
            }
        }

        #endregion

        #region Write_Headers_Footers

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            if (hasHeader)
            {
                // left side is the string array passed in
                // right side is a built in string array (0 = date, 1 = time, 2(optional) = page)
                float[] widths = new float[2] { 90f, 10f };

                PdfPTable hdrTable = new PdfPTable(2);
                hdrTable.TotalWidth = document.PageSize.Width - (_leftMargin + _rightMargin);
                hdrTable.WidthPercentage = 95;
                hdrTable.SetWidths(widths);
                hdrTable.LockedWidth = true;

                for (int hdrIdx = 0; hdrIdx < (_headerLines.Length < 2 ? 2 : _headerLines.Length); hdrIdx ++)
                {
                    string leftLine = (hdrIdx < _headerLines.Length ? _headerLines[hdrIdx] : string.Empty);

                    Paragraph leftPara = new Paragraph(5, leftLine, (hdrIdx == 0 ? fontTxtBold : fontTxtRegular));

                    switch (hdrIdx)
                    {
                        case 0:
                            {
                                leftPara.Font.Size = _fontPointSize;

                                PdfPCell leftCell = new PdfPCell(leftPara);
                                leftCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                leftCell.Border = 0;

                                string rightLine = string.Format(SalesPlanResources.datePara, runTime.ToString(SalesPlanResources.datePrintMask));
                                Paragraph rightPara = new Paragraph(5, rightLine, (hdrIdx == 0 ? fontTxtBold : fontTxtRegular));
                                rightPara.Font.Size = _fontPointSize;

                                PdfPCell rightCell = new PdfPCell(rightPara);
                                rightCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                rightCell.Border = 0;

                                hdrTable.AddCell(leftCell);
                                hdrTable.AddCell(rightCell);

                                break;
                            }

                        case 1:
                            {
                                leftPara.Font.Size = _fontPointSize;

                                PdfPCell leftCell = new PdfPCell(leftPara);
                                leftCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                leftCell.Border = 0;

                                string rightLine = string.Format(SalesPlanResources.timePara, runTime.ToString(SalesPlanResources.timePrintMask));
                                Paragraph rightPara = new Paragraph(5, rightLine, (hdrIdx == 0 ? fontTxtBold : fontTxtRegular));
                                rightPara.Font.Size = _fontPointSize;

                                PdfPCell rightCell = new PdfPCell(rightPara);
                                rightCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                rightCell.Border = 0;

                                hdrTable.AddCell(leftCell);
                                hdrTable.AddCell(rightCell);

                                break;
                            }

                        case 2:
                            {
                                leftPara.Font.Size = _fontPointSize;

                                PdfPCell leftCell = new PdfPCell(leftPara);
                                leftCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                leftCell.Border = 0;

                                string rightLine;
                                if (NumberSettings == PageNumbers.HeaderPlacement)
                                {
                                    rightLine = string.Concat(SalesPlanResources.pagePara, writer.PageNumber.ToString());
                                }
                                else
                                {
                                    rightLine = string.Empty; 
                                }
                                Paragraph rightPara = new Paragraph(5, rightLine, fontTxtRegular);
                                rightPara.Font.Size = _fontPointSize;

                                PdfPCell rightCell = new PdfPCell(rightPara);
                                rightCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                rightCell.Border = 0;

                                hdrTable.AddCell(leftCell);
                                hdrTable.AddCell(rightCell);

                                break;
                            }

                        default:
                            {
                                leftPara.Font.Size = _fontPointSize;

                                PdfPCell leftCell = new PdfPCell(leftPara);
                                leftCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                leftCell.Border = 0;
                                leftCell.Colspan = 2;                               

                                hdrTable.AddCell(leftCell);

                                break;
                            }
                    }
                }

                hdrTable.WriteSelectedRows(0, -1, _leftMargin, document.PageSize.Height - _topMargin, writer.DirectContent);

                //Move the pointer and draw line to separate header section from rest of page
                cb.MoveTo(_leftMargin, document.Top + 10);
                cb.LineTo(document.PageSize.Width - _leftMargin, document.Top + 10);
                cb.Stroke();
            }

            if (hasFooter)
            {
                // footer line is the width of the page so it is centered horizontally 
                PdfPTable ftrTable = new PdfPTable(1);
                float[] widths = new float[1] {100 };

                ftrTable.TotalWidth = document.PageSize.Width - 10;
                ftrTable.WidthPercentage = 95;
                ftrTable.SetWidths(widths);

                string OneLine;

                if (NumberSettings == PageNumbers.FooterPlacement)
                {
                    OneLine = string.Concat(_footerLine, writer.PageNumber.ToString());
                }
                else
                {
                    OneLine = _footerLine;
                }

                Paragraph onePara = new Paragraph(0, OneLine, fontTxtRegular);
                onePara.Font.Size = _fontPointSize;

                PdfPCell oneCell = new PdfPCell(onePara);
                oneCell.HorizontalAlignment = Element.ALIGN_CENTER; 
                oneCell.Border = 0;
                ftrTable.AddCell(oneCell);

                ftrTable.WriteSelectedRows(0, -1, _leftMargin, (_footerHeight), writer.DirectContent);

                //Move the pointer and draw line to separate footer section from rest of page
                cb.MoveTo(_leftMargin, document.PageSize.GetBottom(_footerHeight + 2));
                cb.LineTo(document.PageSize.Width - _leftMargin, document.PageSize.GetBottom(_footerHeight + 2));
                cb.Stroke();
            }
        }

        #endregion


        #region Setup_Headers_Footers_Happens_here

        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            // create the fonts that are to be used
            // first the hightlight or Bold font
            fontTxtBold = FontFactory.GetFont(_boldFont.fontFamily, _boldFont.fontSize, _boldFont.foreColor);
            if (_boldFont.isBold)
            {
                fontTxtBold.SetStyle(Font.BOLD);
            }
            if (_boldFont.isItalic)
            {
                fontTxtBold.SetStyle(Font.ITALIC);
            }
            if (_boldFont.isUnderlined)
            {
                fontTxtBold.SetStyle(Font.UNDERLINE);
            }

            // next the normal font
            fontTxtRegular = FontFactory.GetFont(_normalFont.fontFamily, _normalFont.fontSize, _normalFont.foreColor);
            if (_normalFont.isBold)
            {
                fontTxtRegular.SetStyle(Font.BOLD);
            }
            if (_normalFont.isItalic)
            {
                fontTxtRegular.SetStyle(Font.ITALIC);
            }
            if (_normalFont.isUnderlined)
            {
                fontTxtRegular.SetStyle(Font.UNDERLINE);
            }

            // now build the header and footer templates
            try
            {
                float pageHeight = document.PageSize.Height;
                float pageWidth = document.PageSize.Width;

                _headerWidth = (int)pageWidth - ((int)_rightMargin + (int)_leftMargin);
                _footerWidth = _headerWidth;

                if (hasHeader)
                {
                    // i basically dummy build the headers so i can trial fit them and see how much space they take.
                    float[] widths = new float[1] { 90f };

                    PdfPTable hdrTable = new PdfPTable(1);
                    hdrTable.TotalWidth = document.PageSize.Width - (_leftMargin + _rightMargin);
                    hdrTable.WidthPercentage = 95;
                    hdrTable.SetWidths(widths);
                    hdrTable.LockedWidth = true;

                    _headerHeight = 0;

                    for (int hdrIdx = 0; hdrIdx < (_headerLines.Length < 2 ? 2 : _headerLines.Length); hdrIdx++)
                    {
                        Paragraph hdrPara = new Paragraph(5, hdrIdx > _headerLines.Length - 1 ? string.Empty : _headerLines[hdrIdx], (hdrIdx > 0 ? fontTxtRegular : fontTxtBold));
                        PdfPCell hdrCell = new PdfPCell(hdrPara);
                        hdrCell.HorizontalAlignment = Element.ALIGN_LEFT;
                        hdrCell.Border = 0;
                        hdrTable.AddCell(hdrCell);
                        _headerHeight = _headerHeight + (int)hdrTable.GetRowHeight(hdrIdx);
                    }

                    // iTextSharp underestimates the size of each line so fudge it a little 
                    // this gives me 3 extra lines to play with on the spacing
                    _headerHeight = _headerHeight + (_fontPointSize * 3);

                }

                if (hasFooter)
                {
                    _footerHeight = (_fontPointSize * 2);
                }

                document.SetMargins(_leftMargin, _rightMargin, (_topMargin + _headerHeight), _footerHeight);

                cb = writer.DirectContent;

                if (hasHeader)
                {
                    headerTemplate = cb.CreateTemplate(_headerWidth, _headerHeight);
                }

                if (hasFooter)
                {
                    footerTemplate = cb.CreateTemplate(_footerWidth, _footerHeight);
                }
            }
            catch (DocumentException de)
            {

            }
            catch (System.IO.IOException ioe)
            {

            }
        }

        #endregion

        #region Cleanup_Doc_Processing

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);

            if (hasHeader)
            {
                headerTemplate.BeginText();
                headerTemplate.SetTextMatrix(0, 0);

                if (NumberSettings == PageNumbers.HeaderPlacement)
                {
                }

                headerTemplate.EndText();
            }

            if (hasFooter)
            {
                footerTemplate.BeginText();
                footerTemplate.SetTextMatrix(0, 0);

                if (NumberSettings == PageNumbers.FooterPlacement)
                {
                }

                footerTemplate.EndText();
            }
        }

        #endregion

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace DataMngt.MyCode
{

    // used to define the fonts passed into the header and footer class
    public struct DefineFont
    {
        public string fontFamily { get; set; }
        public int fontSize { get; set; }
        public bool isBold { get; set; }
        public bool isItalic { get; set; }
        public bool isUnderlined { get; set; }
        public BaseColor foreColor { get; set; }
    }
}

To Use:

 Document pdfDoc = new Document(PageSize.LEGAL.Rotate(), 10, 10, 25, 25);
 System.IO.MemoryStream mStream = new System.IO.MemoryStream();
 PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
 MyCode.HeaderFooter headers = new MyCode.HeaderFooter();
 writer.PageEvent = headers;

.. .. Build the string array for the headers ...

DefineFont passFont = new DefineFont();

    // always set this to the largest font used
    headers.fontPointSize = 8;

    // set up the highlight or bold font
    passFont.fontFamily = "Helvetica";
    passFont.fontSize = 8;
    passFont.isBold = true;
    passFont.isItalic = false;
    passFont.isUnderlined = false;
    passFont.foreColor = BaseColor.BLACK;

    headers.boldFont = passFont;

    // now setup the normal text font
    passFont.fontSize = 7;
    passFont.isBold = false;

    headers.normalFont = passFont;

    headers.leftMargin = 10;
    headers.bottomMargin = 25;
    headers.rightMargin = 10;
    headers.topMargin = 25;

    headers.PageNumberSettings = HeaderFooter.PageNumbers.FooterPlacement;

    headers.footerLine = "Page";
    headers.headerLines = parmLines.ToArray();

    pdfDoc.SetMargins(headers.leftMargin, headers.rightMargin, headers.topMargin + headers.headerheight, headers.bottomMargin + headers.footerHeight);
    pdfDoc.Open();

    // the new page is necessary due to a bug in in the current version of itextsharp
    pdfDoc.NewPage();

... now your headers and footer will be handled automatically

@Media min-width & max-width

The underlying issue is using max-device-width vs plain old max-width.

Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.

For example:

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE for DEVICES with physical max-screen width of 480px */
}

Versus

@media only screen and (max-width: 480px) {
    /* STYLES HERE for BROWSER WINDOWS with a max-width of 480px. 
       This will work on desktops when the window is narrowed.  */
}

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

How can I find the OWNER of an object in Oracle?

I found this question as the top result while Googling how to find the owner of a table in Oracle, so I thought that I would contribute a table specific answer for others' convenience.

To find the owner of a specific table in an Oracle DB, use the following query:

select owner from ALL_TABLES where TABLE_NAME ='<MY-TABLE-NAME>';

Java code To convert byte to Hexadecimal

The Best solution is this badass one-liner:

String hex=DatatypeConverter.printHexBinary(byte[] b);

as mentioned here

Java constructor/method with optional parameters?

Java doesn't support default parameters. You will need to have two constructors to do what you want.

An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.

e.g.

   public class Foo {
     private final String param1;
     private final String param2;

     private Foo(Builder builder) {
       this.param1 = builder.param1;
       this.param2 = builder.param2;
     }
     public static class Builder {
       private String param1 = "defaultForParam1";
       private String param2 = "defaultForParam2";

       public Builder param1(String param1) {
         this.param1 = param1;
         return this;
       }
       public Builder param2(String param1) {
         this.param2 = param2;
         return this;
       }
       public Foo build() {
         return new Foo(this);
       }
     }
   }

which allows you to say:

Foo myFoo = new Foo.Builder().param1("myvalue").build();

which will have a default value for param2.

How to get a list of images on docker registry v2

Install registry:2.1.1 or later (you can check the last one, here) and use GET /v2/_catalog to get list.

https://github.com/docker/distribution/blob/master/docs/spec/api.md#listing-repositories

Lista all images by Shell script example: https://gist.github.com/OndrejP/a2386d08e5308b0776c0

Add a tooltip to a div

You can create custom CSS tooltips using a data attribute, pseudo elements and content: attr() eg.

http://jsfiddle.net/clintioo/gLeydk0k/11/

<div data-tooltip="This is my tooltip">
    <label>Name</label>
    <input type="text" />
</div>

.

div:hover:before {
    content: attr(data-tooltip);
    position: absolute;
    padding: 5px 10px;
    margin: -3px 0 0 180px;
    background: orange;
    color: white;
    border-radius: 3px;
}

div:hover:after {
    content: '';
    position: absolute;
    margin: 6px 0 0 3px;
    width: 0;
    height: 0;
    border-top: 5px solid transparent;
    border-right: 10px solid orange;
    border-bottom: 5px solid transparent;
}

input[type="text"] {
    width: 125px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

How to automatically generate getters and setters in Android Studio

Another funny way

Type the parameter name anywhere in the object after definition, you will see setter and getter, Just select and click enter :)

I tried with Android Studio 2.3

No generated R.java file in my project

Go to Project and hit Clean. This should, among others, regenerate your R.java file.

Also get rid of any import android.R.* statements and then do the clean up I mentioned.

Apparently Jonas problem was related to incorrect target build settings. His target build was set to Android 2.1 (SDK v7) where his layout XML used Android 2.2 (SDK v8) elements (layout parameter match_parent), due to this there was no way for Eclipse to correctly generate the R.java file which caused all the problems.

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

I guess, a column value in a foreign key table should match with the column value of the primary key table. If we are trying to create a foreign key constraint between two tables where the value inside one column(going to be the foreign key) is different from the column value of the primary key table then it will throw the message.

So it is always recommended to insert only those values in the Foreign key column which are present in the Primary key table column.

For ex. If the Primary table column has values 1, 2, 3 and in Foreign key column the values inserted are different, then the query would not be executed as it expects the values to be between 1 & 3.

OperationalError, no such column. Django

just remember there is a pycache folder hidden inside the migrations folder so if you change your models and delete all your migration files you MUST delete the pycache folder also.

The only one you should not delete is your init file.

Hope this helps

Heap vs Binary Search Tree (BST)

As mentioned by others, Heap can do findMin or findMax in O(1) but not both in the same data structure. However I disagree that Heap is better in findMin/findMax. In fact, with a slight modification, the BST can do both findMin and findMax in O(1).

In this modified BST, you keep track of the the min node and max node everytime you do an operation that can potentially modify the data structure. For example in insert operation you can check if the min value is larger than the newly inserted value, then assign the min value to the newly added node. The same technique can be applied on the max value. Hence, this BST contain these information which you can retrieve them in O(1). (same as binary heap)

In this BST (Balanced BST), when you pop min or pop max, the next min value to be assigned is the successor of the min node, whereas the next max value to be assigned is the predecessor of the max node. Thus it perform in O(1). However we need to re-balance the tree, thus it will still run O(log n). (same as binary heap)

I would be interested to hear your thought in the comment below. Thanks :)

Update

Cross reference to similar question Can we use binary search tree to simulate heap operation? for more discussion on simulating Heap using BST.

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

Jquery click event not working after append method

The .on() method is used to delegate events to elements, dynamically added or already present in the DOM:

_x000D_
_x000D_
// STATIC-PARENT              on  EVENT    DYNAMIC-CHILD_x000D_
$('#registered_participants').on('click', '.new_participant_form', function() {_x000D_
_x000D_
  var $td = $(this).closest('tr').find('td');_x000D_
  var part_name = $td.eq(1).text();_x000D_
  console.log( part_name );_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
$('#add_new_participant').click(function() {_x000D_
_x000D_
  var first_name = $.trim( $('#f_name_participant').val() );_x000D_
  var last_name  = $.trim( $('#l_name_participant').val() );_x000D_
  var role       = $('#new_participant_role').val();_x000D_
  var email      = $('#email_participant').val();_x000D_
  _x000D_
  if(!first_name && !last_name) return;_x000D_
_x000D_
  $('#registered_participants').append('<tr><td><a href="#" class="new_participant_form">Participant Registration</a></td><td>' + first_name + ' ' + last_name + '</td><td>' + role + '</td><td>0% done</td></tr>');_x000D_
_x000D_
});
_x000D_
<table id="registered_participants" class="tablesorter">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Form</th>_x000D_
      <th>Name</th>_x000D_
      <th>Role</th>_x000D_
      <th>Progress </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td><a href="#" class="new_participant_form">Participant Registration</a></td>_x000D_
      <td>Smith Johnson</td>_x000D_
      <td>Parent</td>_x000D_
      <td>60% done</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<input type="text" id="f_name_participant" placeholder="Name">_x000D_
<input type="text" id="l_name_participant" placeholder="Surname">_x000D_
<select id="new_participant_role">_x000D_
  <option>Parent</option>_x000D_
  <option>Child</option>_x000D_
</select>_x000D_
<button id="add_new_participant">Add New Entry</button>_x000D_
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Read more: http://api.jquery.com/on/

What's the difference between @Component, @Repository & @Service annotations in Spring?

They are almost the same - all of them mean that the class is a Spring bean. @Service, @Repository and @Controller are specialized @Components. You can choose to perform specific actions with them. For example:

  • @Controller beans are used by spring-mvc
  • @Repository beans are eligible for persistence exception translation

Another thing is that you designate the components semantically to different layers.

One thing that @Component offers is that you can annotate other annotations with it, and then use them the same way as @Service.

For example recently I made:

@Component
@Scope("prototype")
public @interface ScheduledJob {..}

So all classes annotated with @ScheduledJob are spring beans and in addition to that are registered as quartz jobs. You just have to provide code that handles the specific annotation.

How to drop all stored procedures at once in SQL Server database?

ANSI compliant, without cursor

DECLARE @SQL national character varying(MAX) 
SET @SQL= ''

SELECT @SQL= @SQL+ N'DROP PROCEDURE "' + REPLACE(SPECIFIC_SCHEMA, N'"', N'""') + N'"."' + REPLACE(SPECIFIC_NAME, N'"', N'""') + N'"; '
FROM INFORMATION_SCHEMA.ROUTINES 

WHERE (1=1) 
AND ROUTINE_TYPE = 'PROCEDURE' 
AND ROUTINE_NAME NOT IN 
(
     'dt_adduserobject'
    ,'dt_droppropertiesbyid'
    ,'dt_dropuserobjectbyid'
    ,'dt_generateansiname'
    ,'dt_getobjwithprop'
    ,'dt_getobjwithprop_u'
    ,'dt_getpropertiesbyid'
    ,'dt_getpropertiesbyid_u'
    ,'dt_setpropertybyid'
    ,'dt_setpropertybyid_u'
    ,'dt_verstamp006'
    ,'dt_verstamp007'

    ,'sp_helpdiagrams'
    ,'sp_creatediagram'
    ,'sp_alterdiagram'
    ,'sp_renamediagram'
    ,'sp_dropdiagram'

    ,'sp_helpdiagramdefinition'
    ,'fn_diagramobjects'
    ,'sp_upgraddiagrams'
) 


ORDER BY SPECIFIC_NAME 


-- PRINT @SQL
EXEC(@SQL) 

Without cursor, non-ansi compliant:

DECLARE @sql NVARCHAR(MAX) = N''
, @lineFeed NVARCHAR(2) = CHAR(13) + CHAR(10) ;

SELECT @sql = @sql + N'DROP PROCEDURE ' + QUOTENAME(SPECIFIC_SCHEMA) + N'.' + QUOTENAME(SPECIFIC_NAME) + N';' + @lineFeed
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_TYPE = 'PROCEDURE' 
-- AND SPECIFIC_NAME LIKE 'sp[_]RPT[_]%'


AND ROUTINE_NAME NOT IN 
( 
    SELECT name FROM sys.procedures WHERE is_ms_shipped <> 0 
) 


ORDER BY SPECIFIC_NAME 


-- PRINT @sql 
EXECUTE(@sql)

append new row to old csv file python

# I like using the codecs opening in a with 
field_names = ['latitude', 'longitude', 'date', 'user', 'text']
with codecs.open(filename,"ab", encoding='utf-8') as logfile:
    logger = csv.DictWriter(logfile, fieldnames=field_names)
    logger.writeheader()

# some more code stuff 

    for video in aList:
        video_result = {}                                     
        video_result['date'] = video['snippet']['publishedAt']
        video_result['user'] = video['id']
        video_result['text'] = video['snippet']['description'].encode('utf8')
        logger.writerow(video_result) 

What are OLTP and OLAP. What is the difference between them?

The difference is quite simple:

OLTP (Online Transaction Processing)

OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.

OLAP (Online Analytical Processing)

OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.

See more details OLTP and OLAP

Can't build create-react-app project with custom PUBLIC_URL

If the other answers aren't working for you, there's also a homepage field in package.json. After running npm run build you should get a message like the following:

The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:

  "homepage" : "http://myname.github.io/myapp",

You would just add it as one of the root fields in package.json, e.g.

{
  // ...
  "scripts": {
    // ...
  },
  "homepage": "https://example.com"
}

When it's successfully set, either via homepage or PUBLIC_URL, you should instead get a message like this:

The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.

How to run a function in jquery

You can also do this - Since you want one function to be used everywhere, you can do so by directly calling JqueryObject.function(). For example if you want to create your own function to manipulate any CSS on an element:

jQuery.fn.doSomething = function () {
   this.css("position","absolute");
   return this;
}

And the way to call it:

$("#someRandomDiv").doSomething();

How do I turn a python datetime into a string, with readable format date?

Python datetime object has a method attribute, which prints in readable format.

>>> a = datetime.now()
>>> a.ctime()
'Mon May 21 18:35:18 2018'
>>> 

How to detect a mobile device with JavaScript?

Since it's now 2015, if you stumbled across this question then you should probably be using window.matchMedia (and, if it's still 2015, polyfilling for older browsers):

if (matchMedia('handheld').matches) {
    //...
} else {
    //...
}

How to change status bar color to match app in Lollipop? [Android]

To change status bar color use setStatusBarColor(int color). According the javadoc, we also need set some flags on the window.

Working snippet of code:

Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(ContextCompat.getColor(activity, R.color.example_color));


Keep in mind according Material Design guidelines status bar color and action bar color should be different:

  • ActionBar should use primary 500 color
  • StatusBar should use primary 700 color

Look at the screenshot below:

enter image description here

“tag already exists in the remote" error after recreating the git tag

Edit, 24 Nov 2016: this answer is apparently popular, so I am adding a note here. If you replace a tag on a central server, anyone who has the old tag—any clone of that central-server repository that already has the tag—could retain its old tag. So while this tells you how to do it, be really sure you want to do it. You'll need to get everyone who already has the "wrong" tag to delete their "wrong tag" and replace it with the new "right tag".

Testing in Git 2.10/2.11 shows that retaining the old tag is the default behavior for clients running git fetch, and updating is the default behavior for clients running git fetch --tags.

(Original answer follows.)


When you ask to push tags, git push --tags sends (along with any commits and other objects needed and any other ref updates from the push settings) to the remote an update request of the form new-sha1 refs/tags/name. (Well, it sends however many: one of those for each tag.)

The update request is modified by the remote to add an old-sha1 (or again, one for each tag), then delivered to the pre-receive and/or update hooks (whichever hooks exist on the remote). Those hooks can decide whether to allow or reject the tag create/delete/update.

The old-sha1 value is the all-zeros "null" SHA-1 if the tag is being created. The new-sha1 is the null SHA-1 if the tag is being deleted. Otherwise both SHA-1 values are real, valid values.

Even with no hooks, there's a sort of "built-in hook" that is also run: the remote will refuse to move a tag unless you use the "force" flag (though the "built-in hook" is always OK with both "add" and "delete"). The rejection message you're seeing is coming from this built-in hook. (Incidentally, this same built-in hook also rejects branch updates that are not fast-forwards.)1

But—here's one of the keys to understanding what's going on—the git push step has no idea whether the remote has that tag now, and if so, what SHA-1 value it has. It only says "here's my complete list of tags, along with their SHA-1 values". The remote compares the values and if there are additions and/or changes, runs the hooks on those. (For tags that are the same, it does nothing at all. For tags you don't have that they do, it also does nothing!)

If you delete the tag locally, then push, your push simply does not transfer the tag. The remote assumes no change should be made.

If you delete the tag locally, then create it pointing to a new place, then push, your push transfers the tag, and the remote sees this as a tag-change and rejects the change, unless it's a force-push.

Thus, you have two options:

  • do a force-push, or
  • delete the tag on the remote.

The latter is possible via git push2 even though deleting the tag locally and pushing has no effect. Assuming the name of the remote is origin, and the tag you want it to delete is dev:

git push origin :refs/tags/dev

This asks the remote to delete the tag. The presence or absence of the tag dev in your local repository is irrelevant; this kind of push, with :remoteref as a refspec, is a pure-delete push.

The remote may or may not allow tag deletion (depending on any extra hooks added). If it allows the deletion, then the tag will be gone, and a second git push --tags, when you have a local dev tag pointing to some commit or annotated tag repo object, send your new dev tag. On the remote, dev will now be a newly created tag, so the remote will probably allow the push (again this depends on any extra hooks added).

The force-push is simpler. If you want to be sure not to update anything other than the tag, just tell git push to push only that one refspec:

git push --force origin refs/tags/dev:refs/tags/dev

(note: you don't need --tags if you're explicitly pushing just one tag ref-spec).


1Of course, the reason for this built-in hook is to help enforce the behavior that other users of that same remote-repo expect: that branches are not rewound, and tags do not move. If you force-push, you should let the other users know you are doing this, so that they can correct for it. Note that "tags don't move at all" is newly enforced by Git 1.8.2; previous versions would allow the tag to "move forward" in the commit graph, much like branch names. See the git 1.8.2 release notes.

2It's trivial if you can log in on the remote. Just go to the Git repository there and run git tag -d dev. Note that either way—deleting the tag on the remote, or using git push to delete it—there's a period of time when anyone who accesses the remote will find that the dev tag is missing. (They will continue to have their own old tag, if they already have it, and they might even push their old tag back up before you can push the new one.)

How to delete a folder and all contents using a bat file in windows?

@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"

Explanation:

Removes (deletes) a directory.

RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path

/S      Removes all directories and files in the specified directory
        in addition to the directory itself.  Used to remove a directory
        tree.

/Q      Quiet mode, do not ask if ok to remove a directory tree with /S

What is the hamburger menu icon called and the three vertical dots icon called?

Look at this photo, it says "Kebab Menu" is a correct answer:

enter image description here

per comment below, sourced from Luke Wroblewski: https://twitter.com/lukew/status/591296890030915585/photo/1

How to enable curl in xampp?

For XAMPP on MACOS or Linux, remove the semicolon in php.ini file after extension=curl.so

Difference between checkout and export in SVN

if you are using tortoise svn client - while exporting - it displays ..export / checkout , it is confusing , it is just export only. only view/read use export , to commit use - "checkout"

How can I align all elements to the left in JPanel?

You should use setAlignmentX(..) on components you want to align, not on the container that has them..

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(c1);
panel.add(c2);

c1.setAlignmentX(Component.LEFT_ALIGNMENT);
c2.setAlignmentX(Component.LEFT_ALIGNMENT);

is there a require for json in node.js

Two of the most common

First way :

let jsonData = require('./JsonFile.json')

let jsonData = require('./JsonFile') // if we omitting .json also works

OR

import jsonData from ('./JsonFile.json')

Second way :

1) synchronously

const fs = require('fs')
let jsonData = JSON.parse(fs.readFileSync('JsonFile.json', 'utf-8'))

2) asynchronously

const fs = require('fs')
let jsonData = {}
fs.readFile('JsonFile.json', 'utf-8', (err, data) => {
  if (err) throw err

  jsonData = JSON.parse(data)
})

Note: 1) if we JsonFile.json is changed, we not get the new data, even if we re run require('./JsonFile.json')

2) The fs.readFile or fs.readFileSync will always re read the file, and get changes

How to use sed to replace only the first occurrence in a file?

The use case can perhaps be that your occurences are spread throughout your file, but you know your only concern is in the first 10, 20 or 100 lines.

Then simply adressing those lines fixes the issue - even if the wording of the OP regards first only.

sed '1,10s/#include/#include "newfile.h"\n#include/'

How to clear https proxy setting of NPM?

By the default value npm is looking for packages from https://registry.npmjs.org. What you also need to do is override the registry and strict-ssl values.

npm config set registry "http://registry.npmjs.org"
npm config set strict-ssl false

How to put labels over geom_bar in R with ggplot2

Another solution is to use stat_count() when dealing with discrete variables (and stat_bin() with continuous ones).

ggplot(data = df, aes(x = x)) +
geom_bar(stat = "count") + 
stat_count(geom = "text", colour = "white", size = 3.5,
aes(label = ..count..),position=position_stack(vjust=0.5))

enter image description here

npm command to uninstall or prune unused packages in Node.js

If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules and npm install again to rebuild the local modules.

How to use awk sort by column 3

awk -F, '{ print $3, $0 }' user.csv | sort -nk2 

and for reverse order

awk -F, '{ print $3, $0 }' user.csv | sort -nrk2 

Re-ordering columns in pandas dataframe based on column name

print df.sort_index(by='Frequency',ascending=False)

where by is the name of the column,if you want to sort the dataset based on column

How to send 500 Internal Server Error error from a PHP script

You can just put:

header("HTTP/1.0 500 Internal Server Error");

inside your conditions like:

if (that happened) {
    header("HTTP/1.0 500 Internal Server Error");
}

As for the database query, you can just do that like this:

$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");

You should remember that you have to put this code before any html tag (or output).