Programs & Examples On #Encapsulation

In OOP, mechanism for restricting access to some of the object's components or a design principle encouraging decoupling from implementation details.

Difference between Encapsulation and Abstraction

Let me explain it in with the same example discussed above. Kindly consider the same TV.

Encapsulation: The adjustments we can make with the remote is a good example - Volume UP/DOWN, Color & Contrast - All we can do is adjust it to the min and max value provided and cannot do anything beyond what is provided in the remote - Imagine the getter and setter here(The setter function will check whether the value provided is valid if Yes, it process the operation if not won't allow us to make changes - like we cannot decrease the volume beyond zero even we press the volume down button a hundred times).

Abstraction: We can take the same example here but with a higher Degree/Context. The volume down button will decrease the volume - and this is the info we provide to the user and the user is not aware of neither the infrared transmitter inside the remote nor the receiver in the TV and the subsequent process of parsing the signal and the microprocessor architecture inside the TV. Simply put it is not needed in the context - Just provide what is necessary. One can easily relate the Text book definition here ie., Hiding the inner implementation and only providing what it will do rather than how it do that!

Hope it clarifies a bit!

Difference between private, public, and protected inheritance

It's essentially the access protection of the public and protected members of the base class in the derived class. With public inheritance, the derived class can see public and protected members of the base. With private inheritance, it can't. With protected, the derived class and any classes derived from that can see them.

What's the difference between abstraction and encapsulation?

Abstraction has to do with separating interface from implementation. (We don't care what it is, we care that it works a certain way.)

Encapsulation has to do with disallowing access to or knowledge of internal structures of an implementation. (We don't care or need to see how it works, only that it does.)

Some people do use encapsulation as a synonym for abstraction, which is (IMO) incorrect. It's possible that your interviewer thought this. If that is the case then you were each talking about two different things when you referred to "encapsulation."


It's worth noting that these concepts are represented differently in different programming languages. A few examples:

  • In Java and C#, interfaces (and, to some degree, abstract classes) provide abstraction, while access modifiers provide encapsulation.
  • It's mostly the same deal in C++, except that we don't have interfaces, we only have abstract classes.
  • In JavaScript, duck typing provides abstraction, and closure provides encapsulation. (Naming convention can also provide encapsulation, but this only works if all parties agree to follow it.)

Set and Get Methods in java?

I want to add to other answers that setters can be used to prevent putting the object in an invalid state.

For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:

private String taxId;

public void setTaxId(String taxId) {
    this.taxId = taxId;
}

However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:

private String taxId;

public void setTaxId(String taxId) throws IllegalArgumentException {
    if (isTaxIdValid(taxId)) {
        throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
    }
    this.taxId = taxId;
}

The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.

private final TaxId taxId = new TaxId()

public void setTaxId(String taxIdString) throws IllegalArgumentException {
    taxId.set(taxIdString); //will throw exception if not valid
}

Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:

public String getTaxId() throws IllegalStateException {
    return taxId.get(); //will throw exception if not set
}

Difference between abstraction and encapsulation?

Abstraction: Only necessary information is shown. Let's focus on the example of switching on a computer. The user does not have to know what goes on while the system is still loading (that information is hidden from the user).

Let's take another example, that of the ATM. The customer does not need to know how the machine reads the PIN and processes the transaction, all he needs to do is enter the PIN, take the cash and leave.

Encapsulation: Deals with hiding the sensitive data of a clas hence privatising part of it. It is a way of keeping some information private to its clients by allowing no access to it from outside.

When should you use 'friend' in C++?

Friend functions and classes provide direct access to private and protected members of class to avoid breaking encapsulation in the general case. Most usage is with ostream: we would like to be able to type:

Point p;
cout << p;

However, this may require access to the private data of Point, so we define the overloaded operator

friend ostream& operator<<(ostream& output, const Point& p);

There are obvious encapsulation implications, however. First, now the friend class or function has full access to ALL members of the class, even ones that do not pertain to its needs. Second, the implementations of the class and the friend are now enmeshed to the point where an internal change in the class can break the friend.

If you view the friend as an extension of the class, then this is not an issue, logically speaking. But, in that case, why was it necessary to spearate out the friend in the first place.

To achieve the same thing that 'friends' purport to achieve, but without breaking encapsulation, one can do this:

class A
{
public:
    void need_your_data(B & myBuddy)
    {
        myBuddy.take_this_name(name_);
    }
private:
    string name_;
};

class B
{
public:
    void print_buddy_name(A & myBuddy)
    {
        myBuddy.need_your_data(*this);
    }
    void take_this_name(const string & name)
    {
        cout << name;
    }
}; 

Encapsulation is not broken, class B has no access to the internal implementation in A, yet the result is the same as if we had declared B a friend of A. The compiler will optimize away the function calls, so this will result in the same instructions as direct access.

I think using 'friend' is simply a shortcut with arguable benefit, but definite cost.

Why are Python's 'private' methods not actually private?

Similar behavior exists when module attribute names begin with a single underscore (e.g. _foo).

Module attributes named as such will not be copied into an importing module when using the from* method, e.g.:

from bar import *

However, this is a convention and not a language constraint. These are not private attributes; they can be referenced and manipulated by any importer. Some argue that because of this, Python can not implement true encapsulation.

Abstraction VS Information Hiding VS Encapsulation

Abstraction allows you to treat a complex process as a simple process. For example, the standard "file" abstraction treats files as a contiguous array of bytes. The user/developer does not even have to think about issues of clusters and fragmentation. (Abstraction normally appears as classes or subroutines.)

Information hiding is about protecting your abstractions from malicious/incompetent users. By restricting control of some state (hard drive allocations, for example) to the original developer, huge amounts of error handling becomes redundant. If nobody else besides the file system driver can write to the hard drive, then the file system driver knows exactly what has been written to the hard drive and where. (The usual manifestation of this concept is private and protected keywords in OO languages.)

Simple way to understand Encapsulation and Abstraction

Abstraction is like using a computer.

You have absolutely no idea what's going on with it beyond what you see with the GUI (graphical user interface) and external hardware (e.g. screen). All those pretty colors and such. You're only presented the details relevant to you as a generic consumer.

Encapsulation is the actual act of hiding the irrelevant details.

You use your computer, but you don't see what its CPU (central processing unit) looks like (unless you try to break into it). It's hidden (or encapsulated) behind all that chrome and plastic.

In the context of OOP (object-oriented programming) languages, you usually have this kind of setup:

CLASS {
  METHOD { 
    *the actual code*
  }
}

An example of "encapsulation" would be having a METHOD that the regular user can't see (private). "Abstraction" is the regular user using the METHOD that they can (public) in order to use the private one.

How abstraction and encapsulation differ?

I think of it this way, encapsulation is hiding the way something gets done. This can be one or many actions.

Abstraction is related to "why" I am encapsulating it the first place.

I am basically telling the client "You don't need to know much about how I process the payment and calculate shipping, etc. I just want you to tell me you want to 'Checkout' and I will take care of the details for you."

This way I have encapsulated the details by generalizing (abstracting) into the Checkout request.

I really think that abstracting and encapsulation go together.

How to access private data members outside the class without making "friend"s?

http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html

this guy's blog shows you how to do it using templates. With some modifications, you can adapt this method to access a private data member, although I found it tricky despite having 10+ years experience.

I wanted to point out like everyone else, that there is an extremely few number of cases where doing this is legitimate. However, I want to point out one: I was writing unit tests for a software suite. A federal regulatory agency requires every single line of code to be exercised and tested, without modifying the original code. Due to (IMHO) poor design, a static constant was in the 'private' section, but I needed to use it in the unit test. So the method seemed to me like the best way to do it.

I'm sure the way could be simplified, and I'm sure there are other ways. I'm not posting this for the OP, since it's been 5 months, but hopefully this will be useful to some future googler.

Good way to encapsulate Integer.parseInt()

To avoid handling exceptions use a regular expression to make sure you have all digits first:

//Checking for Regular expression that matches digits
if(value.matches("\\d+")) {
     Integer.parseInt(value);
}

ERROR Error: No value accessor for form control with unspecified name attribute on switch

I also had the same error , angular 7

 <button (click)="Addcity(city.name)" [(ngModel)]="city.name"  class="dropdown-item fontstyle"
     *ngFor="let city of Cities; let i = index">
      {{city.name}}
 </button>

I just added ngDefaultControl

   <button (click)="Addcity(city.name)" [(ngModel)]="city.name"  ngDefaultControl class="dropdown-item fontstyle"
 *ngFor="let city of Cities; let i = index">
  {{city.name}}

Creating a procedure in mySql with parameters

I figured it out now. Here's the correct answer

CREATE PROCEDURE checkUser 
(
   brugernavn1 varchar(64),
   password varchar(64)
) 
BEGIN 
   SELECT COUNT(*) FROM bruger 
   WHERE bruger.brugernavn=brugernavn1 
   AND bruger.pass=password; 
END; 

@ points to a global var in mysql. The above syntax is correct.

Importing Maven project into Eclipse

I am not experienced with Eclipse or Maven so the other answers seemed a bit over complicated.

The following simpler set of steps worked for me:

Prerequisite: Make sure you have Maven plugin installed in your Eclipse IDE: How to add Maven plugin to Eclipse

  1. Open Eclipse
  2. Click File > Import
  3. Type Maven in the search box under Select an import source:
  4. Select Existing Maven Projects
  5. Click Next
  6. Click Browse and select the folder that is the root of the Maven project (probably contains the pom.xml file)
  7. Click Next
  8. Click Finish

VBA code to set date format for a specific column as "yyyy-mm-dd"

It works, when you use both lines:

Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"

Bitwise operation and usage

Whilst manipulating bits of an integer is useful, often for network protocols, which may be specified down to the bit, one can require manipulation of longer byte sequences (which aren't easily converted into one integer). In this case it is useful to employ the bitstring library which allows for bitwise operations on data - e.g. one can import the string 'ABCDEFGHIJKLMNOPQ' as a string or as hex and bit shift it (or perform other bitwise operations):

>>> import bitstring
>>> bitstring.BitArray(bytes='ABCDEFGHIJKLMNOPQ') << 4
BitArray('0x142434445464748494a4b4c4d4e4f50510')
>>> bitstring.BitArray(hex='0x4142434445464748494a4b4c4d4e4f5051') << 4
BitArray('0x142434445464748494a4b4c4d4e4f50510')

SQL: Select columns with NULL values only

SELECT cols
FROM table
WHERE cols IS NULL

JavaScript REST client Library

You can also use mvc frameworks like Backbone.js that will provide a javascript model of the data. Changes to the model will be translated into REST calls.

Getter and Setter declaration in .NET

1st

string _myProperty { get; set; }

This is called an Auto Property in the .NET world. It's just syntactic sugar for #2.

2nd

string _myProperty;

public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

This is the usual way to do it, which is required if you need to do any validation or extra code in your property. For example, in WPF if you need to fire a Property Changed Event. If you don't, just use the auto property, it's pretty much standard.

3

string _myProperty;

public string getMyProperty()
{
    return this._myProperty;
}

public string setMyProperty(string value)
{
    this._myProperty = value;
}

The this keyword here is redundant. Not needed at all. These are just Methods that get and set as opposed to properties, like the Java way of doing things.

Create a custom View by inflating a layout?

Here is a simple demo to create customview (compoundview) by inflating from xml

attrs.xml

<resources>

    <declare-styleable name="CustomView">
        <attr format="string" name="text"/>
        <attr format="reference" name="image"/>
    </declare-styleable>
</resources>

CustomView.kt

class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
        ConstraintLayout(context, attrs, defStyleAttr) {

    init {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        View.inflate(context, R.layout.custom_layout, this)

        val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
        try {
            val text = ta.getString(R.styleable.CustomView_text)
            val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
            if (drawableId != 0) {
                val drawable = AppCompatResources.getDrawable(context, drawableId)
                image_thumb.setImageDrawable(drawable)
            }
            text_title.text = text
        } finally {
            ta.recycle()
        }
    }
}

custom_layout.xml

We should use merge here instead of ConstraintLayout because

If we use ConstraintLayout here, layout hierarchy will be ConstraintLayout->ConstraintLayout -> ImageView + TextView => we have 1 redundant ConstraintLayout => not very good for performance

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:parentTag="android.support.constraint.ConstraintLayout">

    <ImageView
        android:id="@+id/image_thumb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="ContentDescription"
        tools:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/text_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="@id/image_thumb"
        app:layout_constraintStart_toStartOf="@id/image_thumb"
        app:layout_constraintTop_toBottomOf="@id/image_thumb"
        tools:text="Text" />

</merge>

Using activity_main.xml

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

    <your_package.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#f00"
        app:image="@drawable/ic_android"
        app:text="Android" />

    <your_package.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0f0"
        app:image="@drawable/ic_adb"
        app:text="ADB" />

</LinearLayout>

Result

enter image description here

Github demo

Extract data from log file in specified range of time

You can use this for getting current and log times:

#!/bin/bash

log="log_file_name"
while read line
do
  current_hours=`date | awk 'BEGIN{FS="[ :]+"}; {print $4}'`
  current_minutes=`date | awk 'BEGIN{FS="[ :]+"}; {print $5}'`
  current_seconds=`date | awk 'BEGIN{FS="[ :]+"}; {print $6}'`

  log_file_hours=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print  $7}'`
  log_file_minutes=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print  $8}'`
  log_file_seconds=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print  $9}'`    
done < $log

And compare log_file_* and current_* variables.

How to combine class and ID in CSS selector?

use: tag.id ; tag#classin the tag variables in your css.

LaTeX: Multiple authors in a two-column article

What about using a tabular inside \author{}, just like in IEEE macros:

\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c} 
I. M. Author  & M. Y. Coauthor \\
My Department & Coauthor Department \\ 
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle    
\end{document}

This will produce two columns authors with any documentclass.

Results:

enter image description here

Parsing ISO 8601 date in Javascript

Looks like moment.js is the most popular and with active development:

moment("2010-01-01T05:06:07", moment.ISO_8601);

Why am I getting InputMismatchException?

Here you can see the nature of Scanner:

double nextDouble()

Returns the next token as a double. If the next token is not a float or is out of range, InputMismatchException is thrown.

Try to catch the exception

try {
    // ...
} catch (InputMismatchException e) {
    System.out.print(e.getMessage()); //try to find out specific reason.
}

UPDATE

CASE 1

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

CASE 2

You have entered something, which is out of range as I have mentioned above.

I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

import java.util.*;

public class Test {
    public static void main(String... args) {
        new Test().askForMarks(5);
    }

    public void askForMarks(int student) {
        double marks[] = new double[student];
        int index = 0;
        Scanner reader = new Scanner(System.in);
        while (index < student) {
            System.out.print("Please enter a mark (0..30): ");
            marks[index] = (double) checkValueWithin(0, 30); 
            index++;
        }
    }

    public double checkValueWithin(int min, int max) {
        double num;
        Scanner reader = new Scanner(System.in);
        num = reader.nextDouble();                         
        while (num < min || num > max) {                 
            System.out.print("Invalid. Re-enter number: "); 
            num = reader.nextDouble();                         
        } 

        return num;
    }
}

As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.

Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).

How to connect to LocalDB in Visual Studio Server Explorer?

In Visual Studio 2012 all I had to do was enter:

(localdb)\v11.0

Visual Studio 2015 and Visual Studio 2017 changed to:

(localdb)\MSSQLLocalDB

as the server name when adding a Microsoft SQL Server Data source in:

View/Server Explorer/(Right click) Data Connections/Add Connection

and then the database names were populated. I didn't need to do all the other steps in the accepted answer, although it would be nice if the server name was available automatically in the server name combo box.

You can also browse the LocalDB database names available on your machine using:

View/SQL Server Object Explorer.

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

well you need to understand there are always two things the API and the implementation (mind the gradle format of the following code)

compile group:'javax.servlet.jsp.jstl', name:'javax.servlet.jsp.jstl-api', version:'1.2.1'

compile group:'org.glassfish.web', name:'javax.servlet.jsp.jstl',version:'1.2.1'

so If you're using a servlet container with no jstl support then of course it will not provide both of them, a mistake which I made is that I only put the first one, but if you're using full stack application server i.e glassfish then glassfish will have both of them already inside.

CORS with POSTMAN

While all of the answers here are a really good explanation of what cors is but the direct answer to your question would be because of the following differences postman and browser.

Browser: Sends OPTIONS call to check the server type and getting the headers before sending any new request to the API endpoint. Where it checks for Access-Control-Allow-Origin. Taking this into account Access-Control-Allow-Origin header just specifies which all CROSS ORIGINS are allowed, although by default browser will only allow the same origin.

Postman: Sends direct GET, POST, PUT, DELETE etc. request without checking what type of server is and getting the header Access-Control-Allow-Origin by using OPTIONS call to the server.

How to write a PHP ternary operator

To be honest, a ternary operator would only make this worse, what i would suggest if making it simpler is what you are aiming at is:

$groups = array(1=>"Player", 2=>"Gamemaster", 3=>"God");
echo($groups[$result->group_id]);

and then a similar one for your vocations

$vocations = array(
  1=>"Sorcerer",
  2=>"Druid",
  3=>"Paladin",
  4=>"Knight",
  ....
);
echo($vocations[$result->vocation]);

With a ternary operator, you would end up with

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

Which as you can tell, only gets more complicated the more you add to it

How to get a random number between a float range?

if you want generate a random float with N digits to the right of point, you can make this :

round(random.uniform(1,2), N)

the second argument is the number of decimals.

Override valueof() and toString() in Java enum

How about a Java 8 implementation? (null can be replaced by your default Enum)

public static RandomEnum getEnum(String value) {
    return Arrays.stream(RandomEnum.values()).filter(m -> m.value.equals(value)).findAny().orElse(null);
}

Or you could use:

...findAny().orElseThrow(NotFoundException::new);

Access multiple elements of list knowing their index

My answer does not use numpy or python collections.

One trivial way to find elements would be as follows:

a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
c = [i for i in a if i in b]

Drawback: This method may not work for larger lists. Using numpy is recommended for larger lists.

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

You need to use jackson-module-kotlin to deserialize to data classes. See here for details.

The error message above is what Jackson gives you if you try to deserialize some value into a data class when that module isn't enabled or, even if it is, when the ObjectMapper it uses doesn't have the KotlinModule registered. For example, take this code:

data class TestDataClass (val foo: String)

val jsonString = """{ "foo": "bar" }"""
val deserializedValue = ObjectMapper().readerFor(TestDataClass::class.java).readValue<TestDataClass>(jsonString)

This will fail with the following error:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `test.SerializationTests$TestDataClass` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)

If you change the code above and replace ObjectMapper with jacksonObjectMapper (which simply returns a normal ObjectMapper with the KotlinModule registered), it works. i.e.

val deserializedValue = jacksonObjectMapper().readerFor(TestDataClass::class.java).readValue<TestDataClass>(jsonString)

I'm not sure about the Android side of things, but it looks like you'll need to get the system to use the jacksonObjectMapper to do the deserialization.

C++ - how to find the length of an integer

How about (works also for 0 and negatives):

int digits( int x ) { 
    return ( (bool) x * (int) log10( abs( x ) ) + 1 );
}

A non-blocking read on a subprocess.PIPE in Python

This is a example to run interactive command in subprocess, and the stdout is interactive by using pseudo terminal. You can refer to: https://stackoverflow.com/a/43012138/3555925

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import select
import termios
import tty
import pty
from subprocess import Popen

command = 'bash'
# command = 'docker run -it --rm centos /bin/bash'.split()

# save original tty setting then set it to raw mode
old_tty = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())

# open pseudo-terminal to interact with subprocess
master_fd, slave_fd = pty.openpty()

# use os.setsid() make it run in a new process group, or bash job control will not be enabled
p = Popen(command,
          preexec_fn=os.setsid,
          stdin=slave_fd,
          stdout=slave_fd,
          stderr=slave_fd,
          universal_newlines=True)

while p.poll() is None:
    r, w, e = select.select([sys.stdin, master_fd], [], [])
    if sys.stdin in r:
        d = os.read(sys.stdin.fileno(), 10240)
        os.write(master_fd, d)
    elif master_fd in r:
        o = os.read(master_fd, 10240)
        if o:
            os.write(sys.stdout.fileno(), o)

# restore tty settings back
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)

Apply CSS style attribute dynamically in Angular JS

I would say that you should put styles that won't change into a regular style attribute, and conditional/scope styles into an ng-style attribute. Also, string keys are not necessary. For hyphen-delimited CSS keys, use camelcase.

<div ng-style="{backgroundColor: data.backgroundCol}" style="width:20px; height:20px; margin-top:10px; border:solid 1px black;"></div>

How can I tail a log file in Python?

The only portable way to tail -f a file appears to be, in fact, to read from it and retry (after a sleep) if the read returns 0. The tail utilities on various platforms use platform-specific tricks (e.g. kqueue on BSD) to efficiently tail a file forever without needing sleep.

Therefore, implementing a good tail -f purely in Python is probably not a good idea, since you would have to use the least-common-denominator implementation (without resorting to platform-specific hacks). Using a simple subprocess to open tail -f and iterating through the lines in a separate thread, you can easily implement a non-blocking tail operation in Python.

Example implementation:

import threading, Queue, subprocess
tailq = Queue.Queue(maxsize=10) # buffer at most 100 lines

def tail_forever(fn):
    p = subprocess.Popen(["tail", "-f", fn], stdout=subprocess.PIPE)
    while 1:
        line = p.stdout.readline()
        tailq.put(line)
        if not line:
            break

threading.Thread(target=tail_forever, args=(fn,)).start()

print tailq.get() # blocks
print tailq.get_nowait() # throws Queue.Empty if there are no lines to read

Can I add extension methods to an existing static class?

I tried to do this with System.Environment back when I was learning extension methods and was not successful. The reason is, as others mention, because extension methods require an instance of the class.

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

How do I compare two columns for equality in SQL Server?

A solution avoiding CASE WHEN is to use COALESCE.

SELECT
    t1.Col2 AS t1Col2,
    t2.Col2 AS t2Col2,
    COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)) as NULL_IF_SAME
 FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID

NULL_IF_SAME column will give NULL for all rows where t1.col2 = t2.col2 (including NULL). Though this is not more readable than CASE WHEN expression, it is ANSI SQL.

Just for the sake of fun, if one wants to have boolean bit values of 0 and 1 (though it is not very readable, hence not recommended), one can use (which works for all datatypes):

1/ISNULL(LEN(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+2,1) as BOOL_BIT_SAME.

Now if you have one of the numeric data types and want bits, in the above LEN function converts to string first which may be problematic,so instead this should work:

1/(CAST(ISNULL(ABS(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+1,0)as bit)+1) as FAST_BOOL_BIT_SAME_NUMERIC

Above will work for Integers without CAST.

NOTE: also in SQLServer 2012, we have IIF function.

Warning: date_format() expects parameter 1 to be DateTime

This may help

$formattedweddingdate =date('d-m-Y',strtotime($weddingdate));

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

Rotate a div using javascript

To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.

To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.

var rotated = false;

document.getElementById('button').onclick = function() {
    var div = document.getElementById('div'),
        deg = rotated ? 0 : 66;

    div.style.webkitTransform = 'rotate('+deg+'deg)'; 
    div.style.mozTransform    = 'rotate('+deg+'deg)'; 
    div.style.msTransform     = 'rotate('+deg+'deg)'; 
    div.style.oTransform      = 'rotate('+deg+'deg)'; 
    div.style.transform       = 'rotate('+deg+'deg)'; 

    rotated = !rotated;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

To add some animation to the rotation all we have to do is add CSS transitions

div {
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript

document.getElementById('button').onclick = function() {
    document.getElementById('div').classList.toggle('rotated');
}

_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
    -webkit-transform : rotate(66deg); _x000D_
    -moz-transform : rotate(66deg); _x000D_
    -ms-transform : rotate(66deg); _x000D_
    -o-transform : rotate(66deg); _x000D_
    transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

Bootstrap - 5 column layout

.col-xs-2{
    background:#00f;
    color:#FFF;
}
.col-half-offset{
    margin-left:4.166666667%
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
    <div class="row" style="border: 1px solid red">
        <div class="col-xs-4" id="p1">One</div>
        <div class="col-xs-4 col-half-offset" id="p2">Two</div>
        <div class="col-xs-4 col-half-offset" id="p3">Three</div>
        <div>Test</div>
    </div>
</div>

IsNothing versus Is Nothing

VB is full of things like that trying to make it both "like English" and comfortable for people who are used to languages that use () and {} a lot. And on the other side, as you already probably know, most of the time you can use () with function calls if you want to, but don't have to.

I prefer IsNothing()... but I use C and C#, so that's just what is comfortable. And I think it's more readable. But go with whatever feels more comfortable to you.

Can't install nuget package because of "Failed to initialize the PowerShell host"

This issue is not always related to the PowerShell Execution Policy. My machine is configured as "Unrestricted" for both PowerShell x64 and x86, but I still get this error message from times to times in Visual Studio 2013.

When I try to open the Package Manager Console:

Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of Unrestricted. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more information please see "Get-Help Set-ExecutionPolicy".

This is not a valid error message.

Rebooting Visual Studio does not always resolve the problem.

Running the process as an admin never resolves the problem.

Like Declan, the latest update of the Package Manager plugin fixed the issue: 2.8.60723.765

How can I center text (horizontally and vertically) inside a div block?

If it is one line of text and/or image, then it is easy to do. Just use:

text-align: center;
vertical-align: middle;
line-height: 90px;       /* The same as your div height */

That's it. If it can be multiple lines, then it is somewhat more complicated. But there are solutions on http://pmob.co.uk/. Look for "vertical align".

Since they tend to be hacks or adding complicated divs... I usually use a table with a single cell to do it... to make it as simple as possible.


Update for 2020:

Unless you need make it work on earlier browsers such as Internet Explorer 10, you can use flexbox. It is widely supported by all current major browsers. Basically, the container needs to be specified as a flex container, together with centering along its main and cross axis:

#container {
  display: flex;
  justify-content: center;
  align-items: center;
}

To specify a fixed width for the child, which is called a "flex item":

#content {
  flex: 0 0 120px;
}

Example: http://jsfiddle.net/2woqsef1/1/

To shrink-wrap the content, it is even simpler: just remove the flex: ... line from the flex item, and it is automatically shrink-wrapped.

Example: http://jsfiddle.net/2woqsef1/2/

The examples above have been tested on major browsers including MS Edge and Internet Explorer 11.

One technical note if you need to customize it: inside of the flex item, since this flex item is not a flex container itself, the old non-flexbox way of CSS works as expected. However, if you add an additional flex item to the current flex container, the two flex items will be horizontally placed. To make them vertically placed, add the flex-direction: column; to the flex container. This is how it works between a flex container and its immediate child elements.

There is an alternative method of doing the centering: by not specifying center for the distribution on the main and cross axis for the flex container, but instead specify margin: auto on the flex item to take up all extra space in all four directions, and the evenly distributed margins will make the flex item centered in all directions. This works except when there are multiple flex items. Also, this technique works on MS Edge but not on Internet Explorer 11.


Update for 2016 / 2017:

It can be more commonly done with transform, and it works well even in older browsers such as Internet Explorer 10 and Internet Explorer 11. It can support multiple lines of text:

position: relative;
top: 50%;
transform: translateY(-50%);

Example: https://jsfiddle.net/wb8u02kL/1/

To shrink-wrap the width:

The solution above used a fixed width for the content area. To use a shrink-wrapped width, use

position: relative;
float: left;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Example: https://jsfiddle.net/wb8u02kL/2/

If the support for Internet Explorer 10 is needed, then flexbox won't work and the method above and the line-height method would work. Otherwise, flexbox would do the job.

Fit background image to div

background-position-x: center;
background-position-y: center;

Link a .css on another folder

I think what you want to do is

_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="font/font-face/my-font-face.css">
_x000D_
_x000D_
_x000D_

Java - Opposite of .contains (does not contain)

Maybe

if (inventory.contains("bread") && !inventory.contains("water"))

Or

if (inventory.contains("bread")) {
    if (!inventory.contains("water")) {
        // do something here
    } 
}

What does <![CDATA[]]> in XML mean?

CDATA stands for Character Data. You can use this to escape some characters which otherwise will be treated as regular XML. The data inside this will not be parsed. For example, if you want to pass a URL that contains & in it, you can use CDATA to do it. Otherwise, you will get an error as it will be parsed as regular XML.

How to add a margin to a table row <tr>

You can create space between table rows by adding an empty row of cells like this...

<tr><td></td><td></td></tr>

CSS can then be used to target the empty cells like this…

table :empty{border:none; height:10px;}

NB: This technique is only good if none of your normal cells will be empty/vacant.

Even a non-breaking space will do to avoid a cell from being targetted by the CSS rule above.

Needless to mention that you can adjust the space's height to whatever you like with the height property included.

Render Content Dynamically from an array map function in React Native

Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}

Vue.js: Conditional class style binding

<i class="fa" v-bind:class="cravings"></i>

and add in computed :

computed: {
    cravings: function() {
        return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
    }
}

How can I start and check my MySQL log?

For me, general_log didn't worked. But adding this to my.ini worked

[mysqld]
log-output=FILE
slow_query_log = 1
slow_query_log_file = "d:/temp/developer.log"

How to add a classname/id to React-Bootstrap Component?

If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

How to create a List with a dynamic object type

It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.

Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.

DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj

...

The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.

var DyObjectsList = new List<dynamic>; 
if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true; 
    DyObj.Message = "Message 1"; 
    DyObjectsList .Add(DyObj); 
} 
if (condition2) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false; 
    DyObj.Message = "Message 2"; 
    DyObjectsList .Add(DyObj); 
} 

your resulting List essentially looks like this

DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj

Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.

However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.

How to shift a column in Pandas DataFrame

Lets define the dataframe from your example by

>>> df = pd.DataFrame([[206, 214], [226, 234], [245, 253], [265, 272], [283, 291]], 
    columns=[1, 2])
>>> df
     1    2
0  206  214
1  226  234
2  245  253
3  265  272
4  283  291

Then you could manipulate the index of the second column by

>>> df[2].index = df[2].index+1

and finally re-combine the single columns

>>> pd.concat([df[1], df[2]], axis=1)
       1      2
0  206.0    NaN
1  226.0  214.0
2  245.0  234.0
3  265.0  253.0
4  283.0  272.0
5    NaN  291.0

Perhaps not fast but simple to read. Consider setting variables for the column names and the actual shift required.

Edit: Generally shifting is possible by df[2].shift(1) as already posted however would that cut-off the carryover.

Variable that has the path to the current ansible-playbook that is executing?

There don't seem to be a variable which holds exactly what you want.

However, quoting the docs:

Also available, inventory_dir is the pathname of the directory holding Ansible’s inventory host file, inventory_file is the pathname and the filename pointing to the Ansible’s inventory host file.

playbook_dir contains the playbook base directory.

And finally, role_path will return the current role’s pathname (since 1.8). This will only work inside a role.

Dependent on your setup, those or the $ pwd -based solution might be enough.

How to modify existing, unpushed commit messages?

You can use git-rebase-reword

It is designed to edit any commit (not just last) same way as commit --amend

$ git rebase-reword <commit-or-refname>

It is named after the action on rebase interactive to amend a commit: "reword". See this post and man -section interactive mode-

Examples:

$ git rebase-reword b68f560
$ git rebase-reword HEAD^

Converting String to Int using try/except in Python

You can do :

try : 
   string_integer = int(string)
except ValueError  :
   print("This string doesn't contain an integer")

find the array index of an object with a specific key value in underscore

Keepin' it simple:

// Find the index of the first element in array
// meeting specified condition.
//
var findIndex = function(arr, cond) {
  var i, x;
  for (i in arr) {
    x = arr[i];
    if (cond(x)) return parseInt(i);
  }
};

var idIsTwo = function(x) { return x.id == 2 }
var tv = [ {id: 1}, {id: 2} ]
var i = findIndex(tv, idIsTwo) // 1

Or, for non-haters, the CoffeeScript variant:

findIndex = (arr, cond) ->
  for i, x of arr
    return parseInt(i) if cond(x)

What does "\r" do in the following script?

'\r' means 'carriage return' and it is similar to '\n' which means 'line break' or more commonly 'new line'

in the old days of typewriters, you would have to move the carriage that writes back to the start of the line, and move the line down in order to write onto the next line.

in the modern computer era we still have this functionality for multiple reasons. but mostly we use only '\n' and automatically assume that we want to start writing from the start of the line, since it would not make much sense otherwise.

however, there are some times when we want to use JUST the '\r' and that would be if i want to write something to an output, and the instead of going down to a new line and writing something else, i want to write something over what i already wrote, this is how many programs in linux or in windows command line are able to have 'progress' information that changes on the same line.

nowadays most systems use only the '\n' to denote a newline. but some systems use both together.

you can see examples of this given in some of the other answers, but the most common are:

  • windows ends lines with '\r\n'
  • mac ends lines with '\r'
  • unix/linux use '\n'

and some other programs also have specific uses for them.

for more information about the history of these characters

Difference between JSON.stringify and JSON.parse

JSON.stringify() Converts an object into a string.

JSON.parse() Converts a JSON string into an object.

How to POST the data from a modal form of Bootstrap?

You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.

You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.

<form asp-action="AddUsersToRole" method="POST" class="mb-3">

    @await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)

    <div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add Users to Role</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

</form>

You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action. You do not have to use ajax.

Mozilla documentation on form action

Blur or dim background when Android PopupWindow active

Maybe this repo will help for you:BasePopup

This is my repo, which is used to solve various problems of PopupWindow.

In the case of using the library, if you need to blur the background, just call setBlurBackgroundEnable(true).

See the wiki for more details.(Language in zh-cn)

BasePopup:wiki

HTML Image not displaying, while the src url works

In your angular.json folder structure should be like this

"assets": [             
  "src/assets",
  "src/favicon.ico"
],

not this

"assets": [     
  "src/favicon.ico",
  "src/assets",
],

This solved my problem.

How to start http-server locally

When you're running npm install in the project's root, it installs all of the npm dependencies into the project's node_modules directory.

If you take a look at the project's node_modules directory, you should see a directory called http-server, which holds the http-server package, and a .bin folder, which holds the executable binaries from the installed dependencies. The .bin directory should have the http-server binary (or a link to it).

So in your case, you should be able to start the http-server by running the following from your project's root directory (instead of npm start):

./node_modules/.bin/http-server -a localhost -p 8000 -c-1

This should have the same effect as running npm start.

If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin folder to your $PATH environment variable:

export PATH=./node_modules/.bin:$PATH

This will put this folder on your path, and you should be able to simply run

http-server -a localhost -p 8000 -c-1

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

You can do it in this way

// xyz.h
#ifndef _XYZ_
#define _XYZ_

template <typename XYZTYPE>
class XYZ {
  //Class members declaration
};

#include "xyz.cpp"
#endif

//xyz.cpp
#ifdef _XYZ_
//Class definition goes here

#endif

This has been discussed in Daniweb

Also in FAQ but using C++ export keyword.

TypeError: object of type 'int' has no len() error assistance needed

Abstract:

The reason why you are getting this error message is because you are trying to call a method on an int type of a variable. This would work if would have called len() function on a list type of a variable. Let's examin the two cases:

Fail:

num = 10

print(len(num))

The above will produce an error similar to yours due to calling len() function on an int type of a variable;

Success:

data = [0, 4, 8, 9, 12]

print(len(data))

The above will work since you are calling a function on a list type of a variable;

Fling gesture detection on grid layout

I do it a little different, and wrote an extra detector class that implements the View.onTouchListener

onCreateis simply add it to the lowest layout like this:

ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
lowestLayout = (RelativeLayout)this.findViewById(R.id.lowestLayout);
lowestLayout.setOnTouchListener(activitySwipeDetector);

where id.lowestLayout is the id.xxx for the view lowest in the layout hierarchy and lowestLayout is declared as a RelativeLayout

And then there is the actual activity swipe detector class:

public class ActivitySwipeDetector implements View.OnTouchListener {

static final String logTag = "ActivitySwipeDetector";
private Activity activity;
static final int MIN_DISTANCE = 100;
private float downX, downY, upX, upY;

public ActivitySwipeDetector(Activity activity){
    this.activity = activity;
}

public void onRightSwipe(){
    Log.i(logTag, "RightToLeftSwipe!");
    activity.doSomething();
}

public void onLeftSwipe(){
    Log.i(logTag, "LeftToRightSwipe!");
    activity.doSomething();
}

public void onDownSwipe(){
    Log.i(logTag, "onTopToBottomSwipe!");
    activity.doSomething();
}

public void onUpSwipe(){
    Log.i(logTag, "onBottomToTopSwipe!");
    activity.doSomething();
}

public boolean onTouch(View v, MotionEvent event) {
    switch(event.getAction()){
        case MotionEvent.ACTION_DOWN: {
            downX = event.getX();
            downY = event.getY();
            return true;
        }
        case MotionEvent.ACTION_UP: {
            upX = event.getX();
            upY = event.getY();

            float deltaX = downX - upX;
            float deltaY = downY - upY;

       // swipe horizontal?
        if(Math.abs(deltaX) > Math.abs(deltaY))
        {
            if(Math.abs(deltaX) > MIN_DISTANCE){
                // left or right
                if(deltaX > 0) { this.onRightSwipe(); return true; }
                if(deltaX < 0) { this.onLeftSwipe(); return true; }
            }
            else {
                    Log.i(logTag, "Horizontal Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
                    return false; // We don't consume the event
            }
        }
        // swipe vertical?
        else 
        {
            if(Math.abs(deltaY) > MIN_DISTANCE){
                // top or down
                if(deltaY < 0) { this.onDownSwipe(); return true; }
                if(deltaY > 0) { this.onUpSwipe(); return true; }
            }
            else {
                    Log.i(logTag, "Vertical Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
                    return false; // We don't consume the event
            }
        }

            return true;
        }
    }
    return false;
}

}

Works really good for me!

In C#, why is String a reference type that behaves like a value type?

In a very simple words any value which has a definite size can be treated as a value type.

Subtracting 2 lists in Python

arr1=[1,2,3]
arr2=[2,1,3]
ls=[arr2-arr1 for arr1,arr2 in zip(arr1,arr2)]
print(ls)
>>[1,-1,0]

XAMPP, Apache - Error: Apache shutdown unexpectedly

In XAMPP Control Panel V3.2.1, click on "NetStat" button on top right. Make sure port 80 is not used by any other program. Then click on "Shell" Right below it. Issue this command "Type ap then TAB two times"

Apache_Start.bat

You will actually see the exact error why Apache failed. It will be mostly likely virtual host configuration issue or may be something else. It will display the line number on which the error is occurring. Just fix that error. Note that in RootDocument a trailing \ can be a source of error as well. Remove any trailing "\".

How to get the browser viewport dimensions?

Cross-browser @media (width) and @media (height) values 

const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)

window.innerWidth and window.innerHeight

  • gets CSS viewport @media (width) and @media (height) which include scrollbars
  • initial-scale and zoom variations may cause mobile values to wrongly scale down to what PPK calls the visual viewport and be smaller than the @media values
  • zoom may cause values to be 1px off due to native rounding
  • undefined in IE8-

document.documentElement.clientWidth and .clientHeight


Resources

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

In my case it was caused by not having CascadeType on the @ManyToOne side of the bidirectional relationship. To be more precise, I had CascadeType.ALL on @OneToMany side and did not have it on @ManyToOne. Adding CascadeType.ALL to @ManyToOne resolved the issue. One-to-many side:

@OneToMany(cascade = CascadeType.ALL, mappedBy="globalConfig", orphanRemoval = true)
private Set<GlobalConfigScope>gcScopeSet;

Many-to-one side (caused the problem)

@ManyToOne
@JoinColumn(name="global_config_id")
private GlobalConfig globalConfig;

Many-to-one (fixed by adding CascadeType.PERSIST)

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name="global_config_id")
private GlobalConfig globalConfig;

How to make an autocomplete address field with google maps api?

Below I split all the details of formatted address like City, State, Country and Zip code. 
So when you start typing your street name and select any option then street name write over street field, city name write over city field and all other fields like state, country and zip code will fill automatically. 
Using Google APIs.
------------------------------------------------
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function() {
    var places = new google.maps.places.Autocomplete(document
            .getElementById('txtPlaces'));
    google.maps.event.addListener(places, 'place_changed', function() {
        var place = places.getPlace();
        var address = place.formatted_address;
        var  value = address.split(",");
        count=value.length;
        country=value[count-1];
        state=value[count-2];
        city=value[count-3];
        var z=state.split(" ");
        document.getElementById("selCountry").text = country;
        var i =z.length;
        document.getElementById("pstate").value = z[1];
        if(i>2)
        document.getElementById("pzcode").value = z[2];
        document.getElementById("pCity").value = city;
        var latitude = place.geometry.location.lat();
        var longitude = place.geometry.location.lng();
        var mesg = address;
        document.getElementById("txtPlaces").value = mesg;
        var lati = latitude;
        document.getElementById("plati").value = lati;
        var longi = longitude;
        document.getElementById("plongi").value = longi;            
    });
});

How can I reduce the waiting (ttfb) time

I would suggest you read this article and focus more on how to optimize the overall response to the user request (either a page, a search result etc.)

A good argument for this is the example they give about using gzip to compress the page. Even though ttfb is faster when you do not compress, the overall experience of the user is worst because it takes longer to download content that is not zipped.

Set custom HTML5 required field validation message

You can simply achieve this using oninvalid attribute, checkout this demo code

<form>
<input type="email" pattern="[^@]*@[^@]" required oninvalid="this.setCustomValidity('Put  here custom message')"/>
<input type="submit"/>
</form>

enter image description here

Codepen Demo: https://codepen.io/akshaykhale1992/pen/yLNvOqP

How to delete directory content in Java?

You have to do this for each File:

public static void deleteFolder(File folder) {
    File[] files = folder.listFiles();
    if(files!=null) { //some JVMs return null for empty dirs
        for(File f: files) {
            if(f.isDirectory()) {
                deleteFolder(f);
            } else {
                f.delete();
            }
        }
    }
    folder.delete();
}

Then call

deleteFolder(outputFolder);

How do I display local image in markdown?

Solution for Unix-like operating system.

STEP BY STEP :
  1. Create a directory named like Images and put all the images that will be rendered by the Markdown.

  2. For example, put example.png into Images.

  3. To load example.png that was located under the Images directory before.

![title](Images/example.png)

Note : Images directory must be located under the same directory of your markdown text file which has .md extension.

How to find the largest file in a directory and its subdirectories?

To list the larger file in a folder

ls -sh /pathFolder | sort -rh | head -n 1

The output of ls -sh is a sized s and human h understandable view of the file size number.

You could use ls -shS /pathFolder | head -n 1. The bigger S from ls already order the list from the larger files to the smaller ones but the first result its the sum of all files in that folder. So if you want just to list the bigger file, one file, you need to head -n 2 and check at the "second line result" or use the first example with ls sort head.

Copy a variable's value into another

The reason for this is simple. JavaScript uses refereces, so when you assign b = a you are assigning a reference to b thus when updating a you are also updating b

I found this on stackoverflow and will help prevent things like this in the future by just calling this method if you want to do a deep copy of an object.

function clone(obj) {
    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        var copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        var copy = [];
        for (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        var copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}

How to pass arguments to a Button command in Tkinter?

This can also be done by using partial from the standard library functools, like this:

from functools import partial
#(...)
action_with_arg = partial(action, arg)
button = Tk.Button(master=frame, text='press', command=action_with_arg)

How to pause javascript code execution for 2 seconds

Javascript is single-threaded, so by nature there should not be a sleep function because sleeping will block the thread. setTimeout is a way to get around this by posting an event to the queue to be executed later without blocking the thread. But if you want a true sleep function, you can write something like this:

function sleep(miliseconds) {
   var currentTime = new Date().getTime();

   while (currentTime + miliseconds >= new Date().getTime()) {
   }
}

Note: The above code is NOT recommended.

The cast to value type 'Int32' failed because the materialized value is null

Got this error in Entity Framework 6 with this code at runtime:

var fileEventsSum = db.ImportInformations.Sum(x => x.FileEvents)

Update from LeandroSoares:

Use this for single execution:

var fileEventsSum = db.ImportInformations.Sum(x => (int?)x.FileEvents) ?? 0

Original:

Changed to this and then it worked:

var fileEventsSum = db.ImportInformations.Any() ? db.ImportInformations.Sum(x => x.FileEvents) : 0;

How to perform runtime type checking in Dart?

There are two operators for type testing: E is T tests for E an instance of type T while E is! T tests for E not an instance of type T.

Note that E is Object is always true, and null is T is always false unless T===Object.

What's the difference between commit() and apply() in SharedPreferences

apply() was added in 2.3, it commits without returning a boolean indicating success or failure.

commit() returns true if the save works, false otherwise.

apply() was added as the Android dev team noticed that almost no one took notice of the return value, so apply is faster as it is asynchronous.

http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()

finding and replacing elements in a list

a = [1,2,3,4,5,1,2,3,4,5,1,12]
for i in range (len(a)):
    if a[i]==2:
        a[i]=123

You can use a for and or while loop; however if u know the builtin Enumerate function, then it is recommended to use Enumerate.1

Sql query to insert datetime in SQL Server

If you are storing values via any programming language

Here is an example in C#

To store date you have to convert it first and then store it

insert table1 (foodate)
   values (FooDate.ToString("MM/dd/yyyy"));

FooDate is datetime variable which contains your date in your format.

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

Any tools to generate an XSD schema from an XML instance document?

This is an old thread but I thought it could be useful to post this link: just found this tool: xsd-gen Generate XML Schema from XML

and it just did what I needed.

Where does npm install packages?

The command npm root will tell you the effective installation directory of your npm packages.

If your current working directory is a node package or a sub-directory of a node package, npm root will tell you the local installation directory. npm root -g will show the global installation root regardless of current working directory.

Example:

$ npm root -g
/usr/local/lib/node_modules

See the documentation.

How to add a new line in textarea element?

I think you are confusing the syntax of different languages.

  • &#10; is (the HtmlEncoded value of ASCII 10 or) the linefeed character literal in a HTML string. But the line feed character does NOT render as a line break in HTML (see notes at bottom).

  • \n is the linefeed character literal (ASCII 10) in a Javascript string.

  • <br/> is a line break in HTML. Many other elements, eg <p>, <div>, etc also render line breaks unless overridden with some styles.

Hopefully the following illustration will make it clearer:

_x000D_
_x000D_
T.innerText = "Position of LF: " + t.value.indexOf("\n");_x000D_
_x000D_
p1.innerHTML = t.value;_x000D_
p2.innerHTML = t.value.replace("\n", "<br/>");_x000D_
p3.innerText = t.value.replace("\n", "<br/>");
_x000D_
<textarea id="t">Line 1&#10;Line 2</textarea>_x000D_
_x000D_
<p id='T'></p>_x000D_
<p id='p1'></p>_x000D_
<p id='p2'></p>_x000D_
<p id='p3'></p>
_x000D_
_x000D_
_x000D_

A few points to note about Html:

  • The innerHTML value of the TEXTAREA element does not render Html. Try the following: <textarea>A <a href='x'>link</a>.</textarea> to see.
  • The P element renders all contiguous white spaces (including new lines) as one space.
  • The LF character does not render to a new line or line break in HTML.
  • The TEXTAREA renders LF as a new line inside the text area box.

Can you have a <span> within a <span>?

HTML4 specification states that:

Inline elements may contain only data and other inline elements

Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.

HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.

Execute multiple command lines with the same process using .NET

Couldn't you just write all the commands into a .cmd file in the temp folder and then execute that file?

What is the difference between Jupyter Notebook and JupyterLab?

Jupyter Notebook is a web-based interactive computational environment for creating Jupyter notebook documents. It supports several languages like Python (IPython), Julia, R etc. and is largely used for data analysis, data visualization and further interactive, exploratory computing.

JupyterLab is the next-generation user interface including notebooks. It has a modular structure, where you can open several notebooks or files (e.g. HTML, Text, Markdowns etc) as tabs in the same window. It offers more of an IDE-like experience.

For a beginner I would suggest starting with Jupyter Notebook as it just consists of a filebrowser and an (notebook) editor view. It might be easier to use. If you want more features, switch to JupyterLab. JupyterLab offers much more features and an enhanced interface, which can be extended through extensions: JupyterLab Extensions (GitHub)

How to remove all duplicate items from a list

This should do it for you:

new_list = list(set(old_list))

set will automatically remove duplicates. list will cast it back to a list.

What is a stack trace, and how can I use it to debug my application errors?

To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.

Key 1:A tricky and important thing here need to be understand is : the deepest cause may not be the "root cause", because if you write some "bad code", it may cause some exception underneath which is deeper than its layer. For example, a bad sql query may cause SQLServerException connection reset in the bottem instead of syndax error, which may just in the middle of the stack.

-> Locate the root cause in the middle is your job. enter image description here

Key 2:Another tricky but important thing is inside each "Cause by" block, the first line was the deepest layer and happen first place for this block. For instance,

Exception in thread "main" java.lang.NullPointerException
        at com.example.myproject.Book.getTitle(Book.java:16)
           at com.example.myproject.Author.getBookTitles(Author.java:25)
               at com.example.myproject.Bootstrap.main(Bootstrap.java:14)

Book.java:16 was called by Auther.java:25 which was called by Bootstrap.java:14, Book.java:16 was the root cause. Here attach a diagram sort the trace stack in chronological order. enter image description here

COUNT DISTINCT with CONDITIONS

Code counts the unique/distinct combination of Tag & Entry ID when [Entry Id]>0

select count(distinct(concat(tag,entryId)))
from customers
where id>0

In the output it will display the count of unique values Hope this helps

How do I correctly clone a JavaScript object?

To support a better understanding of copying of objects, this illustrative jsbin may be of value

class base {
  get under(){return true}
}

class a extends base {}

const b = {
  get b1(){return true},
  b: true
}

console.log('Object assign')
let t1 = Object.create(b)
t1.x = true
const c = Object.assign(t1, new a())
console.log(c.b1 ? 'prop value copied': 'prop value gone')
console.log(c.x ? 'assigned value copied': 'assigned value gone')
console.log(c.under ? 'inheritance ok': 'inheritance gone')
console.log(c.b1 ? 'get value unchanged' : 'get value lost')
c.b1 = false
console.log(c.b1? 'get unchanged' : 'get lost')
console.log('-----------------------------------')
console.log('Object assign  - order swopped')
t1 = Object.create(b)
t1.x = true
const d = Object.assign(new a(), t1)
console.log(d.b1 ? 'prop value copied': 'prop value gone')
console.log(d.x ? 'assigned value copied': 'assigned value gone')
console.log(d.under ? 'inheritance n/a': 'inheritance gone')
console.log(d.b1 ? 'get value copied' : 'get value lost')
d.b1 = false
console.log(d.b1? 'get copied' : 'get lost')
console.log('-----------------------------------')
console.log('Spread operator')
t1 = Object.create(b)
t2 = new a()
t1.x = true
const e = { ...t1, ...t2 }
console.log(e.b1 ? 'prop value copied': 'prop value gone')
console.log(e.x ? 'assigned value copied': 'assigned value gone')
console.log(e.under ? 'inheritance ok': 'inheritance gone')
console.log(e.b1 ? 'get value copied' : 'get value lost')
e.b1 = false
console.log(e.b1? 'get copied' : 'get lost')
console.log('-----------------------------------')
console.log('Spread operator on getPrototypeOf')
t1 = Object.create(b)
t2 = new a()
t1.x = true
const e1 = { ...Object.getPrototypeOf(t1), ...Object.getPrototypeOf(t2) }
console.log(e1.b1 ? 'prop value copied': 'prop value gone')
console.log(e1.x ? 'assigned value copied': 'assigned value gone')
console.log(e1.under ? 'inheritance ok': 'inheritance gone')
console.log(e1.b1 ? 'get value copied' : 'get value lost')
e1.b1 = false
console.log(e1.b1? 'get copied' : 'get lost')
console.log('-----------------------------------')
console.log('keys, defineProperty, getOwnPropertyDescriptor')
f = Object.create(b)
t2 = new a()
f.x = 'a'
Object.keys(t2).forEach(key=> {
  Object.defineProperty(f,key,Object.getOwnPropertyDescriptor(t2, key))
})
console.log(f.b1 ? 'prop value copied': 'prop value gone')
console.log(f.x ? 'assigned value copied': 'assigned value gone')
console.log(f.under ? 'inheritance ok': 'inheritance gone')
console.log(f.b1 ? 'get value copied' : 'get value lost')
f.b1 = false
console.log(f.b1? 'get copied' : 'get lost')
console.log('-----------------------------------')
console.log('defineProperties, getOwnPropertyDescriptors')
let g = Object.create(b)
t2 = new a()
g.x = 'a'
Object.defineProperties(g,Object.getOwnPropertyDescriptors(t2))
console.log(g.b1 ? 'prop value copied': 'prop value gone')
console.log(g.x ? 'assigned value copied': 'assigned value gone')
console.log(g.under ? 'inheritance ok': 'inheritance gone')
console.log(g.b1 ? 'get value copied' : 'get value lost')
g.b1 = false
console.log(g.b1? 'get copied' : 'get lost')
console.log('-----------------------------------')

JQuery - how to select dropdown item based on value

$('select#myselect option[value="ab"]').

SQL Server 2008 R2 can't connect to local database in Management Studio

Your "SQL Server Browser" service has to be started too.

Browse to Computer Management > Services. how to browse to computer management

Find find "SQL Server Browser"

  1. set it to Automatic
  2. and also Manually start it (2)

how to edit sql server browser properties and start it

Hope it helps.

Mockito: List Matchers with generics

For Java 8 and above, it's easy:

when(mock.process(Matchers.anyList()));

For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz):

when(mock.process(Matchers.anyListOf(Bar.class)));

How to add option to select list in jQuery

Your code fails because you are executing a method (addOption) on the jQuery object (and this object does not support the method)

You can use the standard Javascript function like this:

$("#dropListBuilding")[0].options.add( new Option("My Text","My Value") )

How to extend an existing JavaScript array with another array, without creating a new array

The .push method can take multiple arguments. You can use the spread operator to pass all the elements of the second array as arguments to .push:

>>> a.push(...b)

If your browser does not support ECMAScript 6, you can use .apply instead:

>>> a.push.apply(a, b)

Or perhaps, if you think it's clearer:

>>> Array.prototype.push.apply(a,b)

Please note that all these solutions will fail with a stack overflow error if array b is too long (trouble starts at about 100,000 elements, depending on the browser).
If you cannot guarantee that b is short enough, you should use a standard loop-based technique described in the other answer.

How to calculate percentage with a SQL statement

I simply use this when ever I need to work out a percentage..

ROUND(CAST((Numerator * 100.0 / Denominator) AS FLOAT), 2) AS Percentage

Note that 100.0 returns decimals, whereas 100 on it's own will round up the result to the nearest whole number, even with the ROUND() function!

Format Date time in AngularJS

I know this is an old item, but thought I'd throw in another option to consider.

As the original string doesn't include the "T" demarker, the default implementation in Angular doesn't recognize it as a date. You can force it using new Date, but that is a bit of a pain on an array. Since you can pipe filters together, you might be able to use a filter to convert your input to a date and then apply the date: filter on the converted date. Create a new custom filter as follows:

app
.filter("asDate", function () {
    return function (input) {
        return new Date(input);
    }
});

Then in your markup, you can pipe the filters together:

{{item.myDateTimeString | asDate | date:'shortDate'}}

Check if a string contains a number

What about this one?

import string

def containsNumber(line):
    res = False
    try:
        for val in line.split():
            if (float(val.strip(string.punctuation))):
                res = True
                break
    except ValueError:
        pass
    return res

containsNumber('234.12 a22') # returns True
containsNumber('234.12L a22') # returns False
containsNumber('234.12, a22') # returns True

How to redirect to previous page in Ruby On Rails?

For those who are interested, here is my implementation extending MBO's original answer (written against rails 4.2.4, ruby 2.1.5).

class ApplicationController < ActionController::Base
  after_filter :set_return_to_location

  REDIRECT_CONTROLLER_BLACKLIST = %w(
    sessions
    user_sessions
    ...
    etc.
  )

  ...

  def set_return_to_location
    return unless request.get?
    return unless request.format.html?
    return unless %w(show index edit).include?(params[:action])
    return if REDIRECT_CONTROLLER_BLACKLIST.include?(controller_name)
    session[:return_to] = request.fullpath
  end

  def redirect_back_or_default(default_path = root_path)
    redirect_to(
      session[:return_to].present? && session[:return_to] != request.fullpath ?
        session[:return_to] : default_path
    )
  end
end

Generate a Hash from string in Javascript

EDIT

based on my jsperf tests, the accepted answer is actually faster: http://jsperf.com/hashcodelordvlad

ORIGINAL

if anyone is interested, here is an improved ( faster ) version, which will fail on older browsers who lack the reduce array function.

hashCode = function(s){
  return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);              
}

one-liner arrow function version :

hashCode = s => s.split('').reduce((a,b)=>{a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)

How to use variables in SQL statement in Python?

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

Note that the parameters are passed as a tuple.

The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%), because

  1. it does not do any escaping or quoting.
  2. it is prone to Uncontrolled string format attacks e.g. SQL injection.

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

How to take a screenshot programmatically on iOS

Two options available at bellow site:

OPTION 1: using UIWindow (tried and work perfectly)

// create graphics context with screen size
CGRect screenRect = [[UIScreen mainScreen] bounds];
UIGraphicsBeginImageContext(screenRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, screenRect);

// grab reference to our window
UIWindow *window = [UIApplication sharedApplication].keyWindow;

// transfer content into our context
[window.layer renderInContext:ctx];
UIImage *screengrab = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

OPTION 2: using UIView

// grab reference to the view you'd like to capture
UIView *wholeScreen = self.splitViewController.view;

// define the size and grab a UIImage from it
UIGraphicsBeginImageContextWithOptions(wholeScreen.bounds.size, wholeScreen.opaque, 0.0);
[wholeScreen.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screengrab = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

For retina screen (as DenNukem answer)

// grab reference to our window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;

    // create graphics context with screen size
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, [UIScreen mainScreen].scale);
    } else {
        UIGraphicsBeginImageContext(screenRect.size);
        [window.layer renderInContext:UIGraphicsGetCurrentContext()];
    }

for more detail: http://pinkstone.co.uk/how-to-take-a-screeshot-in-ios-programmatically/

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

add class with JavaScript

Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

function getElementsByClass(searchClass, node, tag) {

  var classElements = new Array();

  if (node == null)

    node = document;

  if (tag == null)

    tag = '*';

  var els = node.getElementsByTagName(tag);

  var elsLen = els.length;

  var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');

  for (i = 0, j = 0; i < elsLen; i++) {

    if (pattern.test(els[i].className)) {

      classElements[j] = els[i];

      j++;

    }

  }

  return classElements;

}

Responsive web design is working on desktop but not on mobile device

Responsive meta tag

To ensure proper rendering and touch zooming for all devices, add the responsive viewport meta tag to your <head>.

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

Override body style for content in an iframe

I have a blog and I had a lot of trouble finding out how to resize my embedded gist. Post manager only allows you to write text, place images and embed HTML code. Blog layout is responsive itself. It's built with Wix. However, embedded HTML is not. I read a lot about how it's impossible to resize components inside body of generated iFrames. So, here is my suggestion:

If you only have one component inside your iFrame, i.e. your gist, you can resize only the gist. Forget about the iFrame.

I had problems with viewport, specific layouts to different user agents and this is what solved my problem:

<script language="javascript" type="text/javascript" src="https://gist.github.com/roliveiravictor/447f994a82238247f83919e75e391c6f.js"></script>

<script language="javascript" type="text/javascript">

function windowSize() {
  let gist = document.querySelector('#gist92442763');

  let isMobile = {
    Android: function() {
        return /Android/i.test(navigator.userAgent)
    },
    BlackBerry: function() {
        return /BlackBerry/i.test(navigator.userAgent)
    },
    iOS: function() {
        return /iPhone|iPod/i.test(navigator.userAgent)
    },
    Opera: function() {
        return /Opera Mini/i.test(navigator.userAgent)
    },
    Windows: function() {
        return /IEMobile/i.test(navigator.userAgent) || /WPDesktop/i.test(navigator.userAgent)
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

  if(isMobile.any()) {
    gist.style.width = "36%";
    gist.style.WebkitOverflowScrolling = "touch"
    gist.style.position = "absolute"
  } else {
    gist.style.width = "auto !important";
  }
}

windowSize();

window.addEventListener('onresize', function() {
    windowSize();
});

</script>

<style type="text/css">

.gist-data {
  max-height: 300px;
}

.gist-meta {
  display: none;
}

</style>

The logic is to set gist (or your component) css based on user agent. Make sure to identify your component first, before applying to query selector. Feel free to take a look how responsiveness is working.

How to terminate a process in vbscript

Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.

Regular Expression - 2 letters and 2 numbers in C#

Just for fun, here's a non-regex (more readable/maintainable for simpletons like me) solution:

string myString = "AB12";

if( Char.IsLetter(myString, 0) && 
    Char.IsLetter(myString, 1) && 
    Char.IsNumber(myString, 2) &&
    Char.IsNumber(myString, 3)) {
    // First two are letters, second two are numbers
}
else {
    // Validation failed
}

EDIT

It seems that I've misunderstood the requirements. The code below will ensure that the first two characters and last two characters of a string validate (so long as the length of the string is > 3)

string myString = "AB12";

if(myString.Length > 3) {    
    if( Char.IsLetter(myString, 0) && 
        Char.IsLetter(myString, 1) && 
        Char.IsNumber(myString, (myString.Length - 2)) &&
        Char.IsNumber(myString, (myString.Length - 1))) {
        // First two are letters, second two are numbers
      }
      else {
        // Validation failed
    }
}
else {
   // Validation failed
}

list all files in the folder and also sub folders

Use FileUtils from Apache commons.

listFiles

public static Collection<File> listFiles(File directory,
                                         String[] extensions,
                                         boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files

PHP function to build query string from array

Here's a simple php4-friendly implementation:

/**
* Builds an http query string.
* @param array $query  // of key value pairs to be used in the query
* @return string       // http query string.
**/
function build_http_query( $query ){

    $query_array = array();

    foreach( $query as $key => $key_value ){

        $query_array[] = urlencode( $key ) . '=' . urlencode( $key_value );

    }

    return implode( '&', $query_array );

}

Declare variable in SQLite and use it

For a read-only variable (that is, a constant value set once and used anywhere in the query), use a Common Table Expression (CTE).

WITH const AS (SELECT 'name' AS name, 10 AS more)
SELECT table.cost, (table.cost + const.more) AS newCost
FROM table, const 
WHERE table.name = const.name

SQLite WITH clause

How do I rename a Git repository?

There are various possible interpretations of what is meant by renaming a Git repository: the displayed name, the repository directory, or the remote repository name. Each requires different steps to rename.

Displayed Name

Rename the displayed name (for example, shown by gitweb):

  1. Edit .git/description to contain the repository's name.
  2. Save the file.

Repository Directory

Git does not reference the name of the directory containing the repository, as used by git clone master child, so we can simply rename it:

  1. Open a command prompt (or file manager window).
  2. Change to the directory that contains the repository directory (i.e., do not go into the repository directory itself).
  3. Rename the directory (for example, using mv from the command line or the F2 hotkey from a GUI).

Remote Repository

Rename a remote repository as follows:

  1. Go to the remote host (for example, https://github.com/User/project).
  2. Follow the host's instructions to rename the project (will differ from host to host, but usually Settings is a good starting point).
  3. Go to your local repository directory (i.e., open a command prompt and change to the repository's directory).
  4. Determine the new URL (for example, [email protected]:User/project-new.git)
  5. Set the new URL using Git:

    git remote set-url origin [email protected]:User/project-new.git
    

100% Min Height CSS layout

I agree with Levik as the parent container is set to 100% if you have sidebars and want them to fill the space to meet up with the footer you cannot set them to 100% because they will be 100 percent of the parent height as well which means that the footer ends up getting pushed down when using the clear function.

Think of it this way if your header is say 50px height and your footer is 50px height and the content is just autofitted to the remaining space say 100px for example and the page container is 100% of this value its height will be 200px. Then when you set the sidebar height to 100% it is then 200px even though it is supposed to fit snug in between the header and footer. Instead it ends up being 50px + 200px + 50px so the page is now 300px because the sidebars are set to the same height as the page container. There will be a big white space in the contents of the page.

I am using internet Explorer 9 and this is what I am getting as the effect when using this 100% method. I havent tried it in other browsers and I assume that it may work in some of the other options. but it will not be universal.

Bootstrap 3: Using img-circle, how to get circle from non-square image?

the problem mainly is because the width have to be == to the height, and in the case of bs, the height is set to auto so here is a fix for that in js instead

function img_circle() {
    $('.img-circle').each(function() {
        $w = $(this).width();
        $(this).height($w);
    });
}

$(document).ready(function() {
    img_circle();
});

$(window).resize(function() {
    img_circle();
});

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

How to match hyphens with Regular Expression?

Escape the hyphen.

[a-zA-Z0-9!$* \t\r\n\-]

UPDATE:
Never mind this answer - you can add the hyphen to the group but you don't have to escape it. See Konrad Rudolph's answer instead which does a much better job of answering and explains why.

What characters do I need to escape in XML documents?

Escaping characters is different for tags and attributes.

For tags:

 < &lt;
 > &gt; (only for compatibility, read below)
 & &amp;

For attributes:

" &quot;
' &apos;

From Character Data and Markup:

The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " &amp; " and " &lt; " respectively. The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility, be escaped using either " &gt; " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as " &apos; ", and the double-quote character (") as " &quot; ".

Change link color of the current page with CSS

It is possible to achieve this without having to modify each page individually (adding a 'current' class to a specific link), but still without JS or a server-side script. This uses the :target pseudo selector, which relies on #someid appearing in the addressbar.

<!DOCTYPE>
<html>
<head>
    <title>Some Title</title>
<style>
:target {
    background-color: yellow;
}
</style>
</head>
<body>
<ul>
    <li><a id="news" href="news.html#news">News</a></li>
    <li><a id="games" href="games.html#games">Games</a></li>
    <li><a id="science" href="science.html#science">Science</a></li>
</ul>
<h1>Stuff about science</h1>
<p>lorem ipsum blah blah</p>
</body>
</html>

There are a couple of restrictions:

  • If the page wasn't navigated to using one of these links it won't be coloured;
  • The ids need to occur at the top of the page otherwise the page will jump down a bit when visited.

As long as any links to these pages include the id, and the navbar is at the top, it shouldn't be a problem.


Other in-page links (bookmarks) will also cause the colour to be lost.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

I resolved this problem by opening the .xsd file with an XML reader and deleting a constraint placed on one of my views. For whatever reason when I added the view to the data it added a primary key constraint to one of the columns when there shouldn't have been one.

The other way is to open the .xsd file normally, look at the table/view causing the issue and delete any keys (right click column, select delete key) that should not be there.

reading from app.config file

The reason is simple, your call to ConfigurationSettings.AppSettings is not returning the required config file. Please try any of the following ways:

  • Make sure your app config has the same name as your application's exe file - with the extension .config appended eg MyApp.exe.config
  • OR you can use ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings["StartingMonthColumn"]

Hope this helps

Get last dirname/filename in a file path argument in Bash

basename does remove the directory prefix of a path:

$ basename /usr/local/svn/repos/example
example
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"
/server/root/example

'router-outlet' is not a known element

Its just better to create a routing component that would handle all your routes! From the angular website documentation! That's good practice!

ng generate module app-routing --flat --module=app

The above CLI generates a routing module and adds to your app module, all you need to do from the generated component is to declare your routes, also don't forget to add this:

exports: [
    RouterModule
  ],

to your ng-module decorator as it doesn't come with the generated app-routing module by default!

Regex empty string or email

matching empty string or email

(^$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)

matching empty string or email but also matching any amount of whitespace

(^\s*$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)

see more about the email matching regex itself:

http://www.regular-expressions.info/email.html

Force Java timezone as GMT/UTC

You could change the timezone using TimeZone.setDefault():

TimeZone.setDefault(TimeZone.getTimeZone("GMT"))

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

The equivalent is:

python3 -m http.server

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

For any executable file, you can run your program using cmd with "c" parameter:

cmd /c "your program address"\"YourFileName".bat  

(->if it's a batch file!) As a final solution, I suggest that you create a .cmd file and put this command in it:

cmd /c "your program address"\"YourFileName".bat
exit

Now just run this .cmd file.

How to make html <select> element look like "disabled", but pass values?

If you can supply a default value for your selects, then you can use the same approach for unchecked check boxes which requires a hidden input before the actual element, as these don't post a value if left unchecked:

<input type="hidden" name="myfield" value="default" />
<select name="myfield">
    <option value="default" selected="selected">Default</option>
    <option value="othervalue">Other value</option>
    <!-- ... //-->
</select>

This will actually post the value "default" (without quotes, obviously) if the select is disabled by javascript (or jQuery) or even if your code writes the html disabling the element itself with the attribute: disabled="disabled".

How to configure static content cache per folder and extension in IIS7?

You can set specific cache-headers for a whole folder in either your root web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- Note the use of the 'location' tag to specify which 
       folder this applies to-->
  <location path="images">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
      </staticContent>
    </system.webServer>
  </location>
</configuration>

Or you can specify these in a web.config file in the content folder:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
    </staticContent>
  </system.webServer>
</configuration>

I'm not aware of a built in mechanism to target specific file types.

How do you fade in/out a background color using jquery?

Using jQuery only (no UI library/plugin). Even jQuery can be easily eliminated

//Color row background in HSL space (easier to manipulate fading)
$('tr').eq(1).css('backgroundColor','hsl(0,100%,50%');

var d = 1000;
for(var i=50; i<=100; i=i+0.1){ //i represents the lightness
    d  += 10;
    (function(ii,dd){
        setTimeout(function(){
            $('tr').eq(1).css('backgroundColor','hsl(0,100%,'+ii+'%)'); 
        }, dd);    
    })(i,d);
}

Demo : http://jsfiddle.net/5NB3s/2/

  • SetTimeout increases the lightness from 50% to 100%, essentially making the background white (you can choose any value depending on your color).
  • SetTimeout is wrapped in an anonymous function for it to work properly in a loop ( reason )

Padding or margin value in pixels as integer using jQuery

PLEASE don't go loading another library just to do something that's already natively available!

jQuery's .css() converts %'s and em's to their pixel equivalent to begin with, and parseInt() will remove the 'px' from the end of the returned string and convert it to an integer:

http://jsfiddle.net/BXnXJ/

$(document).ready(function () {
    var $h1 = $('h1');
    console.log($h1);
    $h1.after($('<div>Padding-top: ' + parseInt($h1.css('padding-top')) + '</div>'));
    $h1.after($('<div>Margin-top: ' + parseInt($h1.css('margin-top')) + '</div>'));
});

Select value from list of tuples where condition

If you have named tuples you can do this:

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

Otherwise use indexes:

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

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

How to sum array of numbers in Ruby?

Or try the Ruby 1.9 way:

array.inject(0, :+)

Note: the 0 base case is needed otherwise nil will be returned on empty arrays:

> [].inject(:+)
nil
> [].inject(0, :+)
0

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

It's a separate statement.

It's also not possible to insert into a table and select from it and build an index in the same statement either.

The BOL entry contains the information you need:

CLUSTERED | NONCLUSTERED
Indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED, and UNIQUE constraints default to NONCLUSTERED.

In a CREATE TABLE statement, CLUSTERED can be specified for only one constraint. If CLUSTERED is specified for a UNIQUE constraint and a PRIMARY KEY constraint is also specified, the PRIMARY KEY defaults to NONCLUSTERED.

You can create an index on a PK field, but not a non-clustered index on a non-pk non-unique-constrained field.

A NCL index is not relevant to the structure of the table, and is not a constraint on the data inside the table. It's a separate entity that supports the table but is not integral to it's functionality or design.

That's why it's a separate statement. The NCL index is irrelevant to the table from a design perspective (query optimization notwithstanding).

Bootstrap 4 navbar color

I got it. This is very simple. Using the class bg you can achieve this easily.

Let me show you:

<nav class="navbar navbar-expand-lg navbar-dark navbar-full bg-primary"></nav>

This gives you the default blue navbar

If you want to change your favorite color, then simply use the style tag within the nav:

<nav class="navbar navbar-expand-lg navbar-dark navbar-full" style="background-color: #FF0000">

At least one JAR was scanned for TLDs yet contained no TLDs

If one wants to have the conf\logging.properties read one must (see also here) dump this file into the Servers\Tomcat v7.0 Server at localhost-config\ folder and then add the lines :

-Djava.util.logging.config.file="${workspace_loc}\Servers\Tomcat v7.0 Server at localhost-config\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager

to the VM arguments of the launch configuration one is using.

This may have taken a restart or two (or not) but finally I saw in the console in bright red :

FINE: No TLD files were found in [file:/C:/Dropbox/eclipse_workspaces/javaEE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ted2012/WEB-INF/lib/logback-classic-1.0.7.jar]. Consider adding the JAR to the tomcat.util.scan.DefaultJarScanner.jarsToSkip or org.apache.catalina.startup.TldConfig.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file. //etc

I still don't know when exactly this FINE warning appears - does not appear immediately on tomcat launch EDIT: from the comment by @Stephan: "The FINE warning appears each time any change is done in the JSP file".


Bonus: To make the warning go away add in catalina.properties :

# Additional JARs (over and above the default JARs listed above) to skip when
# scanning for TLDs. The list must be a comma separated list of JAR file names.
org.apache.catalina.startup.TldConfig.jarsToSkip=logback-classic-1.0.7.jar,\
joda-time-2.1.jar,joda-time-2.1-javadoc.jar,mysql-connector-java-5.1.24-bin.jar,\
logback-core-1.0.7.jar,javax.servlet.jsp.jstl-api-1.2.1.jar

crop text too long inside div

Below code will hide your text with fixed width you decide. but not quite right for responsive designs.

.CropLongTexts {
  width: 170px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Update

I have noticed in (mobile) device(s) that the text (mixed) with each other due to (fixed width)... so i have edited the code above to become hidden responsively as follow:

.CropLongTexts {
  max-width: 170px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

The (max-width) ensure the text will be hidden responsively whatever the (screen size) and will not mixed with each other.

How to use ImageBackground to set background image for screen in react-native

.hero-image {
  background-image: url("photographer.jpg"); /* The image used */
  background-color: #cccccc; /* Used if the image is unavailable */
  height: 500px; /* You must set a specified height */
  background-position: center; /* Center the image */
  background-repeat: no-repeat; /* Do not repeat the image */
  background-size: cover; /* Resize the background image to cover the entire container */
}

look result

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How to get row index number in R?

Perhaps this complementary example of "match" would be helpful.

Having two datasets:

first_dataset <- data.frame(name = c("John", "Luke", "Simon", "Gregory", "Mary"),
                            role = c("Audit", "HR", "Accountant", "Mechanic", "Engineer"))

second_dataset <- data.frame(name = c("Mary", "Gregory", "Luke", "Simon"))

If the name column contains only unique across collection values (across whole collection) then you can access row in other dataset by value of index returned by match

name_mapping <- match(second_dataset$name, first_dataset$name)

match returns proper row indexes of names in first_dataset from given names from second: 5 4 2 1 example here - accesing roles from first dataset by row index (by given name value)

for(i in 1:length(name_mapping)) {
    role <- as.character(first_dataset$role[name_mapping[i]])   
    second_dataset$role[i] = role
}

===

second dataset with new column:
     name       role
1    Mary   Engineer
2 Gregory   Mechanic
3    Luke Supervisor
4   Simon Accountant

What is the email subject length limit?

See RFC 2822, section 2.1.1 to start.

There are two limits that this standard places on the number of characters in a line. Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF.

As the RFC states later, you can work around this limit (not that you should) by folding the subject over multiple lines.

Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding". The general rule is that wherever this standard allows for folding white space (not simply WSP characters), a CRLF may be inserted before any WSP. For example, the header field:

       Subject: This is a test

can be represented as:

       Subject: This
        is a test

The recommendation for no more than 78 characters in the subject header sounds reasonable. No one wants to scroll to see the entire subject line, and something important might get cut off on the right.

Using cut command to remove multiple columns

The same could be done with Perl
Because it uses 0-based-indexing instead of 1-based-indexing, the field values are offset by 1

perl -F, -lane 'print join ",", @F[1..3,5..9,11..19]'    

is equivalent to:

cut -d, -f2-4,6-10,12-20

If the commas are not needed in the output:

perl -F, -lane 'print "@F[1..3,5..9,11..19]"'

How do I find what Java version Tomcat6 is using?

You can use the Tomcat manager app to find out which JRE and OS versions Tomcat is using. Given a user tomcat with password password with a role of manager:

Tomcat 6:

curl http://tomcat:password@localhost:8080/manager/serverinfo

Tomcat 7/8:

curl http://tomcat:password@localhost:8080/manager/text/serverinfo

How to add new line into txt file

var Line = textBox1.Text + "," + textBox2.Text;

File.AppendAllText(@"C:\Documents\m2.txt", Line + Environment.NewLine);

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21

webViewClient = object : WebViewClient() {
.
.
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            parseUri(request?.url)
            return true
        }

        @SuppressWarnings("deprecation")
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            parseUri(Uri.parse(url))
            return true
        }
}

"The semaphore timeout period has expired" error for USB connection

This error could also appear if you are having network latency or internet or local network problems. Bridged connections that have a failing counterpart may be the culprit as well.

How do I consume the JSON POST data in an Express application

Sometimes you don't need third party libraries to parse JSON from text. Sometimes all you need it the following JS command, try it first:

        const res_data = JSON.parse(body);

Change color and appearance of drop down arrow

You can acheive this with CSS but you are not techinically changing the arrow itself.

In this example I am actually hiding the default arrow and displaying my own arrow instead.

_x000D_
_x000D_
.styleSelect select {_x000D_
  background: transparent;_x000D_
  width: 168px;_x000D_
  padding: 5px;_x000D_
  font-size: 16px;_x000D_
  line-height: 1;_x000D_
  border: 0;_x000D_
  border-radius: 0;_x000D_
  height: 34px;_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.styleSelect {_x000D_
  width: 140px;_x000D_
  height: 34px;_x000D_
  overflow: hidden;_x000D_
  background: url("images/downArrow.png") no-repeat right #fff;_x000D_
  border: 2px solid #000;_x000D_
}
_x000D_
<div class="styleSelect">_x000D_
  <select class="units">_x000D_
    <option value="Metres">Metres</option>_x000D_
    <option value="Feet">Feet</option>_x000D_
    <option value="Fathoms">Fathoms</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Force LF eol in git repo and working copy

Starting with git 2.10 (released 2016-09-03), it is not necessary to enumerate each text file separately. Git 2.10 fixed the behavior of text=auto together with eol=lf. Source.

.gitattributes file in the root of your git repository:

* text=auto eol=lf

Add and commit it.

Afterwards, you can do following to steps and all files are normalized now:

git rm --cached -r .  # Remove every file from git's index.
git reset --hard      # Rewrite git's index to pick up all the new line endings.

Source: Answer by kenorb.

Select Pandas rows based on list index

Another way (although it is a longer code) but it is faster than the above codes. Check it using %timeit function:

df[df.index.isin([1,3])]

PS: You figure out the reason

enter image description here

vba pass a group of cells as range to function

As written, your function accepts only two ranges as arguments.

To allow for a variable number of ranges to be used in the function, you need to declare a ParamArray variant array in your argument list. Then, you can process each of the ranges in the array in turn.

For example,

Function myAdd(Arg1 As Range, ParamArray Args2() As Variant) As Double
    Dim elem As Variant
    Dim i As Long
    For Each elem In Arg1
        myAdd = myAdd + elem.Value
    Next elem
    For i = LBound(Args2) To UBound(Args2)
        For Each elem In Args2(i)
            myAdd = myAdd + elem.Value
        Next elem
    Next i
End Function

This function could then be used in the worksheet to add multiple ranges.

myAdd usage

For your function, there is the question of which of the ranges (or cells) that can passed to the function are 'Sessions' and which are 'Customers'.

The easiest case to deal with would be if you decided that the first range is Sessions and any subsequent ranges are Customers.

Function calculateIt(Sessions As Range, ParamArray Customers() As Variant) As Double
    'This function accepts a single Sessions range and one or more Customers
    'ranges
    Dim i As Long
    Dim sessElem As Variant
    Dim custElem As Variant
    For Each sessElem In Sessions
        'do something with sessElem.Value, the value of each
        'cell in the single range Sessions
        Debug.Print "sessElem: " & sessElem.Value
    Next sessElem
    'loop through each of the one or more ranges in Customers()
    For i = LBound(Customers) To UBound(Customers)
        'loop through the cells in the range Customers(i)
        For Each custElem In Customers(i)
            'do something with custElem.Value, the value of
            'each cell in the range Customers(i)
            Debug.Print "custElem: " & custElem.Value
         Next custElem
    Next i
End Function

If you want to include any number of Sessions ranges and any number of Customers range, then you will have to include an argument that will tell the function so that it can separate the Sessions ranges from the Customers range.

This argument could be set up as the first, numeric, argument to the function that would identify how many of the following arguments are Sessions ranges, with the remaining arguments implicitly being Customers ranges. The function's signature would then be:

Function calculateIt(numOfSessionRanges, ParamAray Args() As Variant)

Or it could be a "guard" argument that separates the Sessions ranges from the Customers ranges. Then, your code would have to test each argument to see if it was the guard. The function would look like:

Function calculateIt(ParamArray Args() As Variant)

Perhaps with a call something like:

calculateIt(sessRange1,sessRange2,...,"|",custRange1,custRange2,...)

The program logic might then be along the lines of:

Function calculateIt(ParamArray Args() As Variant) As Double
   ...
   'loop through Args
   IsSessionArg = True
   For i = lbound(Args) to UBound(Args)
       'only need to check for the type of the argument
       If TypeName(Args(i)) = "String" Then
          IsSessionArg = False
       ElseIf IsSessionArg Then
          'process Args(i) as Session range
       Else
          'process Args(i) as Customer range
       End if
   Next i
   calculateIt = <somevalue>
End Function

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

jQuery click event not working after adding class

.live() is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax

$(document).on('click', "a.tabclick", function() {

This syntax will work for delegated events

.on()

@selector() in Swift?

selector is a word from Objective-C world and you are able to use it from Swift to have a possibility to call Objective-C from Swift It allows you to execute some code at runtime

Before Swift 2.2 the syntax is:

Selector("foo:")

Since a function name is passed into Selector as a String parameter("foo") it is not possible to check a name in compile time. As a result you can get a runtime error:

unrecognized selector sent to instance

After Swift 2.2+ the syntax is:

#selector(foo(_:))

Xcode's autocomplete help you to call a right method

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

Want to put out there that there is not much to worry about if someone provides an answer as an extension method because an extension method is just a cool way to call an instance method. I understand that you want the answer without using an extension method. Regardless if the method is defined as static, instance or extension - the result is the same.

The code below uses the code from the accepted answer to define an extension method and an instance method and creates a unit test to show the output is the same.

public static class Extensions
{
    public static void Each<T>(this IEnumerable<T> items, Action<T> action)
    {
        foreach (var item in items)
        {
            action(item);
        }
    }
}

[TestFixture]
public class ForEachTests
{
    public void Each<T>(IEnumerable<T> items, Action<T> action)
    {
        foreach (var item in items)
        {
            action(item);
        }
    }

    private string _extensionOutput;

    private void SaveExtensionOutput(string value)
    {
        _extensionOutput += value;
    }

    private string _instanceOutput;

    private void SaveInstanceOutput(string value)
    {
        _instanceOutput += value;
    }

    [Test]
    public void Test1()
    {
        string[] teams = new string[] {"cowboys", "falcons", "browns", "chargers", "rams", "seahawks", "lions", "heat", "blackhawks", "penguins", "pirates"};

        Each(teams, SaveInstanceOutput);

        teams.Each(SaveExtensionOutput);

        Assert.AreEqual(_extensionOutput, _instanceOutput);
    }
}

Quite literally, the only thing you need to do to convert an extension method to an instance method is remove the static modifier and the first parameter of the method.

This method

public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
    foreach (var item in items)
    {
        action(item);
    }
 }

becomes

public void Each<T>(Action<T> action)
{
    foreach (var item in items)
    {
        action(item);
    }
 }

How can I do time/hours arithmetic in Google Spreadsheet?

When the number being returned by your formula is being formatted as a time, and you want it formatted as a plain number, change the format of the cell to a plain number format: click the cell and then click Format, Number, Normal.

Time values in Google spreadsheet are represented as days and parts of days. For example, 36:00:00 is the formatted representation of the number 1.5 (a day and a half).

Suppose you divide 36:00:00 by 3:00:00, as in your example. Google Spreadsheet performs the calculation 1.5 divided by 0.125, which is 12. The result tells you that you have 12 3-hour intervals in a 36-hour time period. 12, of course, is not a time interval. It is a unitless quantity.

Going the other way, it is possible to format any number as a time. If you format 12 as a time, it's reasonable to expect that you will get 288:00:00. 12 days contain 288 hours.

What's the difference between deadlock and livelock?

Taken from http://en.wikipedia.org/wiki/Deadlock:

In concurrent computing, a deadlock is a state in which each member of a group of actions, is waiting for some other member to release a lock

A livelock is similar to a deadlock, except that the states of the processes involved in the livelock constantly change with regard to one another, none progressing. Livelock is a special case of resource starvation; the general definition only states that a specific process is not progressing.

A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time.

Livelock is a risk with some algorithms that detect and recover from deadlock. If more than one process takes action, the deadlock detection algorithm can be repeatedly triggered. This can be avoided by ensuring that only one process (chosen randomly or by priority) takes action.

PHP - print all properties of an object

As no one has not provided an OO approach yet here is like it would be done.

class Person {
    public $name = 'Alex Super Tramp';

    public $age = 100;

    private $property = 'property';
}


$r = new ReflectionClass(new Person);
print_r($r->getProperties());

//Outputs
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => name
            [class] => Person
        )

    [1] => ReflectionProperty Object
        (
            [name] => age
            [class] => Person
        )

    [2] => ReflectionProperty Object
        (
            [name] => property
            [class] => Person
        )

)

The advantage when using reflection is that you can filter by visibility of property, like this:

print_r($r->getProperties(ReflectionProperty::IS_PRIVATE));

Since Person::$property is private it's returned when filtering by IS_PRIVATE:

//Outputs
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => property
            [class] => Person
        )

)

Read the docs!

Install apps silently, with granted INSTALL_PACKAGES permission

!/bin/bash

f=/home/cox/myapp.apk   #or $1 if input from terminal.

#backup env var
backup=$LD_LIBRARY_PATH
LD_LIBRARY_PATH=/vendor/lib:/system/lib
myTemp=/sdcard/temp.apk
adb push $f $myTemp
adb shell pm install -r $myTemp
#restore env var
LD_LIBRARY_PATH=$backup

This works for me. I run this on ubuntu 12.04, on shell terminal.

How to show particular image as thumbnail while implementing share on Facebook?

I also had an issue on a site I was working on last week. I implemented a like box and tested the like box. Then I went ahead to add an image to my header (the ob:image meta). Still the correct image did not show up on my facebook notification.

I tried everything, and came to the conclusion that every single implementation of a like button is cached. So let's say you clock the Like button on url A, then you specify an image in the header and you test it by clicking the Luke button again on url A. You won't see the image as the page is cached. The image will show up when you click on the Like button on page B.

To reset the cache, you have to use the lint debugger tool that's mentioned above, and validate all the Urls for those that are cached... That's the only thing that worked for me.

Full Screen Theme for AppCompat

requestWindowFeature(Window.FEATURE_NO_TITLE);

What does git rev-parse do?

git rev-parse is an ancillary plumbing command primarily used for manipulation.

One common usage of git rev-parse is to print the SHA1 hashes given a revision specifier. In addition, it has various options to format this output such as --short for printing a shorter unique SHA1.

There are other use cases as well (in scripts and other tools built on top of git) that I've used for:

  • --verify to verify that the specified object is a valid git object.
  • --git-dir for displaying the abs/relative path of the the .git directory.
  • Checking if you're currently within a repository using --is-inside-git-dir or within a work-tree using --is-inside-work-tree
  • Checking if the repo is a bare using --is-bare-repository
  • Printing SHA1 hashes of branches (--branches), tags (--tags) and the refs can also be filtered based on the remote (using --remote)
  • --parse-opt to normalize arguments in a script (kind of similar to getopt) and print an output string that can be used with eval

Massage just implies that it is possible to convert the info from one form into another i.e. a transformation command. These are some quick examples I can think of:

  • a branch or tag name into the commit's SHA1 it is pointing to so that it can be passed to a plumbing command which only accepts SHA1 values for the commit.
  • a revision range A..B for git log or git diff into the equivalent arguments for the underlying plumbing command as B ^A

How to take the first N items from a generator or list?

With itertools you will obtain another generator object so in most of the cases you will need another step the take the first N elements (N). There are at least two simpler solutions (a little bit less efficient in terms of performance but very handy) to get the elements ready to use from a generator:

Using list comprehension:

first_N_element=[generator.next() for i in range(N)]

Otherwise:

first_N_element=list(generator)[:N]

Where N is the number of elements you want to take (e.g. N=5 for the first five elements).

Should I use px or rem value units in my CSS?

Yes. Or, rather, no.

Er, I mean, it doesn't matter. Use the one that makes sense for your particular project. PX and EM or both equally valid but will behave a bit different depending on your overall page's CSS architecture.

UPDATE:

To clarify, I'm stating that usually it likely doesn't matter which you use. At times, you may specifically want to choose one over the other. EMs are nice if you can start from scratch and want to use a base font size and make everything relative to that.

PXs are often needed when you're retrofitting a redesign onto an existing code base and need the specificity of px to prevent bad nesting issues.

Setting default values to null fields when mapping with Jackson

There is no annotation to set default value.
You can set default value only on java class level:

public class JavaObject 
{
    public String notNullMember;

    public String optionalMember = "Value";
}

React.js: Set innerHTML vs dangerouslySetInnerHTML

Based on (dangerouslySetInnerHTML).

It's a prop that does exactly what you want. However they name it to convey that it should be use with caution

How do I return multiple values from a function in C?

Use pointers as your function parameters. Then use them to return multiple value.

How can I open two pages from a single click without using JavaScript?

it is working perfectly by only using html

<p><a href="#"onclick="window.open('http://google.com');window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>

Byte[] to InputStream or OutputStream

You create and use byte array I/O streams as follows:

byte[] source = ...;
ByteArrayInputStream bis = new ByteArrayInputStream(source);
// read bytes from bis ...

ByteArrayOutputStream bos = new ByteArrayOutputStream();
// write bytes to bos ...
byte[] sink = bos.toByteArray();

Assuming that you are using a JDBC driver that implements the standard JDBC Blob interface (not all do), you can also connect a InputStream or OutputStream to a blob using the getBinaryStream and setBinaryStream methods1, and you can also get and set the bytes directly.

(In general, you should take appropriate steps to handle any exceptions, and close streams. However, closing bis and bos in the example above is unnecessary, since they aren't associated with any external resources; e.g. file descriptors, sockets, database connections.)

1 - The setBinaryStream method is really a getter. Go figure.

Display only 10 characters of a long string?

Show this "long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text "

to

long text long text long ...

        function cutString(text){    
            var wordsToCut = 5;
            var wordsArray = text.split(" ");
            if(wordsArray.length>wordsToCut){
                var strShort = "";
                for(i = 0; i < wordsToCut; i++){
                    strShort += wordsArray[i] + " ";
                }   
                return strShort+"...";
            }else{
                return text;
            }
         };

Text Editor For Linux (Besides Vi)?

I like the versatility of jEdit (http://www.jedit.org), its got a lot of plugins, crossplatform and has also stuff like block selection which I use all the time.

The downside is, because it is written in java, it is not the fastest one.

make iframe height dynamic based on content inside- JQUERY/Javascript

$(document).height() // - $('body').offset().top

and / or

$(window).height()

See Stack Overflow question How to get the height of a body element.

Try this to find the height of the body in jQuery:

if $("body").height()

It doesn't have a value if Firebug. Perhaps that's the problem.

How to use the switch statement in R functions?

those various ways of switch ...

# by index
switch(1, "one", "two")
## [1] "one"


# by index with complex expressions
switch(2, {"one"}, {"two"})
## [1] "two"


# by index with complex named expression
switch(1, foo={"one"}, bar={"two"})
## [1] "one"


# by name with complex named expression
switch("bar", foo={"one"}, bar={"two"})
## [1] "two"

How to replace multiple white spaces with one white space

Replacement groups provide impler approach resolving replacement of multiple white space characters with same single one:

    public static void WhiteSpaceReduce()
    {
        string t1 = "a b   c d";
        string t2 = "a b\n\nc\nd";

        Regex whiteReduce = new Regex(@"(?<firstWS>\s)(?<repeatedWS>\k<firstWS>+)");
        Console.WriteLine("{0}", t1);
        //Console.WriteLine("{0}", whiteReduce.Replace(t1, x => x.Value.Substring(0, 1))); 
        Console.WriteLine("{0}", whiteReduce.Replace(t1, @"${firstWS}"));
        Console.WriteLine("\nNext example ---------");
        Console.WriteLine("{0}", t2);
        Console.WriteLine("{0}", whiteReduce.Replace(t2, @"${firstWS}"));
        Console.WriteLine();
    }

Please notice the second example keeps single \n while accepted answer would replace end of line with space.

If you need to replace any combination of white space characters with the first one, just remove the back-reference \k from the pattern.

Do I really need to encode '&' as '&amp;'?

Update (March 2020): The W3C validator no longer complains about escaping URLs.

I was checking why Image URL's need escaping, hence tried it in https://validator.w3.org. The explanation is pretty nice. It highlights that even URL's need to be escaped. [PS:I guess it will unescaped when its consumed since URL's need &. Can anyone clarify?]

<img alt="" src="foo?bar=qut&qux=fop" />

An entity reference was found in the document, but there is no reference by that name defined. Often this is caused by misspelling the reference name, unencoded ampersands, or by leaving off the trailing semicolon (;). The most common cause of this error is unencoded ampersands in URLs as described by the WDG in "Ampersands in URLs". Entity references start with an ampersand (&) and end with a semicolon (;). If you want to use a literal ampersand in your document you must encode it as "&" (even inside URLs!). Be careful to end entity references with a semicolon or your entity reference may get interpreted in connection with the following text. Also keep in mind that named entity references are case-sensitive; &Aelig; and æ are different characters. If this error appears in some markup generated by PHP's session handling code, this article has explanations and solutions to your problem.

Get JSON object from URL

You need to read about json_decode function http://php.net/manual/en/function.json-decode.php

Here you go

$json = '{"expires_in":5180976,"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"}';
//OR $json = file_get_contents('http://someurl.dev/...');

$obj = json_decode($json);
var_dump($obj-> access_token);

//OR 

$arr = json_decode($json, true);
var_dump($arr['access_token']);

How can I switch themes in Visual Studio 2012

The Blue theme is now supported via Visual Studio update 2, and is accessed like the answer chosen for this question.

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

This is due to the different encoding method when read the file. In python, it defaultly encode the data with unicode. However, it may not works in various platforms.

I propose an encoding method which can help you solve this if 'utf-8' not works.

with open(path, newline='', encoding='cp1252') as csvfile:
    reader = csv.reader(csvfile)

It should works if you change the encoding method here. Also, you can find other encoding method here standard-encodings , if above doesn't work for you.

How to comment/uncomment in HTML code

I find this to be the bane of XML style document commenting too. There are XML editors like eclipse that can perform block commenting. Basically automatically add extra per line and remove them. May be they made it purposefully hard to comment that style of document it was supposed to be self explanatory with the tags after all.

Preloading CSS Images

I can confirm that my original code seems to work. I was casually sticking to an image with a wrong path.

Here's a test : http://paragraphe.org/slidetoggletest/test.html

<script>
    var pic = new Image();
    var pic2 = new Image();
    var pic3 = new Image();
    pic.src="images/inputs/input1.png";
    pic2.src="images/inputs/input2.png";
    pic3.src="images/inputs/input3.png";
</script>

Is System.nanoTime() completely useless?

This answer was written in 2011 from the point of view of what the Sun JDK of the time running on operating systems of the time actually did. That was a long time ago! leventov's answer offers a more up-to-date perspective.

That post is wrong, and nanoTime is safe. There's a comment on the post which links to a blog post by David Holmes, a realtime and concurrency guy at Sun. It says:

System.nanoTime() is implemented using the QueryPerformanceCounter/QueryPerformanceFrequency API [...] The default mechanism used by QPC is determined by the Hardware Abstraction layer(HAL) [...] This default changes not only across hardware but also across OS versions. For example Windows XP Service Pack 2 changed things to use the power management timer (PMTimer) rather than the processor timestamp-counter (TSC) due to problems with the TSC not being synchronized on different processors in SMP systems, and due the fact its frequency can vary (and hence its relationship to elapsed time) based on power-management settings.

So, on Windows, this was a problem up until WinXP SP2, but it isn't now.

I can't find a part II (or more) that talks about other platforms, but that article does include a remark that Linux has encountered and solved the same problem in the same way, with a link to the FAQ for clock_gettime(CLOCK_REALTIME), which says:

  1. Is clock_gettime(CLOCK_REALTIME) consistent across all processors/cores? (Does arch matter? e.g. ppc, arm, x86, amd64, sparc).

It should or it's considered buggy.

However, on x86/x86_64, it is possible to see unsynced or variable freq TSCs cause time inconsistencies. 2.4 kernels really had no protection against this, and early 2.6 kernels didn't do too well here either. As of 2.6.18 and up the logic for detecting this is better and we'll usually fall back to a safe clocksource.

ppc always has a synced timebase, so that shouldn't be an issue.

So, if Holmes's link can be read as implying that nanoTime calls clock_gettime(CLOCK_REALTIME), then it's safe-ish as of kernel 2.6.18 on x86, and always on PowerPC (because IBM and Motorola, unlike Intel, actually know how to design microprocessors).

There's no mention of SPARC or Solaris, sadly. And of course, we have no idea what IBM JVMs do. But Sun JVMs on modern Windows and Linux get this right.

EDIT: This answer is based on the sources it cites. But i still worry that it might actually be completely wrong. Some more up-to-date information would be really valuable. I just came across to a link to a four year newer article about Linux's clocks which could be useful.

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Hopefully, this will help...

interface Param {
    title: string;
    callback: (error: Error, data: string) => void;
}

Or in a Function


let myfunction = (title: string, callback: (error: Error, data: string) => void): string => {

    callback(new Error(`Error Message Here.`), "This is callback data.");
    return title;

}

cleanup php session files

To handle session properly, take a look at http://php.net/manual/en/session.configuration.php.

There you'll find these variables:

  • session.gc_probability
  • session.gc_divisor
  • session.gc_maxlifetime

These control the garbage collector (GC) probability of running with each page request.

You could set those with ini_set() at the beginning of your script or .htaccess file so you get certainty to some extent they will get deleted sometime.

String concatenation in Ruby

You can do that in several ways:

  1. As you shown with << but that is not the usual way
  2. With string interpolation

    source = "#{ROOT_DIR}/#{project}/App.config"
    
  3. with +

    source = "#{ROOT_DIR}/" + project + "/App.config"
    

The second method seems to be more efficient in term of memory/speed from what I've seen (not measured though). All three methods will throw an uninitialized constant error when ROOT_DIR is nil.

When dealing with pathnames, you may want to use File.join to avoid messing up with pathname separator.

In the end, it is a matter of taste.

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

I've mixed and matched from different schemes I've seen and based on the tooling I'm using.
So my completed branch name would be:

name/feature/issue-tracker-number/short-description

which would translate to:

mike/blogs/RSSI-12/logo-fix

The parts are separated by forward slashes because those get interpreted as folders in SourceTree for easy organization. We use Jira for our issue tracking so including the number makes it easier to look up in the system. Including that number also makes it searchable when trying to find that issue inside Github when trying to submit a pull request.

submit a form in a new tab

Add target="_blank" to the <form> tag.

Why do access tokens expire?

It is essentially a security measure. If your app is compromised, the attacker will only have access to the short-lived access token and no way to generate a new one.

Refresh tokens also expire but they are supposed to live much longer than the access token.

no match for ‘operator<<’ in ‘std::operator

There's only one error:

cout.cpp:26:29: error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = std::char_traits]((* & std::cout), ((const char*)"my structure ")) << m’

This means that the compiler couldn't find a matching overload for operator<<. The rest of the output is the compiler listing operator<< overloads that didn't match. The third line actually says this:

cout.cpp:26:29: note: candidates are:

How to keep :active css style after click a button

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

HTML

<input type="checkbox" id="activate-div">
  <label for="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>
  </label>

CSS

#activate-div{display:none}    

.my-div{background-color:#FFF} 

#activate-div:checked ~ label 
.my-div{background-color:#000}



To make button change content:

HTML

<input type="checkbox" id="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>

<label for="activate-div">
   //MY BUTTON STUFF
</label>

CSS

#activate-div{display:none}

.my-div{background-color:#FFF} 

#activate-div:checked + 
.my-div{background-color:#000}

Hope it helps!!

Using setattr() in python

The Python docs say all that needs to be said, as far as I can see.

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

If this isn't enough, explain what you don't understand.

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

Eclipse Optimize Imports to Include Static Imports

Shortcut for static import: CTRL + SHIFT + M

Append an object to a list in R in amortized constant time, O(1)?

This is a straightforward way to add items to an R List:

# create an empty list:
small_list = list()

# now put some objects in it:
small_list$k1 = "v1"
small_list$k2 = "v2"
small_list$k3 = 1:10

# retrieve them the same way:
small_list$k1
# returns "v1"

# "index" notation works as well:
small_list["k2"]

Or programmatically:

kx = paste(LETTERS[1:5], 1:5, sep="")
vx = runif(5)
lx = list()
cn = 1

for (itm in kx) { lx[itm] = vx[cn]; cn = cn + 1 }

print(length(lx))
# returns 5

How to use color picker (eye dropper)?

To open the Eye Dropper simply:

  1. Open DevTools F12
  2. Go to Elements tab
  3. Under Styles side bar click on any color preview box

enter image description here

Its main functionality is to inspect pixel color values by clicking them though with its new features you can also see your page's existing colors palette or material design palette by clicking on the two arrows icon at the bottom. It can get quite handy when designing your page.