Programs & Examples On #Asianfonts

Visual Studio Code - Convert spaces to tabs

If you want to change tabs to spaces in a lot of files, but don't want to open them individually, I have found that it works equally as well to just use the Find and Replace option from the left-most tools bar.

In the first box (Find), copy and paste a tab from the source code.

In the second box (Replace), enter the number of spaces that you wish to use (i.e. 2 or 4).

If you press the ... button, you can specify directories to include or ignore (i.e. src/Data/Json).

Finally, inspect the result preview and press Replace All. All files in the workspace may be affected.

Five equal columns in twitter bootstrap

Another way to enable 5 columns in Bootstrap 3 is to modify the 12 columns format used by default by Bootstrap. And then create a 20 columns grid (use customize on the Bootstrap website OR use the LESS/SASS version).

To customize on the bootstrap website, go to Customize and Download page, update variable @grid-columns from 12 to 20. Then you will be able to create 4 as well as 5 columns.

How do I automatically update a timestamp in PostgreSQL

Updating timestamp, only if the values changed

Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)

CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
   IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
      NEW.modified = now(); 
      RETURN NEW;
   ELSE
      RETURN OLD;
   END IF;
END;
$$ language 'plpgsql';

How to add a border just on the top side of a UIView

Swift 4.2 and AutoLayout

I went through the offered solutions. Many are based in frames This is a simple extension that works with AutoLayout - use View instead of Layer to make sure we can use AutoLayout - Single subview with 4 constraints

Use as follows:

self.addBorder(.bottom, color: .lightGray, thickness: 0.5)


extension UIView {
    func addBorder(_ edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
        let subview = UIView()
        subview.translatesAutoresizingMaskIntoConstraints = false
        subview.backgroundColor = color
        self.addSubview(subview)
        switch edge {
        case .top, .bottom:
            subview.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
            subview.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
            subview.heightAnchor.constraint(equalToConstant: thickness).isActive = true
            if edge == .top {
                subview.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            } else {
                subview.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            }
        case .left, .right:
            subview.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            subview.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            subview.widthAnchor.constraint(equalToConstant: thickness).isActive = true
            if edge == .left {
                subview.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
            } else {
                subview.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
            }
        default:
            break
        }
    }
}

android.view.InflateException: Binary XML file: Error inflating class fragment

In my case .

The layout i was trying to inflate had

<include 
 layout  = "...."
/>

tag, removing it fixed it.

I was trying to inflate a previous layout designed for a Actvity into the view-pager adapter.

Why does npm install say I have unmet dependencies?

I run npm list and installed all the packages listed as UNMET DEPENDENCY

For instance:

+-- UNMET DEPENDENCY css-loader@^0.23.1
npm install css-loader@^0.23.1

How do I set adaptive multiline UILabel text?

Programmatically in Swift 5 with Xcode 10.2

Building on top of @La masse's solution, but using autolayout to support rotation

Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)

label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
self.view.addSubview(label)
// SET AUTOLAYOUT ANCHORS
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// OPTIONALLY, YOU CAN USE THIS INSTEAD OF THE WIDTH ANCHOR (OR LEFT/RIGHT)
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)
label.text = "YOUR LONG TEXT GOES HERE"
label.sizeToFit()

If setting frame.width dynamically using UIScreen:

extension UIScreen {   // OPTIONAL IF USING A DYNAMIC FRAME WIDTH
    class func absoluteWidth() -> CGFloat {
        var width: CGFloat
        if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
            width = self.main.bounds.height // Landscape
        } else {
            width = self.main.bounds.width // Portrait
        }
        return width
    }
}

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

Why is sed not recognizing \t as a tab?

Use $(echo '\t'). You'll need quotes around the pattern.

Eg. To remove a tab:

sed "s/$(echo '\t')//"

Populating a database in a Laravel migration file

This should do what you want.

public function up()
{
    DB::table('user')->insert(array('username'=>'dude', 'password'=>'z19pers!'));
}

SSL Connection / Connection Reset with IISExpress

In my case, the localhost url was redirected to https://localhost when I was debugging. This happened from one moment to other, without changing anything. I solved this by making a hard reload to the browser. Here the link

Redirect stdout to a file in Python?

There is contextlib.redirect_stdout() function in Python 3.4+:

from contextlib import redirect_stdout

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        print('it now prints to `help.text`')

It is similar to:

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout(new_target):
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value

that can be used on earlier Python versions. The latter version is not reusable. It can be made one if desired.

It doesn't redirect the stdout at the file descriptors level e.g.:

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, redirect_stdout(f):
    print('redirected to a file')
    os.write(stdout_fd, b'not redirected')
    os.system('echo this also is not redirected')

b'not redirected' and 'echo this also is not redirected' are not redirected to the output.txt file.

To redirect at the file descriptor level, os.dup2() could be used:

import os
import sys
from contextlib import contextmanager

def fileno(file_or_fd):
    fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
    return fd

@contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
    if stdout is None:
       stdout = sys.stdout

    stdout_fd = fileno(stdout)
    # copy stdout_fd before it is overwritten
    #NOTE: `copied` is inheritable on Windows when duplicating a standard stream
    with os.fdopen(os.dup(stdout_fd), 'wb') as copied: 
        stdout.flush()  # flush library buffers that dup2 knows nothing about
        try:
            os.dup2(fileno(to), stdout_fd)  # $ exec >&to
        except ValueError:  # filename
            with open(to, 'wb') as to_file:
                os.dup2(to_file.fileno(), stdout_fd)  # $ exec > to
        try:
            yield stdout # allow code to be run with the redirected stdout
        finally:
            # restore stdout to its previous value
            #NOTE: dup2 makes stdout_fd inheritable unconditionally
            stdout.flush()
            os.dup2(copied.fileno(), stdout_fd)  # $ exec >&copied

The same example works now if stdout_redirected() is used instead of redirect_stdout():

import os
import sys

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, stdout_redirected(f):
    print('redirected to a file')
    os.write(stdout_fd, b'it is redirected now\n')
    os.system('echo this is also redirected')
print('this is goes back to stdout')

The output that previously was printed on stdout now goes to output.txt as long as stdout_redirected() context manager is active.

Note: stdout.flush() does not flush C stdio buffers on Python 3 where I/O is implemented directly on read()/write() system calls. To flush all open C stdio output streams, you could call libc.fflush(None) explicitly if some C extension uses stdio-based I/O:

try:
    import ctypes
    from ctypes.util import find_library
except ImportError:
    libc = None
else:
    try:
        libc = ctypes.cdll.msvcrt # Windows
    except OSError:
        libc = ctypes.cdll.LoadLibrary(find_library('c'))

def flush(stream):
    try:
        libc.fflush(None)
        stream.flush()
    except (AttributeError, ValueError, IOError):
        pass # unsupported

You could use stdout parameter to redirect other streams, not only sys.stdout e.g., to merge sys.stderr and sys.stdout:

def merged_stderr_stdout():  # $ exec 2>&1
    return stdout_redirected(to=sys.stdout, stdout=sys.stderr)

Example:

from __future__ import print_function
import sys

with merged_stderr_stdout():
     print('this is printed on stdout')
     print('this is also printed on stdout', file=sys.stderr)

Note: stdout_redirected() mixes buffered I/O (sys.stdout usually) and unbuffered I/O (operations on file descriptors directly). Beware, there could be buffering issues.

To answer, your edit: you could use python-daemon to daemonize your script and use logging module (as @erikb85 suggested) instead of print statements and merely redirecting stdout for your long-running Python script that you run using nohup now.

Alter table add multiple columns ms sql

this should work in T-SQL

ALTER TABLE Countries  ADD
HasPhotoInReadyStorage  bit,  
HasPhotoInWorkStorage  bit,  
HasPhotoInMaterialStorage bit,  
HasText  bit GO

http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx

How to flush output after each `echo` call?

Flushing seemingly failing to work is a side effect of automatic character set detection.

The browser will not display anything until it knows the character set to display it in, and if you don't specify the character set, it need tries to guess it. The problem being that it can't make a good guess without enough data, which is why browsers seem to have this 1024 byte (or similar) buffer they need filled before displaying anything.

The solution is therefore to make sure the browser doesn't have to guess the character set.

If you're sending text, add a '; charset=utf-8' to its content type, and if it's HTML, add the character set to the appropriate meta tag.

finding multiples of a number in Python

For the first ten multiples of 5, say

>>> [5*n for n in range(1,10+1)]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

Pandas every nth row

A solution I came up with when using the index was not viable ( possibly the multi-Gig .csv was too large, or I missed some technique that would allow me to reindex without crashing ).
Walk through one row at a time and add the nth row to a new dataframe.

import pandas as pd
from csv import DictReader

def make_downsampled_df(filename, interval):    
    with open(filename, 'r') as read_obj:
        csv_dict_reader = DictReader(read_obj)
        column_names = csv_dict_reader.fieldnames
        df = pd.DataFrame(columns=column_names)
    
        for index, row in enumerate(csv_dict_reader):
            if index % interval == 0:
               print(str(row))
               df = df.append(row, ignore_index=True)

    return df

Use of exit() function

Write header file #include<process.h> and replace exit(); with exit(0);. This will definitely work in Turbo C; for other compilers I don't know.

Detect if device is iOS

Detecting iOS

With iOS 13 iPad both User agent and platform strings are changed and differentiating between iPad and MacOS seems possible, so all answers below needs to take that into account now.

This might be the shortest alternative that also covers iOS 13:

function iOS() {
  return [
    'iPad Simulator',
    'iPhone Simulator',
    'iPod Simulator',
    'iPad',
    'iPhone',
    'iPod'
  ].includes(navigator.platform)
  // iPad on iOS 13 detection
  || (navigator.userAgent.includes("Mac") && "ontouchend" in document)
}

iOS will be either true or false

Worse option: User agent sniffing

User Agent sniffing is more dangerous and problems appear often.

On iPad iOS 13, the user agent is identical with that of a MacOS 13 computer, but if you ignore iPads this might work still for a while:

var iOS = !window.MSStream && /iPad|iPhone|iPod/.test(navigator.userAgent); // fails on iPad iOS 13

The !window.MSStream is to not incorrectly detect IE11, see here and here.

Note: Both navigator.userAgent and navigator.platform can be faked by the user or a browser extension.

Browser extensions to change userAgent or platform exist because websites use too heavy-handed detection and often disable some features even if the user's browser would otherwise be able to use that feature.

To de-escalate this conflict with users it's recommended to detect specifically for each case the exact features that your website needs. Then when the user gets a browser with the needed feature it will already work without additional code changes.

Detecting iOS version

The most common way of detecting the iOS version is by parsing it from the User Agent string. But there is also feature detection inference*;

We know for a fact that history API was introduced in iOS4 - matchMedia API in iOS5 - webAudio API in iOS6 - WebSpeech API in iOS7 and so on.

Note: The following code is not reliable and will break if any of these HTML5 features is deprecated in a newer iOS version. You have been warned!

function iOSversion() {

  if (iOS) { // <-- Use the one here above
    if (window.indexedDB) { return 'iOS 8 and up'; }
    if (window.SpeechSynthesisUtterance) { return 'iOS 7'; }
    if (window.webkitAudioContext) { return 'iOS 6'; }
    if (window.matchMedia) { return 'iOS 5'; }
    if (window.history && 'pushState' in window.history) { return 'iOS 4'; }
    return 'iOS 3 or earlier';
  }

  return 'Not an iOS device';
}

What is the difference between json.load() and json.loads() functions

QUICK ANSWER (very simplified!)

json.load() takes a FILE

json.load() expects a file (file object) - e.g. a file you opened before given by filepath like 'files/example.json'.


json.loads() takes a STRING

json.loads() expects a (valid) JSON string - i.e. {"foo": "bar"}


EXAMPLES

Assuming you have a file example.json with this content: { "key_1": 1, "key_2": "foo", "Key_3": null }

>>> import json
>>> file = open("example.json")

>>> type(file)
<class '_io.TextIOWrapper'>

>>> file
<_io.TextIOWrapper name='example.json' mode='r' encoding='UTF-8'>

>>> json.load(file)
{'key_1': 1, 'key_2': 'foo', 'Key_3': None}

>>> json.loads(file)
Traceback (most recent call last):
  File "/usr/local/python/Versions/3.7/lib/python3.7/json/__init__.py", line 341, in loads
TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper


>>> string = '{"foo": "bar"}'

>>> type(string)
<class 'str'>

>>> string
'{"foo": "bar"}'

>>> json.loads(string)
{'foo': 'bar'}

>>> json.load(string)
Traceback (most recent call last):
  File "/usr/local/python/Versions/3.7/lib/python3.7/json/__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

Git says local branch is behind remote branch, but it's not

You probably did some history rewriting? Your local branch diverged from the one on the server. Run this command to get a better understanding of what happened:

gitk HEAD @{u}

I would strongly recommend you try to understand where this error is coming from. To fix it, simply run:

git push -f

The -f makes this a “forced push” and overwrites the branch on the server. That is very dangerous when you are working in team. But since you are on your own and sure that your local state is correct this should be fine. You risk losing commit history if that is not the case.

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

How do I create an empty array/matrix in NumPy?

I think you can create empty numpy array like:

>>> import numpy as np
>>> empty_array= np.zeros(0)
>>> empty_array
array([], dtype=float64)
>>> empty_array.shape
(0,)

This format is useful when you want to append numpy array in the loop.

Adding local .aar files to Gradle build using "flatDirs" is not working

In my case, I just put the aar file in libs, and add

dependencies { ... api fileTree(dir: 'libs', include: ['*.aar']) ... }

in build.gradle and it works. I think it is similar with default generated dependency:

implementation fileTree(dir: 'libs', include: ['*.jar'])

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

As you can see here:

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Difference between @GetMapping & @RequestMapping

@GetMapping supports the consumes attribute like @RequestMapping.

Open Source Javascript PDF viewer

There are some guys at Mozilla working on implementing a PDF reader using HTML5 and JavaScript. It is called pdf.js and one of the developers just made an interesting blog post about the project.

Creating Accordion Table with Bootstrap

In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:

.collapse-row.collapsed + tr {
     display: none;
}

'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.

Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

Here is another way that gives you access to the key and the value at the same time, in case you have to do some kind of transformation.

Map<String, Integer> pointsByName = new HashMap<>();
Map<String, Integer> maxPointsByName = new HashMap<>();

Map<String, Double> gradesByName = pointsByName.entrySet().stream()
        .map(entry -> new AbstractMap.SimpleImmutableEntry<>(
                entry.getKey(), ((double) entry.getValue() /
                        maxPointsByName.get(entry.getKey())) * 100d))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

C# switch statement limitations - why?

This is my original post, which sparked some debate... because it is wrong:

The switch statement is not the same thing as a big if-else statement. Each case must be unique and evaluated statically. The switch statement does a constant time branch regardless of how many cases you have. The if-else statement evaluates each condition until it finds one that is true.


In fact, the C# switch statement is not always a constant time branch.

In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by Ivan Hamilton the compiler may generate something else entirely.

This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool.

How can I increase the size of a bootstrap button?

Default Bootstrap size classes

You can use btn-lg, btn-sm and btn-xs classes for manipulating with its size.

btn-block

Also, there is a class btn-block which will extend your button to the whole block. It is very convenient in combination with Bootstrap grid.
For example, this code will show a button with the width equal to half of screen for medium and large screens; and will show a full-width button for small screens:

<div class="container">
    <div class="col-xs-12 col-xs-offset-0 col-sm-offset-3 col-sm-6">
        <button class="btn btn-group">Click me!</button>
    </div>
</div>

Check this JSFiddle out. Try to resize frame.

If it is not enough, you can easily create your custom class.

curl posting with header application/x-www-form-urlencoded

Try something like:

$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));   
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$result = curl_exec($ch);

echo $result;

Efficiently finding the last line in a text file

with open('output.txt', 'r') as f:
    lines = f.read().splitlines()
    last_line = lines[-1]
    print last_line

Get unique values from a list in python

If we need to keep the elements order, how about this:

used = set()
mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
unique = [x for x in mylist if x not in used and (used.add(x) or True)]

And one more solution using reduce and without the temporary used var.

mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
unique = reduce(lambda l, x: l.append(x) or l if x not in l else l, mylist, [])

UPDATE - Dec, 2020 - Maybe the best approach!

Starting from python 3.7, the standard dict preserves insertion order.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

So this gives us the ability to use dict.from_keys for de-duplication!

NOTE: Credits goes to @rlat for giving us this approach in the comments!

mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
unique = list(dict.fromkeys(mylist))

In terms of speed - for me its fast enough and readable enough to become my new favorite approach!

UPDATE - March, 2019

And a 3rd solution, which is a neat one, but kind of slow since .index is O(n).

mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
unique = [x for i, x in enumerate(mylist) if i == mylist.index(x)]

UPDATE - Oct, 2016

Another solution with reduce, but this time without .append which makes it more human readable and easier to understand.

mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
unique = reduce(lambda l, x: l+[x] if x not in l else l, mylist, [])
#which can also be writed as:
unique = reduce(lambda l, x: l if x in l else l+[x], mylist, [])

NOTE: Have in mind that more human-readable we get, more unperformant the script is. Except only for the dict.from_keys approach which is python 3.7+ specific.

import timeit

setup = "mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']"

#10x to Michael for pointing out that we can get faster with set()
timeit.timeit('[x for x in mylist if x not in used and (used.add(x) or True)]', setup='used = set();'+setup)
0.2029558869980974

timeit.timeit('[x for x in mylist if x not in used and (used.append(x) or True)]', setup='used = [];'+setup)
0.28999493700030143

# 10x to rlat for suggesting this approach!   
timeit.timeit('list(dict.fromkeys(mylist))', setup=setup)
0.31227896199925453

timeit.timeit('reduce(lambda l, x: l.append(x) or l if x not in l else l, mylist, [])', setup='from functools import reduce;'+setup)
0.7149233570016804

timeit.timeit('reduce(lambda l, x: l+[x] if x not in l else l, mylist, [])', setup='from functools import reduce;'+setup)
0.7379565160008497

timeit.timeit('reduce(lambda l, x: l if x in l else l+[x], mylist, [])', setup='from functools import reduce;'+setup)
0.7400134069976048

timeit.timeit('[x for i, x in enumerate(mylist) if i == mylist.index(x)]', setup=setup)
0.9154880290006986

ANSWERING COMMENTS

Because @monica asked a good question about "how is this working?". For everyone having problems figuring it out. I will try to give a more deep explanation about how this works and what sorcery is happening here ;)

So she first asked:

I try to understand why unique = [used.append(x) for x in mylist if x not in used] is not working.

Well it's actually working

>>> used = []
>>> mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
>>> unique = [used.append(x) for x in mylist if x not in used]
>>> print used
[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']
>>> print unique
[None, None, None, None, None]

The problem is that we are just not getting the desired results inside the unique variable, but only inside the used variable. This is because during the list comprehension .append modifies the used variable and returns None.

So in order to get the results into the unique variable, and still use the same logic with .append(x) if x not in used, we need to move this .append call on the right side of the list comprehension and just return x on the left side.

But if we are too naive and just go with:

>>> unique = [x for x in mylist if x not in used and used.append(x)]
>>> print unique
[]

We will get nothing in return.

Again, this is because the .append method returns None, and it this gives on our logical expression the following look:

x not in used and None

This will basically always:

  1. evaluates to False when x is in used,
  2. evaluates to None when x is not in used.

And in both cases (False/None), this will be treated as falsy value and we will get an empty list as a result.

But why this evaluates to None when x is not in used? Someone may ask.

Well it's because this is how Python's short-circuit operators works.

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

So when x is not in used (i.e. when its True) the next part or the expression will be evaluated (used.append(x)) and its value (None) will be returned.

But that's what we want in order to get the unique elements from a list with duplicates, we want to .append them into a new list only when we they came across for a fist time.

So we really want to evaluate used.append(x) only when x is not in used, maybe if there is a way to turn this None value into a truthy one we will be fine, right?

Well, yes and here is where the 2nd type of short-circuit operators come to play.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

We know that .append(x) will always be falsy, so if we just add one or next to him, we will always get the next part. That's why we write:

x not in used and (used.append(x) or True)

so we can evaluate used.append(x) and get True as a result, only when the first part of the expression (x not in used) is True.

Similar fashion can be seen in the 2nd approach with the reduce method.

(l.append(x) or l) if x not in l else l
#similar as the above, but maybe more readable
#we return l unchanged when x is in l
#we append x to l and return l when x is not in l
l if x in l else (l.append(x) or l)

where we:

  1. Append x to l and return that l when x is not in l. Thanks to the or statement .append is evaluated and l is returned after that.
  2. Return l untouched when x is in l

How can I subset rows in a data frame in R based on a vector of values?

Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:

# Set seed for reproducibility.
set.seed(1)

# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))

# compare data frames by specific columns and keep only 
# the rows with equal values 
data_A[data_A$id %in% data_B$id,]   # will keep data in data_A
data_B[data_B$id %in% data_A$id,]   # will keep data in data_b

Results:

> data_A[data_A$id %in% data_B$id,]
  id value
1  1     1
2  2     2
3  3     3

> data_B[data_B$id %in% data_A$id,]
  id value
1  1     5
2  2     6
3  3     7

How to generate List<String> from SQL query?

Loop through the Items and Add to the Collection. You can use the Add method

List<string>items=new List<string>();
using (var con= new SqlConnection("yourConnectionStringHere")
{
    string qry="SELECT Column1 FROM Table1";
    var cmd= new SqlCommand(qry, con);
    cmd.CommandType = CommandType.Text;
    con.Open();
    using (SqlDataReader objReader = cmd.ExecuteReader())
    {
        if (objReader.HasRows)
        {              
            while (objReader.Read())
            {
              //I would also check for DB.Null here before reading the value.
               string item= objReader.GetString(objReader.GetOrdinal("Column1"));
               items.Add(item);                  
            }
        }
    }
}

Android studio Gradle build speed up

This is what I did and my gradle build speed improved dramatically! from 1 min to 20sec for the first build and succeeding builds became from 40 sec to 5 sec.

In the gradle.properties file Add this:

org.gradle.jvmargs=-Xmx8192M -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

In the Command Line Arguments via Go to File > Other Settings> default Settings >Build, Execution, Deploy> Complier and add the following arguments to Command Line Arguments

Add this:

--debug --stacktrace -a, --no-rebuild -q, --quiet --offline

See image here

How to use Lambda in LINQ select statement

Lambda Expression result

var storesList = context.Stores.Select(x => new { Value= x.name,Text= x.ID }).ToList();

Refresh (reload) a page once using jQuery?

Use:

<html>
    <head>
        <title>Reload (Refresh) Page Using Jquery</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#reload').click(function() {
                    window.location.reload();
                });
            });
        </script>
    </head>
    <body>
        <button id="reload" >Reload (Refresh) Page Using</button>
    </body>
</html>

How to calculate percentage when old value is ZERO

It should be (new minus old)/mod avg of old and new With a special case when both val are zeros

Build Error - missing required architecture i386 in file

Run the file command on the framework from Terminal:

file /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.sdk/System/Library /Frameworks/UIKit.framework/UIKit

You should get back a message telling you which architectures the UIKit binary is compatible with. If you don't see "i386" listed, then you've somehow managed to remove the i386 version of UIKit, which will mean that you can't build for the simulator.To fix that, you'll have to re-install the SDK.

If you get some other error, hopefully it'll help you figure out what the actual problem is.

How to verify if $_GET exists?

You can use isset function:

if(isset($_GET['id'])) {
    // id index exists
}

You can create a handy function to return default value if index doesn't exist:

function Get($index, $defaultValue) {
    return isset($_GET[$index]) ? $_GET[$index] : $defaultValue;
}

// prints "invalid id" if $_GET['id'] is not set
echo Get('id', 'invalid id');

You can also try to validate it at the same time:

function GetInt($index, $defaultValue) {
    return isset($_GET[$index]) && ctype_digit($_GET[$index])
            ? (int)$_GET[$index] 
            : $defaultValue;
}

// prints 0 if $_GET['id'] is not set or is not numeric
echo GetInt('id', 0);

Disable asp.net button after click to prevent double clicking

Here is a solution that works for the asp.net button object. On the front end, add these attributes to your asp:Button definition:

<asp:Button ... OnClientClick="this.disabled=true;" UseSubmitBehavior="false" />

In the back end, in the click event handler method call, add this code to the end (preferably in a finally block)

myButton.Enabled = true;

Special characters like @ and & in cURL POST data

Try this:

export CURLNAME="john:@31&3*J"
curl -d -u "${CURLNAME}" https://www.example.com

$lookup on ObjectId's in an array

Aggregating with $lookup and subsequent $group is pretty cumbersome, so if (and that's a medium if) you're using node & Mongoose or a supporting library with some hints in the schema, you could use a .populate() to fetch those documents:

var mongoose = require("mongoose"),
    Schema = mongoose.Schema;

var productSchema = Schema({ ... });

var orderSchema = Schema({
  _id     : Number,
  products: [ { type: Schema.Types.ObjectId, ref: "Product" } ]
});

var Product = mongoose.model("Product", productSchema);
var Order   = mongoose.model("Order", orderSchema);

...

Order
    .find(...)
    .populate("products")
    ...

Django download a file

I've found Django's FileField to be really helpful for letting users upload and download files. The Django documentation has a section on managing files. You can store some information about the file in a table, along with a FileField that points to the file itself. Then you can list the available files by searching the table.

How to SELECT WHERE NOT EXIST using LINQ?

How about..

var result = (from s in context.Shift join es in employeeshift on s.shiftid equals es.shiftid where es.empid == 57 select s)

Edit: This will give you shifts where there is an associated employeeshift (because of the join). For the "not exists" I'd do what @ArsenMkrt or @hyp suggest

JPA Query selecting only specific columns without using Criteria Query?

Yes, like in plain sql you could specify what kind of properties you want to select:

SELECT i.firstProperty, i.secondProperty FROM ObjectName i WHERE i.id=10

Executing this query will return a list of Object[], where each array contains the selected properties of one object.

Another way is to wrap the selected properties in a custom object and execute it in a TypedQuery:

String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();

Examples can be found in this article.

UPDATE 29.03.2018:

@Krish:

@PatrickLeitermann for me its giving "Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***" exception . how to solve this ?

I guess you’re using JPA in the context of a Spring application, don't you? Some other people had exactly the same problem and their solution was adding the fully qualified name (e. g. com.example.CustomObject) after the SELECT NEW keywords.

Maybe the internal implementation of the Spring data framework only recognizes classes annotated with @Entity or registered in a specific orm file by their simple name, which causes using this workaround.

Datagridview: How to set a cell in editing mode?

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.Handled = true;
            DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.CurrentCell = cell;
            dataGridView1.BeginEdit(true);               
        }
    }

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

ORA-06508: PL/SQL: could not find program unit being called

I suspect you're only reporting the last error in a stack like this:

ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"

If so, that's because your package is stateful:

The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state. If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.

When you recompile the state is lost:

If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.

After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it...

You can't avoid this if your package has state. I think it's fairly rare to really need a package to be stateful though, so you should revisit anything you have declared in the package, but outside a function or procedure, to see if it's really needed at that level. Since you're on 10g though, that includes constants, not just variables and cursors.

But the last paragraph from the quoted documentation means that the next time you reference the package in the same session, you won't get the error and it will work as normal (until you recompile again).

Can I set background image and opacity in the same property?

I had a similar issue and I just took the background image with photoshop and created a new .png with the opacity I needed. Problem solved without worrying about if my CSS worked accross all devices & browsers

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

n-grams in python, four, five, six grams?

For four_grams it is already in NLTK, here is a piece of code that can help you toward this:

 from nltk.collocations import *
 import nltk
 #You should tokenize your text
 text = "I do not like green eggs and ham, I do not like them Sam I am!"
 tokens = nltk.wordpunct_tokenize(text)
 fourgrams=nltk.collocations.QuadgramCollocationFinder.from_words(tokens)
 for fourgram, freq in fourgrams.ngram_fd.items():  
       print fourgram, freq

I hope it helps.

What's the difference between using CGFloat and float?

CGFloat is a regular float on 32-bit systems and a double on 64-bit systems

typedef float CGFloat;// 32-bit
typedef double CGFloat;// 64-bit

So you won't get any performance penalty.

Commenting in a Bash script inside a multiline command

As DigitalRoss pointed out, the trailing backslash is not necessary when the line woud end in |. And you can put comments on a line following a |:

 cat ${MYSQLDUMP} |         # Output MYSQLDUMP file
 sed '1d' |                 # skip the top line
 tr ",;" "\n" | 
 sed -e 's/[asbi]:[0-9]*[:]*//g' -e '/^[{}]/d' -e 's/""//g' -e '/^"{/d' |
 sed -n -e '/^"/p' -e '/^print_value$/,/^option_id$/p' |
 sed -e '/^option_id/d' -e '/^print_value/d' -e 's/^"\(.*\)"$/\1/' |
 tr "\n" "," |
 sed -e 's/,\([0-9]*-[0-9]*-[0-9]*\)/\n\1/g' -e 's/,$//' |   # hate phone numbers
 sed -e 's/^/"/g' -e 's/$/"/g' -e 's/,/","/g' >> ${CSV}

VBA Subscript out of range - error 9

Suggest the following simplification: capture return value from Workbooks.Add instead of subscripting Windows() afterward, as follows:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate


General Philosophy Advice:

Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.

Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

During and within macros do not rely on these built-in names, instead capture return values, e.g.

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

Also, try to use qualified expressions, e.g.

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

or

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

Use qualified expressions, e.g.

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.

Also please note that you'll likely find that you don't need to .Activate nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate could simply be eliminated instead of even being replaced by wkb.Activate.

(Also note: I think the .Select statements you show are not contributing and can be omitted.)

(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)

How to make google spreadsheet refresh itself every 1 minute?

I had a similar problem with crypto updates. A kludgy hack that gets around this is to include a '+ now() - now()' stunt at the end of the cell formula, with the setting as above to recalculate every minute. This worked for my price updates, but, definitely an ugly hack.

How to center a window on the screen in Tkinter?

CENTERING THE WINDOW IN PYTHON Tkinter This is the most easiest thing in tkinter because all we must know is the dimension of the window as well as the dimensions of the computer screen. I come up with the following code which can help someone somehow and i did add some comments so that they can follow up.

code

    #  create a window first
    root = Tk()
    # define window dimensions width and height
    window_width = 800
    window_height = 500
    # get the screen size of your computer [width and height using the root object as foolows]
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    # Get the window position from the top dynamically as well as position from left or right as follows
    position_top = int(screen_height/2 -window_height/2)
    position_right = int(screen_width / 2 - window_width/2)
    # this is the line that will center your window
    root.geometry(f'{window_width}x{window_height}+{position_right}+{position_top}')
    # initialise the window
    root.mainloop(0)

Disable HttpClient logging

In my case I use xml configuration, and I append this to the configuration file

<logger name="org.apache.http">
    <level value="warn"/>
</logger>

How to output to the console and file?

I came up with this [untested]

import sys

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() # If you want the output to be visible immediately
    def flush(self) :
        for f in self.files:
            f.flush()

f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test"  # This will go to stdout and the file out.txt

#use the original
sys.stdout = original
print "This won't appear on file"  # Only on stdout
f.close()

print>>xyz in python will expect a write() function in xyz. You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without >>xyz.

How to specify line breaks in a multi-line flexbox layout?

I tried several answers here, and none of them worked. Ironically, what did work was about the simplest alternative to a <br/> one could attempt:

<div style="flex-basis: 100%;"></div>

or you could also do:

<div style="width: 100%;"></div>

Place that wherever you want a new line. It seems to work even with adjacent <span>'s, but I'm using it with adjacent <div>'s.

How to open mail app from Swift

Swift 2, with availability check:

import MessageUI

if MFMailComposeViewController.canSendMail() {
    let mail = MFMailComposeViewController()
    mail.mailComposeDelegate = self
    mail.setToRecipients(["[email protected]"])
    mail.setSubject("Bla")
    mail.setMessageBody("<b>Blabla</b>", isHTML: true)
    presentViewController(mail, animated: true, completion: nil)
} else {
    print("Cannot send mail")
    // give feedback to the user
}


// MARK: - MFMailComposeViewControllerDelegate

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    switch result.rawValue {
    case MFMailComposeResultCancelled.rawValue:
        print("Cancelled")
    case MFMailComposeResultSaved.rawValue:
        print("Saved")
    case MFMailComposeResultSent.rawValue:
        print("Sent")
    case MFMailComposeResultFailed.rawValue:
        print("Error: \(error?.localizedDescription)")
    default:
        break
    }
    controller.dismissViewControllerAnimated(true, completion: nil)
}

What's the difference between JavaScript and Java?

JavaScript is an object-oriented scripting language that allows you to create dynamic HTML pages, allowing you to process input data and maintain data, usually within the browser.

Java is a programming language, core set of libraries, and virtual machine platform that allows you to create compiled programs that run on nearly every platform, without distribution of source code in its raw form or recompilation.

While the two have similar names, they are really two completely different programming languages/models/platforms, and are used to solve completely different sets of problems.

Also, this is directly from the Wikipedia Javascript article:

A common misconception is that JavaScript is similar or closely related to Java; this is not so. Both have a C-like syntax, are object-oriented, are typically sandboxed and are widely used in client-side Web applications, but the similarities end there. Java has static typing; JavaScript's typing is dynamic (meaning a variable can hold an object of any type and cannot be restricted). Java is loaded from compiled bytecode; JavaScript is loaded as human-readable code. C is their last common ancestor language.

Regular expression to match balanced parentheses

You need the first and last parentheses. Use something like this:

str.indexOf('('); - it will give you first occurrence

str.lastIndexOf(')'); - last one

So you need a string between,

String searchedString = str.substring(str1.indexOf('('),str1.lastIndexOf(')');

Hive: Filtering Data between Specified Dates when Date is a String

You have to convert string formate to required date format as following and then you can get your required result.

hive> select * from salesdata01 where from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') >= from_unixtime(unix_timestamp('2010-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') and from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') <= from_unixtime(unix_timestamp('2011-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') limit 10;
OK
1   3   13-10-2010  Low 6.0 261.54  0.04    Regular Air -213.25 38.94
80  483 10-07-2011  High    30.0    4965.7593   0.08    Regular Air 1198.97 195.99
97  613 17-06-2011  High    12.0    93.54   0.03    Regular Air -54.04  7.3
98  613 17-06-2011  High    22.0    905.08  0.09    Regular Air 127.7   42.76
103 643 24-03-2011  High    21.0    2781.82 0.07    Express Air -695.26 138.14
127 807 23-11-2010  Medium  45.0    196.85  0.01    Regular Air -166.85 4.28
128 807 23-11-2010  Medium  32.0    124.56  0.04    Regular Air -14.33  3.95
160 995 30-05-2011  Medium  46.0    1815.49 0.03    Regular Air 782.91  39.89
229 1539    09-03-2011  Low 33.0    511.83  0.1 Regular Air -172.88 15.99
230 1539    09-03-2011  Low 38.0    184.99  0.05    Regular Air -144.55 4.89
Time taken: 0.166 seconds, Fetched: 10 row(s)
hive> select * from salesdata01 where from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') >= from_unixtime(unix_timestamp('2010-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') and from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') <= from_unixtime(unix_timestamp('2010-12-01', 'yyyy-MM-dd'),'yyyy-MM-dd') limit 10;
OK
1   3   13-10-2010  Low 6.0 261.54  0.04    Regular Air -213.25 38.94
127 807 23-11-2010  Medium  45.0    196.85  0.01    Regular Air -166.85 4.28
128 807 23-11-2010  Medium  32.0    124.56  0.04    Regular Air -14.33  3.95
256 1792    08-11-2010  Low 28.0    370.48  0.04    Regular Air -5.45   13.48
381 2631    23-09-2010  Low 27.0    1078.49 0.08    Regular Air 252.66  40.96
656 4612    19-09-2010  Medium  9.0 89.55   0.06    Regular Air -375.64 4.48
769 5506    07-11-2010  Critical    22.0    129.62  0.05    Regular Air 4.41    5.88
1457    10499   16-11-2010  Not Specified   29.0    6250.936    0.01    Delivery Truck  31.21   262.11
1654    11911   10-11-2010  Critical    25.0    397.84  0.0 Regular Air -14.75  15.22
2323    16741   30-09-2010  Medium  6.0 157.97  0.01    Regular Air -42.38  22.84
Time taken: 0.17 seconds, Fetched: 10 row(s)

What is the maximum length of a URL in different browsers?

WWW FAQs: What is the maximum length of a URL? has its own answer based on empirical testing and research. The short answer is that going over 2048 characters makes Internet Explorer unhappy and thus this is the limit you should use. See the page for a long answer.

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

Protecting cells in Excel but allow these to be modified by VBA script

A basic but simple to understand answer:

Sub Example()
    ActiveSheet.Unprotect
    Program logic...
    ActiveSheet.Protect
End Sub

typeof !== "undefined" vs. != null

good way:

if(typeof neverDeclared == "undefined") //no errors

But the best looking way is to check via :

if(typeof neverDeclared === typeof undefined) //also no errors and no strings

Safely limiting Ansible playbooks to a single machine?

This approach will exit if more than a single host is provided by checking the play_hosts variable. The fail module is used to exit if the single host condition is not met. The examples below use a hosts file with two hosts alice and bob.

user.yml (playbook)

---
- hosts: all
  tasks:
    - name: Check for single host
      fail: msg="Single host check failed."
      when: "{{ play_hosts|length }} != 1"
    - debug: msg='I got executed!'

Run playbook with no host filters

$ ansible-playbook user.yml
PLAY [all] ****************************************************************
TASK: [Check for single host] *********************************************
failed: [alice] => {"failed": true}
msg: Single host check failed.
failed: [bob] => {"failed": true}
msg: Single host check failed.
FATAL: all hosts have already failed -- aborting

Run playbook on single host

$ ansible-playbook user.yml --limit=alice

PLAY [all] ****************************************************************

TASK: [Check for single host] *********************************************
skipping: [alice]

TASK: [debug msg='I got executed!'] ***************************************
ok: [alice] => {
    "msg": "I got executed!"
}

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

I was getting below error on playback

finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey=https://remote-abcabc-svc.an.abc.com:1935/abr/_definst_/smil:v2/video/492F2F82592F59EA74ABAA6B9D6E6F42/F6B1BD452132329FBACD32730862CAE0/091EAD80FE9BEDD52A2F33840CA3CBAC.v3.eng.smil/playlist.m3u8, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <692A1174-DA1C-4267-9560-9020A79F8458>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <692A1174-DA1C-4267-9560-9020A79F8458>

I made sure that I added entry in exception domains in plist file and NSAllowsArbitraryLoads is set to true and still I was seeing an error.

Then I realized that I am playing URL with https and not http.

I set video url to http and problem solved.

Why my $.ajax showing "preflight is invalid redirect error"?

I received the same error when I tried to call https web service as http webservice.

e.g when I call url 'http://api.example.com/users/get'
which should be 'https://api.example.com/users/get'

This error is produced because of redirection status 302 when you try to call http instead of https.

How does Java import work?

In dynamic languages, when the interpreter imports, it simply reads a file and evaluates it.

In C, external libraries are located by the linker at compile time to build the final object if the library is statically compiled, while for dynamic libraries a smaller version of the linker is called at runtime which remaps addresses and so makes code in the library available to the executable.

In Java, import is simply used by the compiler to let you name your classes by their unqualified name, let's say String instead of java.lang.String. You don't really need to import java.lang.* because the compiler does it by default. However this mechanism is just to save you some typing. Types in Java are fully qualified class names, so a String is really a java.lang.String object when the code is run. Packages are intended to prevent name clashes and allow two classes to have the same simple name, instead of relying on the old C convention of prefixing types like this. java_lang_String. This is called namespacing.

BTW, in Java there's the static import construct, which allows to further save typing if you use lots of constants from a certain class. In a compilation unit (a .java file) which declares

import static java.lang.Math.*;

you can use the constant PI in your code, instead of referencing it through Math.PI, and the method cos() instead of Math.cos(). So for example you can write

double r = cos(PI * theta);

Once you understand that classes are always referenced by their fully qualified name in the final bytecode, you must understand how the class code is actually loaded. This happens the first time an object of that class is created, or the first time a static member of the class is accessed. At this time, the ClassLoader tries to locate the class and instantiate it. If it can't find the class a NoClassDefFoundError is thrown (or a a ClassNotFoundException if the class is searched programmatically). To locate the class, the ClassLoader usually checks the paths listed in the $CLASSPATH environment variable.

To solve your problem, it seems you need an applet element like this

<applet
  codebase = "http://san.redenetimoveis.com"
  archive="test.jar, core.jar"
  code="com.colorfulwolf.webcamapplet.WebcamApplet"      
  width="550" height="550" >

BTW, you don't need to import the archives in the standard JRE.

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

Swift 2

Simple

let str = "My String"
let subStr = str[str.startIndex.advancedBy(3)...str.startIndex.advancedBy(7)]
//"Strin"

Swift 3

let startIndex = str.index(str.startIndex, offsetBy: 3)
let endIndex = str.index(str.startIndex, offsetBy: 7)

str[startIndex...endIndex]       // "Strin"
str.substring(to: startIndex)    // "My "
str.substring(from: startIndex)  // "String"

Swift 4

substring(to:) and substring(from:) are deprecated in Swift 4.

String(str[..<startIndex])    // "My "
String(str[startIndex...])    // "String"
String(str[startIndex...endIndex])    // "Strin"

Add a space (" ") after an element using :after

Turns out it needs to be specified via escaped unicode. This question is related and contains the answer.

The solution:

h2:after {
    content: "\00a0";
}

How can I use SUM() OVER()

if you are using SQL 2012 you should try

SELECT  ID, 
        AccountID, 
        Quantity, 
        SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY AccountID rows between unbounded preceding and current row ) AS TopBorcT, 
FROM tCariH

if available, better order by date column.

What does it mean by select 1 from table?

it does what it says - it will always return the integer 1. It's used to check whether a record matching your where clause exists.

Convert string to a variable name

assign is what you are looking for.

assign("x", 5)

x
[1] 5

but buyer beware.

See R FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f

forEach is not a function error with JavaScript array

First option: invoke forEach indirectly

The parent.children is an Array like object. Use the following solution:

const parent = this.el.parentElement;

Array.prototype.forEach.call(parent.children, child => {
  console.log(child)
});

The parent.children is NodeList type, which is an Array like object because:

  • It contains the length property, which indicates the number of nodes
  • Each node is a property value with numeric name, starting from 0: {0: NodeObject, 1: NodeObject, length: 2, ...}

See more details in this article.


Second option: use the iterable protocol

parent.children is an HTMLCollection: which implements the iterable protocol. In an ES2015 environment, you can use the HTMLCollection with any construction that accepts iterables.

Use HTMLCollection with the spread operatator:

const parent = this.el.parentElement;

[...parent.children].forEach(child => {
  console.log(child);
});

Or with the for..of cycle (which is my preferred option):

const parent = this.el.parentElement;

for (const child of parent.children) {
  console.log(child);
}

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.

That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.

public class PlusEquals {
    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        a = a + b;
        System.out.println(a);
    }
}

What does this program print?

Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.

But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

oracle varchar to number

select to_number(exception_value) from exception where to_number(exception_value) = 105

UL or DIV vertical scrollbar

Sometimes it is not eligible to set height to pixel values. However, it is possible to show vertical scrollbar through setting height of div to 100% and overflow to auto.

Let me show an example:

<div id="content" style="height: 100%; overflow: auto">
  <p>some text</p>
  <ul>
    <li>text</li>
    .....
    <li>text</li>
</div>

Converting Long to Date in Java returns 1970

Only set the time in mills on Calendar object

Calendar c = Calendar.getInstance();
c.setTimeInMillis(1385355600000l);
System.out.println(c.get(Calendar.YEAR));
System.out.println(c.get(Calendar.MONTH));
System.out.println(c.get(Calendar.DAY_OF_MONTH));
// get Date
System.out.println(c.getTime());

"inconsistent use of tabs and spaces in indentation"

I had the same problem and fix it using following python script. hope it help others.

it is because of using tabs and spaces for indenting code. in this script I replace each tab with four spaces.

input_file = "source code path here"  # e.g. source.py
output_file = "out put file path here"  # e.g out.py
with open(input_file, 'r') as source:
    with open(output_file, 'a+') as result:
        for line in source:
            line = line.replace('\t', '    ')
            result.write(line)

if you use sublime or any other editor which gives you the tool to replace text you can replace all tabs by four spaces from editor.

Setting onClickListener for the Drawable right of an EditText

This has been already answered but I tried a different way to make it simpler.

The idea is using putting an ImageButton on the right of EditText and having negative margin to it so that the EditText flows into the ImageButton making it look like the Button is in the EditText.

enter image description here

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/editText"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="Enter Pin"
            android:singleLine="true"
            android:textSize="25sp"
            android:paddingRight="60dp"
            />
        <ImageButton
            android:id="@+id/pastePin"
            android:layout_marginLeft="-60dp"
            style="?android:buttonBarButtonStyle"
            android:paddingBottom="5dp"
            android:src="@drawable/ic_action_paste"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

Also, as shown above, you can use a paddingRight of similar width in the EditText if you don't want the text in it to be flown over the ImageButton.

I guessed margin size with the help of android-studio's layout designer and it looks similar across all screen sizes. Or else you can calculate the width of the ImageButton and set the margin programatically.

MS SQL Date Only Without Time

Careful here, if you use anything a long the lines of WHERE CAST(CONVERT(VARCHAR, [tstamp], 102) AS DATETIME) = @dateParam it will force a scan on the table and no indexes will be used for that portion.

A much cleaner way of doing this is defining a calculated column

create table #t (
    d datetime, 

    d2 as 
        cast (datepart(year,d) as varchar(4)) + '-' +
        right('0' + cast (datepart(month,d) as varchar(2)),2) + '-' + 
        right('0' + cast (datepart(day,d) as varchar(2)),2) 
) 
-- notice a lot of care need to be taken to ensure the format is comparable. (zero padding)

insert #t 
values (getdate())

create index idx on #t(d2)

select d2, count(d2) from #t 
where d2 between '2008-01-01' and '2009-01-22'
group by d2
-- index seek is used

This way you can directly check the d2 column and an index will be used and you dont have to muck around with conversions.

How to make a phone call programmatically?

If you end up with a SecurityException (and the call does not work), You should consider requesting the user permission to make a call as this is considered a dangerous permission:

ActivityCompat.requestPermissions(
    activity,
    new String[] {Manifest.permission.CALL_PHONE},
    1
);

Note this has nothing to do with the manifest permission (that you must have as well)

PYTHONPATH vs. sys.path

If the only reason to modify the path is for developers working from their working tree, then you should use an installation tool to set up your environment for you. virtualenv is very popular, and if you are using setuptools, you can simply run setup.py develop to semi-install the working tree in your current Python installation.

How does ifstream's eof() work?

eof() checks the eofbit in the stream state.

On each read operation, if the position is at the end of stream and more data has to be read, eofbit is set to true. Therefore you're going to get an extra character before you get eofbit=1.

The correct way is to check whether the eof was reached (or, whether the read operation succeeded) after the reading operation. This is what your second version does - you do a read operation, and then use the resulting stream object reference (which >> returns) as a boolean value, which results in check for fail().

Finding Number of Cores in Java

This works on Windows with Cygwin installed:

System.getenv("NUMBER_OF_PROCESSORS")

Android - Center TextView Horizontally in LinearLayout

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/title_bar_background">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:padding="10dp"
    android:text="HELLO WORLD" />

</LinearLayout>

How can I truncate a double to only two decimal places in Java?

Formating as a string and converting back to double i think will give you the result you want.

The double value will not be round(), floor() or ceil().

A quick fix for it could be:

 String sValue = (String) String.format("%.2f", oldValue);
 Double newValue = Double.parseDouble(sValue);

You can use the sValue for display purposes or the newValue for calculation.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I was able to fix this by following the steps in this article: http://www.mikesdotnetting.com/article/280/solved-the-microsoft-ace-oledb-12-0-provider-is-not-registered-on-the-local-machine

The key point for me was this:

When debugging with IIS,

by default, Visual Studio uses the 32-bit version. You can change this from within Visual Studio by going to Tools » Options » Projects And Solutions » Web Projects » General, and choosing

"Use the 64 bit version of IIS Express for websites and projects"

After checking that option, then setting the platform target of my project back to "Any CPU" (i had set it to x86 somewhere in the troubleshooting process), i was able to overcome the error.

CodeIgniter - File upload required validation

you can solve it by overriding the Run function of CI_Form_Validation

copy this function in a class which extends CI_Form_Validation .

This function will override the parent class function . Here i added only a extra check which can handle file also

/**
 * Run the Validator
 *
 * This function does all the work.
 *
 * @access  public
 * @return  bool
 */
function run($group = '') {
    // Do we even have any data to process?  Mm?
    if (count($_POST) == 0) {
        return FALSE;
    }

    // Does the _field_data array containing the validation rules exist?
    // If not, we look to see if they were assigned via a config file
    if (count($this->_field_data) == 0) {
        // No validation rules?  We're done...
        if (count($this->_config_rules) == 0) {
            return FALSE;
        }

        // Is there a validation rule for the particular URI being accessed?
        $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;

        if ($uri != '' AND isset($this->_config_rules[$uri])) {
            $this->set_rules($this->_config_rules[$uri]);
        } else {
            $this->set_rules($this->_config_rules);
        }

        // We're we able to set the rules correctly?
        if (count($this->_field_data) == 0) {
            log_message('debug', "Unable to find validation rules");
            return FALSE;
        }
    }

    // Load the language file containing error messages
    $this->CI->lang->load('form_validation');

    // Cycle through the rules for each field, match the
    // corresponding $_POST or $_FILES item and test for errors
    foreach ($this->_field_data as $field => $row) {
        // Fetch the data from the corresponding $_POST or $_FILES array and cache it in the _field_data array.
        // Depending on whether the field name is an array or a string will determine where we get it from.

        if ($row['is_array'] == TRUE) {

            if (isset($_FILES[$field])) {
                $this->_field_data[$field]['postdata'] = $this->_reduce_array($_FILES, $row['keys']);
            } else {
                $this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
            }
        } else {
            if (isset($_POST[$field]) AND $_POST[$field] != "") {
                $this->_field_data[$field]['postdata'] = $_POST[$field];
            } else if (isset($_FILES[$field]) AND $_FILES[$field] != "") {
                $this->_field_data[$field]['postdata'] = $_FILES[$field];
            }
        }

        $this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
    }

    // Did we end up with any errors?
    $total_errors = count($this->_error_array);

    if ($total_errors > 0) {
        $this->_safe_form_data = TRUE;
    }

    // Now we need to re-set the POST data with the new, processed data
    $this->_reset_post_array();

    // No errors, validation passes!
    if ($total_errors == 0) {
        return TRUE;
    }

    // Validation fails
    return FALSE;
}

How to change letter spacing in a Textview?

For embedding HTML text in your textview you can use Html.fromHTML() syntax. More information you will get from http://developer.android.com/reference/android/text/Html.html#fromHtml%28java.lang.String%29

Java maximum memory on Windows XP

The JVM needs contiguous memory and depending on what else is running, what was running before, and how windows has managed memory you may be able to get up to 1.4GB of contiguous memory. I think 64bit Windows will allow larger heaps.

How can I disable the Maven Javadoc plugin from the command line?

Add to the release plugin config in the root-level pom.xml:

<configuration>
    <arguments>-Dmaven.javadoc.skip=true</arguments>
</configuration>

Replace multiple characters in one replace call

You can just try this :

str.replace(/[.#]/g, 'replacechar');

this will replace .,- and # with your replacechar !

javac: invalid target release: 1.8

For IntelliJ IDEA Ultimate latest version as of 18th Dec 2017, if the above suggestions don't work, then please try the following: Right Click on the project and navigate to "Open Module Settings". Open it, then change the "Language Level" from the dropdown.

The model backing the 'ApplicationDbContext' context has changed since the database was created

Below was the similar kind of error i encountered

The model backing the 'PsnlContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

I added the below section in the Application Start event of the Global.asax to solve the error

Database.SetInitializer (null);

This fixed the issue

Redirect all output to file in Bash

You can use exec command to redirect all stdout/stderr output of any commands later.

sample script:

exec 2> your_file2 > your_file1
your other commands.....

Uploading an Excel sheet and importing the data into SQL Server database

using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;

protected void Button1_Click(object sender, EventArgs e)

{

    //Upload and save the file

    string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);

    FileUpload1.SaveAs(excelPath);



    string conString = string.Empty;

    string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);

    switch (extension)

    {

        case ".xls": //Excel 97-03

            conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;

            break;

        case ".xlsx": //Excel 07 or higher

            conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;

            break;



    }

    conString = string.Format(conString, excelPath);

    using (OleDbConnection excel_con = new OleDbConnection(conString))

    {

        excel_con.Open();

        string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();

        DataTable dtExcelData = new DataTable();



        //[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.

        dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),

            new DataColumn("Name", typeof(string)) });



        using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))

        {

            oda.Fill(dtExcelData);

        }

        excel_con.Close();



        string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;

        using (SqlConnection con = new SqlConnection(consString))

        {

            using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))

            {

                //Set the database table name

                sqlBulkCopy.DestinationTableName = "dbo.Table1";



                //[OPTIONAL]: Map the Excel columns with that of the database table

                sqlBulkCopy.ColumnMappings.Add("Sl", "Id");

                sqlBulkCopy.ColumnMappings.Add("Name", "Name");

                con.Open();

                sqlBulkCopy.WriteToServer(dtExcelData);

                con.Close();

            }

        }

    }

}

Copy this in web config

<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>

<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>

you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html

Maven compile with multiple src directories

I naively do it this way :

<build>
  <finalName>osmwse</finalName>
  <sourceDirectory>src/main/java, src/interfaces, src/services</sourceDirectory>
</build>

How to allocate aligned memory only using the standard library?

Unfortunately, in C99 it seems pretty tough to guarantee alignment of any sort in a way which would be portable across any C implementation conforming to C99. Why? Because a pointer is not guaranteed to be the "byte address" one might imagine with a flat memory model. Neither is the representation of uintptr_t so guaranteed, which itself is an optional type anyway.

We might know of some implementations which use a representation for void * (and by definition, also char *) which is a simple byte address, but by C99 it is opaque to us, the programmers. An implementation might represent a pointer by a set {segment, offset} where offset could have who-knows-what alignment "in reality." Why, a pointer could even be some form of hash table lookup value, or even a linked-list lookup value. It could encode bounds information.

In a recent C1X draft for a C Standard, we see the _Alignas keyword. That might help a bit.

The only guarantee C99 gives us is that the memory allocation functions will return a pointer suitable for assignment to a pointer pointing at any object type. Since we cannot specify the alignment of objects, we cannot implement our own allocation functions with responsibility for alignment in a well-defined, portable manner.

It would be good to be wrong about this claim.

How to read a file into vector in C++?

1. In the loop you are assigning value rather than comparing value so

i=((Main.size())-1) -> i=(-1) since Main.size()

Main[i] will yield "Vector Subscript out of Range" coz i = -1.

2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.

intl extension: installing php_intl.dll

/Digger here/

Moving the icu*****.dll files to /ext/ seems to resolve the issue as well.

( If you specified the extension directory to be there of course )

Remove stubborn underline from link

You missed text-decoration:none for the anchor tag. So code should be following.

_x000D_
_x000D_
.boxhead a {_x000D_
    text-decoration: none;_x000D_
}
_x000D_
<div class="boxhead">_x000D_
    <h2>_x000D_
        <span class="thisPage">Current Page</span>_x000D_
        <a href="myLink"><span class="otherPage">Different Page</span></a>_x000D_
    </h2>_x000D_
</div>
_x000D_
_x000D_
_x000D_

More standard properties for text-decoration

enter image description here

How to get the version of ionic framework?

At some point in time the object changed from ionic to an uppercase Ionic.

As of July 2017 you need to put Ionic.version into your console to get the version number.

Add items to comboBox in WPF

There are many ways to perform this task. Here is a simple one:

<Window x:Class="WPF_Demo1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     x:Name="TestWindow"
    Title="MainWindow" Height="500" Width="773">

<DockPanel LastChildFill="False">
    <StackPanel DockPanel.Dock="Top" Background="Red" Margin="2">
        <StackPanel Orientation="Horizontal" x:Name="spTopNav">
            <ComboBox x:Name="cboBox1" MinWidth="120"> <!-- Notice we have used x:Name to identify the object that we want to operate upon.-->
            <!--
                <ComboBoxItem Content="X"/>
                <ComboBoxItem Content="Y"/>
                <ComboBoxItem Content="Z"/>
            -->
            </ComboBox>
        </StackPanel>
    </StackPanel>
    <StackPanel DockPanel.Dock="Bottom" Background="Orange" Margin="2">
        <StackPanel Orientation="Horizontal" x:Name="spBottomNav">
        </StackPanel>
        <TextBlock Height="30" Foreground="White">Left Docked StackPanel 2</TextBlock>
    </StackPanel>
    <StackPanel MinWidth="200" DockPanel.Dock="Left" Background="Teal" Margin="2" x:Name="StackPanelLeft">
        <TextBlock  Foreground="White">Bottom Docked StackPanel Left</TextBlock>

    </StackPanel>
    <StackPanel DockPanel.Dock="Right" Background="Yellow" MinWidth="150" Margin="2" x:Name="StackPanelRight"></StackPanel>
    <Button Content="Button" Height="410" VerticalAlignment="Top" Width="75" x:Name="myButton" Click="myButton_Click"/>


</DockPanel>

</Window>      

Next, we have the C# code:

    private void myButton_Click(object sender, RoutedEventArgs e)
    {
        ComboBoxItem cboBoxItem = new ComboBoxItem(); // Create example instance of our desired type.
        Type type1 = cboBoxItem.GetType();
        object cboBoxItemInstance = Activator.CreateInstance(type1); // Construct an instance of that type.
        for (int i = 0; i < 12; i++)
        {
            string newName = "stringExample" + i.ToString();
           // Generate the objects from our list of strings.
            ComboBoxItem item = this.CreateComboBoxItem((ComboBoxItem)cboBoxItemInstance, "nameExample_" + newName, newName);
            cboBox1.Items.Add(item); // Add each newly constructed item to our NAMED combobox.
        }
    }
    private ComboBoxItem CreateComboBoxItem(ComboBoxItem myCbo, string content, string name)
    {
        Type type1 = myCbo.GetType();
        ComboBoxItem instance = (ComboBoxItem)Activator.CreateInstance(type1);
        // Here, we're using reflection to get and set the properties of the type.
        PropertyInfo Content = instance.GetType().GetProperty("Content", BindingFlags.Public | BindingFlags.Instance);
        PropertyInfo Name = instance.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
        this.SetProperty<ComboBoxItem, String>(Content, instance, content);
        this.SetProperty<ComboBoxItem, String>(Name, instance, name);

        return instance;
        //PropertyInfo prop = type.GetProperties(rb1);
    }

Note: This is using reflection. If you'd like to learn more about the basics of reflection and why you might want to use it, this is a great introductory article:

If you'd like to learn more about how you might use reflection with WPF specifically, here are some resources:

And if you want to massively speed up the performance of reflection, it's best to use IL to do that, like this:

Express.js - app.listen vs server.listen

Express is basically a wrapper of http module that is created for the ease of the developers in such a way that..

  1. They can set up middlewares to respond to HTTP Requests (easily) using express.
  2. They can dynamically render HTML Pages based on passing arguments to templates using express.
  3. They can also define routing easily using express.

display HTML page after loading complete

The easiest thing to do is putting a div with the following CSS in the body:

#hideAll
 {
   position: fixed;
   left: 0px; 
   right: 0px; 
   top: 0px; 
   bottom: 0px; 
   background-color: white;
   z-index: 99; /* Higher than anything else in the document */

 }

(Note that position: fixed won't work in IE6 - I know of no sure-fire way of doing this in that browser)

Add the DIV like so (directly after the opening body tag):

<div style="display: none" id="hideAll">&nbsp;</div>

show the DIV directly after :

 <script type="text/javascript">
   document.getElementById("hideAll").style.display = "block";
 </script> 

and hide it onload:

 window.onload = function() 
  { document.getElementById("hideAll").style.display = "none"; }

or using jQuery

 $(window).load(function() {  document.getElementById("hideAll").style.display = "none"; });

this approach has the advantage that it will also work for clients who have JavaScript turned off. It shouldn't cause any flickering or other side-effects, but not having tested it, I can't entirely guarantee it for every browser out there.

VB.NET Empty String Array

A little verbose, but self documenting...

Dim strEmpty() As String = Enumerable.Empty(Of String).ToArray

Jmeter - get current date and time

Use this format: ${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}

Which will give you: 2018-01-16T08:32:28.75Z

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

I got the same error using:

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">

But once I added https: in the beginning of the href the error disappeared.

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">

Bash tool to get nth line from a file

To print nth line using sed with a variable as line number:

a=4
sed -e $a'q:d' file

Here the '-e' flag is for adding script to command to be executed.

warning: control reaches end of non-void function [-Wreturn-type]

You just need to return from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.

  /* .... */
  if (Date1 == Date2)  
     fprintf (stderr , "Indicating that the first date is equal to second date.\n"); 

  return 0;
}

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

i was trying to use airbnb deeplink dispatch and got this error. i had to also exlude the findbugs group from the annotationProcessor.

//airBnb
    compile ('com.airbnb:deeplinkdispatch:3.1.1'){
        exclude group:'com.google.code.findbugs'
    }
    annotationProcessor ('com.airbnb:deeplinkdispatch-processor:3.1.1'){
        exclude group:'com.google.code.findbugs'
    }

Using Switch Statement to Handle Button Clicks

I have found that the simplest way to do this is to set onClick for each button in the xml

<Button
android:id="@+id/vrHelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_menu_help"
android:onClick="helpB" />

and then you can do a switch case like this

  public void helpB(View v) {
    Button clickedButton = (Button) v;
    switch (clickedButton.getId()) {
      case R.id.vrHelp:
        dosomething...
        break;

      case R.id.coHelp:
        dosomething...
        break;

      case R.id.ksHelp:
        dosomething...
        break;

      case R.id.uHelp:
        dosomething...
        break;

      case R.id.pHelp:
        dosomething...
        break;
    }
  }

CORS header 'Access-Control-Allow-Origin' missing

You have to modify your server side code, as given below

public class CorsResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext,   ContainerResponseContext responseContext)
    throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

  }
}

How to clear cache in Yarn?

In addition to the answer, $ yarn cache clean removes all libraries from cache. If you want to remove a specific lib's cache run $ yarn cache dir to get the right yarn cache directory path for your OS, then $ cd to that directory and remove the folder with the name + version of the lib you want to cleanup.

program cant start because php5.dll is missing

I needed to change environment variable PATH and PHPRC. Also open new cmd.

I already had PHP installed and added EasyPHP when the problem came up. After I changed both variables to C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\binaries\php\php_runningversion it worked fine.

Dockerfile copy keep subdirectory structure

Remove star from COPY, with this Dockerfile:

FROM ubuntu
COPY files/ /files/
RUN ls -la /files/*

Structure is there:

$ docker build .
Sending build context to Docker daemon 5.632 kB
Sending build context to Docker daemon 
Step 0 : FROM ubuntu
 ---> d0955f21bf24
Step 1 : COPY files/ /files/
 ---> 5cc4ae8708a6
Removing intermediate container c6f7f7ec8ccf
Step 2 : RUN ls -la /files/*
 ---> Running in 08ab9a1e042f
/files/folder1:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2

/files/folder2:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2
 ---> 03ff0a5d0e4b
Removing intermediate container 08ab9a1e042f
Successfully built 03ff0a5d0e4b

Removing black dots from li and ul

Relatable post

Those pesky black dots you are referencing to are called bullets.

They are pretty simple to remove, just add this line to your css:

ul {
    list-style-type: none;
}

Hope this helps

Generating random number between 1 and 10 in Bash Shell Script

To generate random numbers with bash use the $RANDOM internal Bash function. Note that $RANDOM should not be used to generate an encryption key. $RANDOM is generated by using your current process ID (PID) and the current time/date as defined by the number of seconds elapsed since 1970.

 echo $RANDOM % 10 + 1 | bc

Undefined symbols for architecture i386

At the risk of sounding obvious, always check the spelling of your forward class files. Sometimes XCode (at least XCode 4.3.2) will turn a declaration green that's actually camel cased incorrectly. Like in this example:

"_OBJC_CLASS_$_RadioKit", referenced from:
  objc-class-ref in RadioPlayerViewController.o

If RadioKit was a class file and you make it a property of another file, in the interface declaration, you might see that

Radiokit *rk;

has "Radiokit" in green when the actual decalaration should be:

RadioKit *rk;

This error will also throw this type of error. Another example (in my case), is when you have _iPhone and _iphone extensions on your class names for universal apps. Once I changed the appropriate file from _iphone to the correct _iPhone, the errors went away.

merge two object arrays with Angular 2 and TypeScript?

The spread operator is kinda cool.

this.results = [ ...this.results, ...data.results];

The spread operator allows you to easily place an expanded version of an array into another array.

You can read about spread operator here.

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

When I got the same error on my machine ("connection is refused"), the reason was that I had defined the following on the server side:

 Naming.rebind("rmi://localhost:8080/AddService"
   ,addService); 

Thus the server binds both the IP = 127.0.0.1 and the port 8080.

But on the client side I had used:

AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost"
                        +"/AddService");

Thus I forgot to add the port number after the localhost, so I rewrote the above command and added the port number 8080 as follows:

AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost:8080"
                        +"/AddService");

and everything worked fine.

javascript regex - look behind alternative?

Below is a positive lookbehind JavaScript alternative showing how to capture the last name of people with 'Michael' as their first name.

1) Given this text:

const exampleText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green Miller and Michael Wood?";

get an array of last names of people named Michael. The result should be: ["Jordan","Johnson","Green","Wood"]

2) Solution:

function getMichaelLastName2(text) {
  return text
    .match(/(?:Michael )([A-Z][a-z]+)/g)
    .map(person => person.slice(person.indexOf(' ')+1));
}

// or even
    .map(person => person.slice(8)); // since we know the length of "Michael "

3) Check solution

console.log(JSON.stringify(    getMichaelLastName(exampleText)    ));
// ["Jordan","Johnson","Green","Wood"]

Demo here: http://codepen.io/PiotrBerebecki/pen/GjwRoo

You can also try it out by running the snippet below.

_x000D_
_x000D_
const inputText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green Miller and Michael Wood?";_x000D_
_x000D_
_x000D_
_x000D_
function getMichaelLastName(text) {_x000D_
  return text_x000D_
    .match(/(?:Michael )([A-Z][a-z]+)/g)_x000D_
    .map(person => person.slice(8));_x000D_
}_x000D_
_x000D_
console.log(JSON.stringify(    getMichaelLastName(inputText)    ));
_x000D_
_x000D_
_x000D_

What is &amp used for

if you're doing a string of characters. make:

let linkGoogle = 'https://www.google.com/maps/dir/?api=1'; 
let origin = '&origin=' + locations[0][1] + ',' + locations[0][2];


aNav.href = linkGoogle + origin;

.NET DateTime to SqlDateTime Conversion

If you are checking for DBNULL, converting a SQL Datetime to a .NET DateTime should not be a problem. However, you can run into problems converting a .NET DateTime to a valid SQL DateTime.

SQL Server does not recognize dates prior to 1/1/1753. Thats the year England adopted the Gregorian Calendar. Usually checking for DateTime.MinValue is sufficient, but if you suspect that the data could have years before the 18th century, you need to make another check or use a different data type. (I often wonder what Museums use in their databases)

Checking for max date is not really necessary, SQL Server and .NET DateTime both have a max date of 12/31/9999 It may be a valid business rule but it won't cause a problem.

Can I position an element fixed relative to parent?

2016 Update

It's now possible in modern browsers to position an element fixed relative to its container. An element that has a transform property acts as the viewport for any of its fixed position child elements.

Or as the CSS Transforms Module puts it:

For elements whose layout is governed by the CSS box model, any value other than none for the transform property also causes the element to establish a containing block for all descendants. Its padding box will be used to layout for all of its absolute-position descendants, fixed-position descendants, and descendant fixed background attachments.

_x000D_
_x000D_
.context {_x000D_
  width: 300px;_x000D_
  height: 250px;_x000D_
  margin: 100px;_x000D_
  transform: translateZ(0);_x000D_
}_x000D_
.viewport {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  border: 1px solid black;_x000D_
  overflow: scroll;_x000D_
}_x000D_
.centered {_x000D_
  position: fixed;_x000D_
  left: 50%;_x000D_
  bottom: 15px;_x000D_
  transform: translateX(-50%);_x000D_
}
_x000D_
<div class="context">_x000D_
  <div class="viewport">_x000D_
    <div class="canvas">_x000D_
_x000D_
      <table>_x000D_
        <tr>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
_x000D_
      <button class="centered">OK</button>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

List directory in Go

Starting with Go 1.16, you can use the os.ReadDir function.

func ReadDir(name string) ([]DirEntry, error)

It reads a given directory and returns a DirEntry slice that contains the directory entries sorted by filename.

It's an optimistic function, so that, when an error occurs while reading the directory entries, it tries to return you a slice with the filenames up to the point before the error.

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    files, err := os.ReadDir(".")
    if err != nil {
        log.Fatal(err)
    }

    for _, file := range files {
        fmt.Println(file.Name())
    }
}

Background

Go 1.16 (Q1 2021) will propose, with CL 243908 and CL 243914 , the ReadDir function, based on the FS interface:

// An FS provides access to a hierarchical file system.
//
// The FS interface is the minimum implementation required of the file system.
// A file system may implement additional interfaces,
// such as fsutil.ReadFileFS, to provide additional or optimized functionality.
// See io/fsutil for details.
type FS interface {
    // Open opens the named file.
    //
    // When Open returns an error, it should be of type *PathError
    // with the Op field set to "open", the Path field set to name,
    // and the Err field describing the problem.
    //
    // Open should reject attempts to open names that do not satisfy
    // ValidPath(name), returning a *PathError with Err set to
    // ErrInvalid or ErrNotExist.
    Open(name string) (File, error)
}

That allows for "os: add ReadDir method for lightweight directory reading":
See commit a4ede9f:

// ReadDir reads the contents of the directory associated with the file f
// and returns a slice of DirEntry values in directory order.
// Subsequent calls on the same file will yield later DirEntry records in the directory.
//
// If n > 0, ReadDir returns at most n DirEntry records.
// In this case, if ReadDir returns an empty slice, it will return an error explaining why.
// At the end of a directory, the error is io.EOF.
//
// If n <= 0, ReadDir returns all the DirEntry records remaining in the directory.
// When it succeeds, it returns a nil error (not io.EOF).
func (f *File) ReadDir(n int) ([]DirEntry, error) 

// A DirEntry is an entry read from a directory (using the ReadDir method).
type DirEntry interface {
    // Name returns the name of the file (or subdirectory) described by the entry.
    // This name is only the final element of the path, not the entire path.
    // For example, Name would return "hello.go" not "/home/gopher/hello.go".
    Name() string
    
    // IsDir reports whether the entry describes a subdirectory.
    IsDir() bool
    
    // Type returns the type bits for the entry.
    // The type bits are a subset of the usual FileMode bits, those returned by the FileMode.Type method.
    Type() os.FileMode
    
    // Info returns the FileInfo for the file or subdirectory described by the entry.
    // The returned FileInfo may be from the time of the original directory read
    // or from the time of the call to Info. If the file has been removed or renamed
    // since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist).
    // If the entry denotes a symbolic link, Info reports the information about the link itself,
    // not the link's target.
    Info() (FileInfo, error)
}

src/os/os_test.go#testReadDir() illustrates its usage:

    file, err := Open(dir)
    if err != nil {
        t.Fatalf("open %q failed: %v", dir, err)
    }
    defer file.Close()
    s, err2 := file.ReadDir(-1)
    if err2 != nil {
        t.Fatalf("ReadDir %q failed: %v", dir, err2)
    }

Ben Hoyt points out in the comments to Go 1.16 os.ReadDir:

os.ReadDir(path string) ([]os.DirEntry, error), which you'll be able to call directly without the Open dance.
So you can probably shorten this to just os.ReadDir, as that's the concrete function most people will call.

See commit 3d913a9 (Dec. 2020):

os: add ReadFile, WriteFile, CreateTemp (was TempFile), MkdirTemp (was TempDir) from io/ioutil

io/ioutil was a poorly defined collection of helpers.

Proposal #40025 moved out the generic I/O helpers to io. This CL for proposal #42026 moves the OS-specific helpers to os, making the entire io/ioutil package deprecated.

os.ReadDir returns []DirEntry, in contrast to ioutil.ReadDir's []FileInfo.
(Providing a helper that returns []DirEntry is one of the primary motivations for this change.)

How to remove element from ArrayList by checking its value?

Try below code :

 public static void main(String[] args) throws Exception{
     List<String> l = new ArrayList<String>();
     l.add("abc");
     l.add("xyz");
     l.add("test");
     l.add("test123");
     System.out.println(l);
     List<String> dl = new ArrayList<String>();
    for (int i = 0; i < l.size(); i++) {
         String a = l.get(i);
         System.out.println(a); 
         if(a.equals("test")){
             dl.add(a);
         }
    }
    l.removeAll(dl);
     System.out.println(l); 
}

your output :

 [abc, xyz, test, test123]
abc
xyz
test
test123
[abc, xyz, test123]

How to style icon color, size, and shadow of Font Awesome Icons

Wrap the i tag in p or span, then you can use bootstrap css class

<p class="text-success"><i class="fa fa-check"></i></p>

Can you autoplay HTML5 videos on the iPad?

I want to start by saying by saying that I realize this question is old and already has an accepted answer; but, as an unfortunate internet user that used this question as a means to end only to be proven wrong shortly after (but not before I upset my client a little) I want to add my thoughts and suggestions.

While @DSG and @Giona are correct, and there is nothing wrong with their answers, there is a creative mechanism you can employ to "get around," so to speak, this limitation. That is not say that I'm condoning circumvention of this feature, quite the contrary, but just some mechanisms so that a user still "feels" as if a video or audio file is "auto playing."

The quick work around is hide a video tag somewhere on the mobile page, since I built a responsive site I only do this for smaller screens. The video tag (HTML and jQuery examples):

HTML

<video id="dummyVideo" src="" preload="none" width="1" height="2"></video>

jQuery

var $dummyVideo = $("<video />", {
  id: "dummyVideo",
  src: "",
  preload: "none",
  width: "1",
  height: "2"
});

With that hidden on the page, when a user "clicks" to watch a movie (still user interaction, there is no way to get around that requirement) instead of navigating to a secondary watch page I load the hidden video. This mainly works because the media tag isn't really used but instead promoted to a Quicktime instance so having a visible video element isn't necessary at all. In the handler for "click" (or "touchend" on mobile).

$(".movie-container").on("click", function() {
  var url = $(this).data("stream-url");
  $dummyVideo.attr("src", url);
  $dummyVideo.get(0).load(); // required if src changed after page load
  $dummyVideo.get(0).play();
});

And viola. As far as UX goes, a user clicks on a video to play and Quicktime opens playing the video they chose. This remains within the limitation that videos can only be played via user action so I'm not forcing data on anyone who isn't deciding to watch a video with this service. I discovered this when trying to figure out how exactly Youtube pulled this off with their mobile which is essentially some really nice Javascript page building and fancy element hiding like in the case of the video tag.

tl;dr Here is a somewhat "workaround" to try and create an "autoplay" UX feature on iOS devices without going above and beyond Apple's limitations and still having users decide if they want to watch a video (or audio most likey, though I've not tested) themselves without having one just loaded without their permission.

Also, to the person who commented that is from sleep.fm, this still unfortunately would not have been a solution to your issues which is time based audio play back.

I hope someone finds this information useful, it would have saved me a week of bad news delivery to a client that was adamant that they have this feature and I was glad to find a way to deliver it in the end.

EDIT

Further finding indicate the above workaround is for iPhone/iPod devices only. The iPad plays video in Safari before it's been full screened so you'll need some mechanism to resize the video on click before playing or else you'll end up with audio and no video.

Laravel update model with unique validation rule for attribute

You can trying code bellow

return [
    'email' => 'required|email|max:255|unique:users,email,' .$this->get('id'),
    'username' => 'required|alpha_dash|max:50|unique:users,username,'.$this->get('id'),
    'password' => 'required|min:6',
    'confirm-password' => 'required|same:password',
];

fs.writeFile in a promise, asynchronous-synchronous stuff

say

const util = require('util')
const fs_writeFile = util.promisify(fs.writeFile)

https://nodejs.org/api/util.html#util_util_promisify_original

this is less prone to bugs than the top-voted answer

CSS / HTML Navigation and Logo on same line

Firstly, let's use some semantic HTML.

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Get in Touch</a></li>
    </ul>
</nav>

In fact, you can even get away with the more minimalist:

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <a href="#">Home</a>
    <a href="#">Projects</a>
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Get in Touch</a>
</nav>

Then add some CSS:

.navigation-bar {
    width: 100%;  /* i'm assuming full width */
    height: 80px; /* change it to desired width */
    background-color: red; /* change to desired color */
}
.logo {
    display: inline-block;
    vertical-align: top;
    width: 50px;
    height: 50px;
    margin-right: 20px;
    margin-top: 15px;    /* if you want it vertically middle of the navbar. */
}
.navigation-bar > a {
    display: inline-block;
    vertical-align: top;
    margin-right: 20px;
    height: 80px;        /* if you want it to take the full height of the bar */
    line-height: 80px;    /* if you want it vertically middle of the navbar */
}

Obviously, the actual margins, heights and line-heights etc. depend on your design.

Other options are to use tables or floats for layout, but these are generally frowned upon.

Last but not least, I hope you get cured of div-itis.

How to turn off magic quotes on shared hosting?

If you can't turn it off, here is what I usually do:

get_magic_quotes_gpc() ? $_POST['username'] : mysql_real_escape_string($_POST['username']);

It will be placed in the database in its proper format.

How can I make a DateTimePicker display an empty string?

The basic concept is the same told by others. But its easier to implement this way when you have multiple dateTimePicker.

dateTimePicker1.Value = DateTime.Now;
dateTimePicker1.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker1.ShowCheckBox=true;
dateTimePicker1.Checked=false;


dateTimePicker2.Value = DateTime.Now;
dateTimePicker2.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker2.ShowCheckBox=true;
dateTimePicker2.Checked=false;

the value changed event function

        void Dtp_ValueChanged(object sender, EventArgs e)
        {
            if(((DateTimePicker)sender).ShowCheckBox==true)
            {
                if(((DateTimePicker)sender).Checked==false)
                {
                    ((DateTimePicker)sender).CustomFormat = " ";
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Custom;
                }
                else
                {
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
                }
            }
            else
            {
                ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
            }
        }

When unchecked enter image description here

When checked enter image description here

MySQL: can't access root account

You can use the init files. Check the MySQL official documentation on How to Reset the Root Password (including comments for alternative solutions).

So basically using init files, you can add any SQL queries that you need for fixing your access (such as GRAND, CREATE, FLUSH PRIVILEGES, etc.) into init file (any file).

Here is my example of recovering root account:

echo "CREATE USER 'root'@'localhost' IDENTIFIED BY 'root';" > your_init_file.sql
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;" >> your_init_file.sql 
echo "FLUSH PRIVILEGES;" >> your_init_file.sql

and after you've created your file, you can run:

killall mysqld
mysqld_safe --init-file=$PWD/your_init_file.sql

then to check if this worked, press Ctrl+Z and type: bg to run the process from the foreground into the background, then verify your access by:

mysql -u root -proot
mysql> show grants;
+-------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                   |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' |

See also:

What is a daemon thread in Java?

Daemon threads are low-priority threads whose only role is to provide services to user threads.

Daemon threads are generally created by JVM for background tasks while user threads are created by application for foreground tasks.

Since daemon threads are meant to serve user threads and are only needed while user threads are running, they won't prevent the JVM from exiting once all user threads have finished their execution.

We can set non-daemon thread to daemon using :

setDaemon(true)

Page Redirect after X seconds wait using JavaScript

You need to pass a function to setTimeout

$(window).load(function () {
    window.setTimeout(function () {
        window.location.href = "https://www.google.co.in";
    }, 5000)
});

How to replace � in a string

Use the unicode escape sequence. First you'll have to find the codepoint for the character you seek to replace (let's just say it is ABCD in hex):

str = str.replaceAll("\uABCD", "");

Git fast forward VS no fast forward merge

When we work on development environment and merge our code to staging/production branch then Git no fast forward can be a better option. Usually when we work in development branch for a single feature we tend to have multiple commits. Tracking changes with multiple commits can be inconvenient later on. If we merge with staging/production branch using Git no fast forward then it will have only 1 commit. Now anytime we want to revert the feature, just revert that commit. Life is easy.

Query Mongodb on month, day, year... of a datetime

how about storing the month in its own property since you need to query for it? less elegant than $where, but likely to perform better since it can be indexed.

Disable mouse scroll wheel zoom on embedded Google Maps

Here is a simple solution. Just set the pointer-events: none CSS to the <iframe> to disable mouse scroll.

<div id="gmap-holder">
    <iframe width="100%" height="400" frameborder="0" style="border:0; pointer-events:none"
            src="https://www.google.com/maps/embed/v1/place?q=XXX&key=YYY"></iframe>
</div>

If you want the mouse scroll to be activated when the user clicks into the map, then use the following JS code. It will also disable the mouse scroll again, when the mouse moves out of the map.

$(function() {
    $('#gmap-holder').click(function(e) {
        $(this).find('iframe').css('pointer-events', 'all');
    }).mouseleave(function(e) {
        $(this).find('iframe').css('pointer-events', 'none');
    });
})

How to make Python speak

A bit cheesy, but if you use a mac you can pass a terminal command to the console from python.

Try typing the following in the terminal:

$ say 'hello world' 

And there will be a voice from the mac that will speak that. From python such a thing is relatively easy:

import os
os.system("echo 'hello world'")
os.system("say 'hello world'") 

CSS: how to get scrollbars for div inside container of fixed height

FWIW, here is my approach = a simple one that works for me:

<div id="outerDivWrapper">
   <div id="outerDiv">
      <div id="scrollableContent">
blah blah blah
      </div>
   </div>
</div>

html, body {
   height: 100%;
   margin: 0em;
}

#outerDivWrapper, #outerDiv {
   height: 100%;
   margin: 0em;
}

#scrollableContent {
   height: 100%;
   margin: 0em;
   overflow-y: auto;
}

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

A bit late to the party but, should you have root access, you can do the following directly:

Log into your mysql as root,

$ mysql -u root -p

Show databases;

mysql>SHOW DATABASES;

Select mysql database, which is where all privileges info is located

mysql>USE mysql;

Show tables.

mysql>SHOW TABLES;

The table concerning privileges for your case is 'db', so let's see what columns it has:

mysql>DESC db;

In order to list the users privileges, type the following command, for example:

mysql>SELECT user, host, db, Select_priv, Insert_priv, Update_priv, Delete_priv FROM db ORDER BY user, db;

If you can't find that user or if you see that that user has a 'N' in the Select_priv column, then you have to either INSERT or UPDATE accordingly:

INSERT:

INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv) VALUES ('localhost','DBname','UserName','Y' ,'N','N','N');

UPDATE:

UPDATE db SET Select_priv = 'Y' WHERE User = 'UserName' AND Db = 'DBname' AND Host='localhost';

Finally, type the following command:

mysql>FLUSH PRIVILEGES;

Ciao.

How do I set up Eclipse/EGit with GitHub?

Make sure your refs for pushing are correct. This tutorial is pretty great, right from the documentation:

http://wiki.eclipse.org/EGit/User_Guide#GitHub_Tutorial

You can clone directly from GitHub, you choose where you clone that repository. And when you import that repository to Eclipse, you choose what refspec to push into upstream.

Click on the Git Repository workspace view, and make sure your remote refs are valid. Make sure you are pointing to the right local branch and pushing to the correct remote branch.

Forking / Multi-Threaded Processes | Bash

In bash scripts (non-interactive) by default JOB CONTROL is disabled so you can't do the the commands: job, fg, and bg.

Here is what works well for me:

#!/bin/sh

set -m # Enable Job Control

for i in `seq 30`; do # start 30 jobs in parallel
  sleep 3 &
done

# Wait for all parallel jobs to finish
while [ 1 ]; do fg 2> /dev/null; [ $? == 1 ] && break; done

The last line uses "fg" to bring a background job into the foreground. It does this in a loop until fg returns 1 ($? == 1), which it does when there are no longer any more background jobs.

Positioning background image, adding padding

Updated Answer:

It's been commented multiple times that this is not the correct answer to this question, and I agree. Back when this answer was written, IE 9 was still new (about 8 months old) and many developers including myself needed a solution for <= IE 9. IE 9 is when IE started supporting background-origin. However, it's been over six and a half years, so here's the updated solution which I highly recommend over using an actual border. In case < IE 9 support is needed. My original answer can be found below the demo snippet. It uses an opaque border to simulate padding for background images.

_x000D_
_x000D_
#hello {
  padding-right: 10px;
  background-color:green;
  background: url("https://placehold.it/15/5C5/FFF") no-repeat scroll right center #e8e8e8;
  background-origin: content-box;
}
_x000D_
<p id="hello">I want the background icon to have padding to it too!I want the background icon twant the background icon to have padding to it too!I want the background icon to have padding to it too!I want the background icon to have padding to it too!</p>
_x000D_
_x000D_
_x000D_

Original Answer:

you can fake it with a 10px border of the same color as the background:

http://jsbin.com/eparad/edit#javascript,html,live

#hello {
   border: 10px solid #e8e8e8;
   background-color: green;
   background: url("http://www.costascuisine.com/images/buttons/collapseIcon.gif")
               no-repeat scroll right center #e8e8e8;
}

Git commit in terminal opens VIM, but can't get back to terminal

You need to return to normal mode and save the commit message with either

<Esc>:wq

or

<Esc>:x

or

<Esc>ZZ

The Esc key returns you from insert mode to normal mode. The :wq, :x or ZZ sequence writes the changes and exits the editor.

Is there a regular expression to detect a valid regular expression?

Good question.

True regular languages can not decide arbitrarily deeply nested well-formed parenthesis. If your alphabet contains '(' and ')' the goal is to decide if a string of these has well-formed matching parenthesis. Since this is a necessary requirement for regular expressions the answer is no.

However, if you loosen the requirement and add recursion you can probably do it. The reason is that the recursion can act as a stack letting you "count" the current nesting depth by pushing onto this stack.

Russ Cox wrote "Regular Expression Matching Can Be Simple And Fast" which is a wonderful treatise on regex engine implementation.

Javascript foreach loop on associative array object

If the node.js or browser supported Object.entries(), it can be used as an alternative to using Object.keys() (https://stackoverflow.com/a/18804596/225291).

_x000D_
_x000D_
const h = {_x000D_
  a: 1,_x000D_
  b: 2_x000D_
};_x000D_
_x000D_
Object.entries(h).forEach(([key, value]) => console.log(value));_x000D_
// logs 1, 2
_x000D_
_x000D_
_x000D_

in this example, forEach uses Destructuring assignment of an array.

jQuery - get all divs inside a div with class ".container"

Known ID

$(".container > #first");

or

$(".container").children("#first");

or since IDs should be unique within a single document:

$("#first");

The last one is of course the fastest.

Unknown ID

Since you're saying that you don't know their ID top couple of the upper selectors (where #first is written), can be changed to:

$(".container > div");
$(".container").children("div");

The last one (of the first three selectors) that only uses ID is of course not possible to be changed in this way.

If you also need to filter out only those child DIV elements that define ID attribute you'd write selectors down this way:

$(".container > div[id]");
$(".container").children("div[id]");

Attach click handler

Add the following code to attach click handler to any of your preferred selector:

// use selector of your choice and call 'click' on it
$(".container > div").click(function(){
    // if you need element's ID
    var divID = this.id;
    cache your element if you intend to use it multiple times
    var clickedDiv = $(this);
    // add CSS class to it
    clickedDiv.addClass("add-some-class");
    // do other stuff that needs to be done
});

CSS3 Selectors specification

I would also like to point you to CSS3 selector specification that jQuery uses. It will help you lots in the future because there may be some selectors you're not aware of at all and could make your life much much easier.

After your edited question

I'm not completey sure that I know what you're after even though you've written some pseudo code... Anyway. Some parts can still be answered:

$(".container > div[id]").each(function(){
    var context = $(this);
    // get menu parent element: Sub: Show Grid
    // maybe I'm not appending to the correct element here but you should know
    context.appendTo(context.parent().parent());
    context.text("Show #" + this.id);
    context.attr("href", "");
    context.click(function(evt){
        evt.preventDefault();
        $(this).toggleClass("showgrid");
    })
});

the last thee context usages could be combined into a single chained one:

context.text(...).attr(...).click(...);

Regarding DOM elements

You can always get the underlaying DOM element from the jQuery result set.

$(...).get(0)
// or
$(...)[0]

will get you the first DOM element from the jQuery result set. jQuery result is always a set of elements even though there's none in them or only one.

But when I used .each() function and provided an anonymous function that will be called on each element in the set, this keyword actually refers to the DOM element.

$(...).each(function(){
    var DOMelement = this;
    var jQueryElement = $(this);
    ...
});

I hope this clears some things for your.

Debugging with command-line parameters in Visual Studio

In Visual Studio 2010, right click the project, choose Properties, click the configuring properties section on the left pane, then click Debugging, then on the right pane there is a box for command arguments.

In that enter the command line arguments. You are good to go. Now debug and see the result. If you are tired of changing in the properties then temporarily give the input directly in the program.

How to manually force a commit in a @Transactional method?

I had a similar use case during testing hibernate event listeners which are only called on commit.

The solution was to wrap the code to be persistent into another method annotated with REQUIRES_NEW. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.

Tx prop REQUIRES_NEW

Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.

Bootstrap 3 Glyphicons CDN

An alternative would be to use Font-Awesome for icons:

Including Font-Awesome

Open Font-Awesome on CDNJS and copy the CSS url of the latest version:

<link rel="stylesheet" href="<url>">

Or in CSS

@import url("<url>");

For example (note, the version will change):

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

Usage:

<i class="fa fa-bed"></i>

It contains a lot of icons!

Check whether there is an Internet connection available on Flutter app

enter image description here

Full example demonstrating a listener of the internet connectivity and its source.

Credit to : connectivity and Günter Zöchbauer

import 'dart:async';
import 'dart:io';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Map _source = {ConnectivityResult.none: false};
  MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
  }

  @override
  Widget build(BuildContext context) {
    String string;
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.none:
        string = "Offline";
        break;
      case ConnectivityResult.mobile:
        string = "Mobile: Online";
        break;
      case ConnectivityResult.wifi:
        string = "WiFi: Online";
    }

    return Scaffold(
      appBar: AppBar(title: Text("Internet")),
      body: Center(child: Text("$string", style: TextStyle(fontSize: 36))),
    );
  }

  @override
  void dispose() {
    _connectivity.disposeStream();
    super.dispose();
  }
}

class MyConnectivity {
  MyConnectivity._internal();

  static final MyConnectivity _instance = MyConnectivity._internal();

  static MyConnectivity get instance => _instance;

  Connectivity connectivity = Connectivity();

  StreamController controller = StreamController.broadcast();

  Stream get myStream => controller.stream;

  void initialise() async {
    ConnectivityResult result = await connectivity.checkConnectivity();
    _checkStatus(result);
    connectivity.onConnectivityChanged.listen((result) {
      _checkStatus(result);
    });
  }

  void _checkStatus(ConnectivityResult result) async {
    bool isOnline = false;
    try {
      final result = await InternetAddress.lookup('example.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        isOnline = true;
      } else
        isOnline = false;
    } on SocketException catch (_) {
      isOnline = false;
    }
    controller.sink.add({result: isOnline});
  }

  void disposeStream() => controller.close();
}

How to reset the bootstrap modal when it gets closed and open it fresh again?

Just reset any content manually when modal is hidden:

$(".modal").on("hidden.bs.modal", function(){
    $(".modal-body1").html("");
});

There is more events. More about them here

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".modal").on("hidden.bs.modal", function() {_x000D_
    $(".modal-body1").html("Where did he go?!?!?!");_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
  Launch modal_x000D_
</button>_x000D_
_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
  <div class="modal-dialog">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>_x000D_
        </button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <div class='modal-body1'>_x000D_
          <h3>Close and open, I will be gone!</h3>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Transpose a data frame

You can use the transpose function from the data.table library. Simple and fast solution that keeps numeric values as numeric.

library(data.table)

# get data
  data("mtcars")

# transpose
  t_mtcars <- transpose(mtcars)

# get row and colnames in order
  colnames(t_mtcars) <- rownames(mtcars)
  rownames(t_mtcars) <- colnames(mtcars)

How to calculate md5 hash of a file using javascript

To get the hash of files, there are a lot of options. Normally the problem is that it's really slow to get the hash of big files.

I created a little library that get the hash of files, with the 64kb of the start of the file and the 64kb of the end of it.

Live example: http://marcu87.github.com/hashme/ and library: https://github.com/marcu87/hashme

How to change href of <a> tag on button click through javascript

I know its bit old post. Still, it might help some one.

Instead of tag,if possible you can this as well.

 <script type="text/javascript">
        function IsItWorking() {
          // Do your stuff here ...
            alert("YES, It Works...!!!");
        }
    </script>   

    `<asp:HyperLinkID="Link1"NavigateUrl="javascript:IsItWorking();"`            `runat="server">IsItWorking?</asp:HyperLink>`

Any comments on this?

Can I send a ctrl-C (SIGINT) to an application on Windows?

A solution that I have found from here is pretty simple if you have python 3.x available in your command line. First, save a file (ctrl_c.py) with the contents:

import ctypes
import sys

kernel = ctypes.windll.kernel32

pid = int(sys.argv[1])
kernel.FreeConsole()
kernel.AttachConsole(pid)
kernel.SetConsoleCtrlHandler(None, 1)
kernel.GenerateConsoleCtrlEvent(0, 0)
sys.exit(0)

Then call:

python ctrl_c.py 12345

If that doesn't work, I recommend trying out the windows-kill project: https://github.com/alirdn/windows-kill

Iterating over dictionaries using 'for' loops

This will print the output in sorted order by values in ascending order.

d = {'x': 3, 'y': 1, 'z': 2}

def by_value(item):
    return item[1]

for key, value in sorted(d.items(), key=by_value):
    print(key, '->', value)

Output:

y -> 1
z -> 2
x -> 3

Using Exit button to close a winform program

You can also do like this:

private void button2_Click(object sender, EventArgs e)
{
    System.Windows.Forms.Application.ExitThread();
}

I want to remove double quotes from a String

var expressionWithoutQuotes = '';
for(var i =0; i<length;i++){
    if(expressionDiv.charAt(i) != '"'){
        expressionWithoutQuotes += expressionDiv.charAt(i);
    }
}

This may work for you.

Filling a List with all enum values in Java

try

enum E {
    E1, E2, E3
}

public static void main(String[] args) throws Exception {
    List<E> list = Arrays.asList(E.values());
    System.out.println(list);
}

Generate PDF from Swagger API documentation

I created a web site https://www.swdoc.org/ that specifically addresses the problem. So it automates swagger.json -> Asciidoc, Asciidoc -> pdf transformation as suggested in the answers. Benefit of this is that you dont need to go through the installation procedures. It accepts a spec document in form of url or just a raw json. Project is written in C# and its page is https://github.com/Irdis/SwDoc

EDIT

It might be a good idea to validate your json specs here: http://editor.swagger.io/ if you are having any problems with SwDoc, like the pdf being generated incomplete.

How can I open Windows Explorer to a certain directory from within a WPF app?

This should work:

Process.Start(@"<directory goes here>")

Or if you'd like a method to run programs/open files and/or folders:

private void StartProcess(string path)
{
    ProcessStartInfo StartInformation = new ProcessStartInfo();

    StartInformation.FileName = path;

    Process process = Process.Start(StartInformation);

    process.EnableRaisingEvents = true;
}

And then call the method and in the parenthesis put either the directory of the file and/or folder there or the name of the application. Hope this helped!

error: expected primary-expression before ')' token (C)

You should create a variable of the type SelectionneNonSelectionne.

struct SelectionneNonSelectionne var;

After that pass that variable to the function like

characterSelection(screen, var);

The error is caused since you are passing the type name SelectionneNonSelectionne

How can I unstage my files again after making a local commit?

Use:

git reset HEAD^

That does a "mixed" reset by default, which will do what you asked; put foo.java in unstaged, removing the most recent commit.

Converting string to number in javascript/jQuery

var votevalue = $.map($(this).data('votevalue'), Number);

Dynamic type languages versus static type languages

The ability of the interpreter to deduce type and type conversions makes development time faster, but it also can provoke runtime failures which you just cannot get in a statically typed language where you catch them at compile time. But which one's better (or even if that's always true) is hotly discussed in the community these days (and since a long time).

A good take on the issue is from Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages by Erik Meijer and Peter Drayton at Microsoft:

Advocates of static typing argue that the advantages of static typing include earlier detection of programming mistakes (e.g. preventing adding an integer to a boolean), better documentation in the form of type signatures (e.g. incorporating number and types of arguments when resolving names), more opportunities for compiler optimizations (e.g. replacing virtual calls by direct calls when the exact type of the receiver is known statically), increased runtime efficiency (e.g. not all values need to carry a dynamic type), and a better design time developer experience (e.g. knowing the type of the receiver, the IDE can present a drop-down menu of all applicable members). Static typing fanatics try to make us believe that “well-typed programs cannot go wrong”. While this certainly sounds impressive, it is a rather vacuous statement. Static type checking is a compile-time abstraction of the runtime behavior of your program, and hence it is necessarily only partially sound and incomplete. This means that programs can still go wrong because of properties that are not tracked by the type-checker, and that there are programs that while they cannot go wrong cannot be type-checked. The impulse for making static typing less partial and more complete causes type systems to become overly complicated and exotic as witnessed by concepts such as “phantom types” [11] and “wobbly types” [10]. This is like trying to run a marathon with a ball and chain tied to your leg and triumphantly shouting that you nearly made it even though you bailed out after the first mile.

Advocates of dynamically typed languages argue that static typing is too rigid, and that the softness of dynamically languages makes them ideally suited for prototyping systems with changing or unknown requirements, or that interact with other systems that change unpredictably (data and application integration). Of course, dynamically typed languages are indispensable for dealing with truly dynamic program behavior such as method interception, dynamic loading, mobile code, runtime reflection, etc. In the mother of all papers on scripting [16], John Ousterhout argues that statically typed systems programming languages make code less reusable, more verbose, not more safe, and less expressive than dynamically typed scripting languages. This argument is parroted literally by many proponents of dynamically typed scripting languages. We argue that this is a fallacy and falls into the same category as arguing that the essence of declarative programming is eliminating assignment. Or as John Hughes says [8], it is a logical impossibility to make a language more powerful by omitting features. Defending the fact that delaying all type-checking to runtime is a good thing, is playing ostrich tactics with the fact that errors should be caught as early in the development process as possible.

Enumerations on PHP

The top answer above is fantastic. However, if you extend it in two different ways, then whichever extension is done first results in a call to the functions will create the cache. This cache will then be used by all subsequent calls, no matter whichever extension the calls are initiated by ...

To solve this, replace the variable and first function with:

private static $constCacheArray = null;

private static function getConstants() {
    if (self::$constCacheArray === null) self::$constCacheArray = array();

    $calledClass = get_called_class();
    if (!array_key_exists($calledClass, self::$constCacheArray)) {
        $reflect = new \ReflectionClass($calledClass);
        self::$constCacheArray[$calledClass] = $reflect->getConstants();
    }

    return self::$constCacheArray[$calledClass];
}

Convert bytes to int?

int.from_bytes( bytes, byteorder, *, signed=False )

doesn't work with me I used function from this website, it works well

https://coderwall.com/p/x6xtxq/convert-bytes-to-int-or-int-to-bytes-in-python

def bytes_to_int(bytes):
    result = 0
    for b in bytes:
        result = result * 256 + int(b)
    return result

def int_to_bytes(value, length):
    result = []
    for i in range(0, length):
        result.append(value >> (i * 8) & 0xff)
    result.reverse()
    return result

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

I've recently stumbled upon the following solution to this problem:

Source: Multiple versions of Chrome

...this is registry data problem: How to do it then (this is an example for 2.0.172.39 and 3.0.197.11, I'll try it with next versions as they will come, let's assume I've started with Chrome 2):

  1. Install Chrome 2, you'll find it Application Data folder, since I'm from Czech Republic and my name is Bronislav Klucka the path looks like this:

    C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome
    

    and run Chrome

  2. Open registry and save

    [HKEY_CURRENT_USER\Software\Google\Update\Clients\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
    [HKEY_CURRENT_USER\Software\Google\Update\ClientState\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
    

    keys, put them into one chrome2.reg file and copy this file next to chrome.exe (ChromeDir\Application)

  3. Rename Chrome folder to something else (e.g. Chrome2)

  4. Install Chrome 3, it will install to Chrome folder again and run Chrome

  5. Save the same keys (there are changes due to different version) and save it to the chrome3.reg file next to chrome.exe file of this new version again
  6. Rename the folder again (e.g. Chrome3)

    the result would be that there is no Chrome dir (only Chrome2 and Chrome3)

  7. Go to the Application folder of Chrome2, create chrome.bat file with this content:

    @echo off
    regedit /S chrome2.reg
    START chrome.exe -user-data-dir="C:\Docume~1\Bronis~1\LocalS~1\Dataap~1\Google\Chrome2\User Data"
    rem START chrome.exe -user-data-dir="C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome2\User Data"
    

    the first line is generic batch command, the second line will update registry with the content of chrome2.reg file, the third lines starts Chrome pointing to passed directory, the 4th line is commented and will not be run.

    Notice short name format passed as -user-data-dir parameter (the full path is at the 4th line), the problem is that Chrome using this parameter has a problem with diacritics (Czech characters)

  8. Do 7. again for Chrome 3, update paths and reg file name in bat file for Chrome 3

Try running both bat files, seems to be working, both versions of Chrome are running simultaneously.

Updating: Running "About" dialog displays correct version, but an error while checking for new one. To correct that do (I'll explain form Chrome2 folder): 1. rename Chrome2 to Chrome 2. Go to Chrome/Application folder 3. run chrome2.reg file 4. run chrome.exe (works the same for Chrome3) now the version checking works. There has been no new version of Chrome since I've find this whole solution up. But I assume that update will be downloaded to this folder so all you need to do is to update reg file after update and rename Chrome folder back to Chrome2. I'll update this post after successful Chrome update.

Bronislav Klucka

Twig for loop for arrays with keys

I found the answer :

{% for key,value in array_path %}
    Key : {{ key }}
    Value : {{ value }}
{% endfor %}

LEFT function in Oracle

I've discovered that LEFT and RIGHT are not supported functions in Oracle. They are used in SQL Server, MySQL, and some other versions of SQL. In Oracle, you need to use the SUBSTR function. Here are simple examples:

LEFT ('Data', 2) = 'Da'

->   SUBSTR('Data',1,2) = 'Da'

RIGHT ('Data', 2) = 'ta'

->   SUBSTR('Data',-2,2) = 'ta'

Notice that a negative number counts back from the end.

Best way to resolve file path too long exception

Not mention so far and an update, there is a very well establish library for handling paths that are too long. AlphaFS is a .NET library providing more complete Win32 file system functionality to the .NET platform than the standard System.IO classes. The most notable deficiency of the standard .NET System.IO is the lack of support of advanced NTFS features, most notably extended length path support (eg. file/directory paths longer than 260 characters).

What's the best way to get the current URL in Spring MVC?

in jsp file:

request.getAttribute("javax.servlet.forward.request_uri")

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

Reading a resource file from within jar

I have found a fix

BufferedReader br = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream(path)));

Replace "Main" with the java class you coded it in. replace "path" with the path within the jar file.

for example, if you put State1.txt in the package com.issac.state, then type the path as "/com/issac/state/State1" if you run Linux or Mac. If you run Windows then type the path as "\com\issac\state\State1". Don't add the .txt extension to the file unless the File not found exception occurs.

MVC 4 Razor File Upload

View Page

@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
 { 
   <input type="file" name="file" />
   <input type="submit" value="Upload" class="save" id="btnid" />
 }

script file

$(document).on("click", "#btnid", function (event) {
        event.preventDefault();
        var fileOptions = {
            success: res,
            dataType: "json"
        }
        $("#formid").ajaxSubmit(fileOptions);
    });

In Controller

    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {

    }

Good Linux (Ubuntu) SVN client

As a developer, I use eclipse + sub-eclipse client (Assuming that you are using svn to checkout some development project and you will compile them).

most people don't spend much time with svn operation, and command line is the fastest way to do so.

there is also some nice GUI tools :

http://rabbitvcs.org/

or

http://www.harecoded.com/nautilus-subversion-integration-tool-execute-svn-commands-with-gnome-scripts-96355

How do I tell if .NET 3.5 SP1 is installed?

You could go to SmallestDotNet using IE from the server. That will tell you the version and also provide a download link if you're out of date.

How do I use the built in password reset/change views with my own templates

If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.

The b-list has a good introduction to context processors.

Edit (I seem to have been confused about what the actual question was):

You'll notice that password_reset takes a named parameter called template_name:

def password_reset(request, is_admin_site=False, 
            template_name='registration/password_reset_form.html',
            email_template_name='registration/password_reset_email.html',
            password_reset_form=PasswordResetForm, 
            token_generator=default_token_generator,
            post_reset_redirect=None):

Check password_reset for more information.

... thus, with a urls.py like:

from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset

urlpatterns = patterns('',
     (r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
     ...
)

django.contrib.auth.views.password_reset will be called for URLs matching '/accounts/password/reset' with the keyword argument template_name = 'my_templates/password_reset.html'.

Otherwise, you don't need to provide any context as the password_reset view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax error and look through the stack trace find the frame with a local variable named context. If you want to modify the context then what I said above about context processors is probably the way to go.

In summary: what do you need to do to use your own template? Provide a template_name keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.

Shell Script — Get all files modified after <date>

as simple as:

find . -mtime -1 | xargs tar --no-recursion -czf myfile.tgz

where find . -mtime -1 will select all the files in (recursively) current directory modified day before. you can use fractions, for example:

find . -mtime -1.5 | xargs tar --no-recursion -czf myfile.tgz

How can I check the size of a collection within a Django template?

I need the collection length to decide whether I should render table <thead></thead>

but don't know why @Django 2.1.7 the chosen answer will fail(empty) my forloop afterward.

I got to use {% if forloop.first %} {% endif %} to overcome:

<table>
    {% for record in service_list %}
        {% if forloop.first %}
            <thead>
            <tr>
                <th>??</th>
            </tr>
            </thead>
        {% endif %}
        <tbody>
        <tr>
            <td>{{ record.date }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

Will iOS launch my app into the background if it was force-quit by the user?

For iOS13

For background pushes in iOS13, you must set below parameters:

apns-priority = 5
apns-push-type = background
//Required for WatchOS
//Highly recommended for Other platforms 

Background PUSHES The video link: https://developer.apple.com/videos/play/wwdc2019/707/

Refresh DataGridView when updating data source

Well, it doesn't get much better than that. Officially, you should use

dataGridView1.DataSource = typeof(List); 
dataGridView1.DataSource = itemStates;

It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.

Target a css class inside another css class

Not certain what the HTML looks like (that would help with answers). If it's

<div class="testimonials content">stuff</div>

then simply remove the space in your css. A la...

.testimonials.content { css here }

UPDATE:

Okay, after seeing HTML see if this works...

.testimonials .wrapper .content { css here }

or just

.testimonials .wrapper { css here }

or

.desc-container .wrapper { css here }

all 3 should work.

Align text in a table header

HTML:

<tr>
    <th>Language</th>
    <th>Skill Level</th>
    <th>&nbsp;</th>
</tr>

CSS:

tr, th {
    padding: 10px;
    text-align: center;
}