Programs & Examples On #Matrix multiplication

Questions related to matrix multiplication, especially implementation. Mathematical questions should consider the linear algebra tag.

Matrix multiplication using arrays

static int b[][]={{21,21},{22,22}};

static int a[][] ={{1,1},{2,2}};

public static void mul(){
    int c[][] = new int[2][2];

    for(int i=0;i<b.length;i++){
        for(int j=0;j<b.length;j++){
            c[i][j] =0;
        }   
    }

    for(int i=0;i<a.length;i++){
        for(int j=0;j<b.length;j++){
            for(int k=0;k<b.length;k++){
            c[i][j]= c[i][j] +(a[i][k] * b[k][j]);
            }
        }
    }

    for(int i=0;i<c.length;i++){
        for(int j=0;j<c.length;j++){
            System.out.print(c[i][j]);
        }   
        System.out.println("\n");
    }
}

how does multiplication differ for NumPy Matrix vs Array classes?

A pertinent quote from PEP 465 - A dedicated infix operator for matrix multiplication , as mentioned by @petr-viktorin, clarifies the problem the OP was getting at:

[...] numpy provides two different types with different __mul__ methods. For numpy.ndarray objects, * performs elementwise multiplication, and matrix multiplication must use a function call (numpy.dot). For numpy.matrix objects, * performs matrix multiplication, and elementwise multiplication requires function syntax. Writing code using numpy.ndarray works fine. Writing code using numpy.matrix also works fine. But trouble begins as soon as we try to integrate these two pieces of code together. Code that expects an ndarray and gets a matrix, or vice-versa, may crash or return incorrect results

The introduction of the @ infix operator should help to unify and simplify python matrix code.

How to get element-wise matrix multiplication (Hadamard product) in numpy?

For elementwise multiplication of matrix objects, you can use numpy.multiply:

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)

Result

array([[ 5, 12],
       [21, 32]])

However, you should really use array instead of matrix. matrix objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use * for elementwise multiplication:

a * b

If you're on Python 3.5+, you don't even lose the ability to perform matrix multiplication with an operator, because @ does matrix multiplication now:

a @ b  # matrix multiplication

matrix multiplication algorithm time complexity

The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).

There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.

See this wikipedia article on Matrix Multiplication for more information.

Difference between numpy dot() and Python 3.5+ matrix multiplication @

In mathematics, I think the dot in numpy makes more sense

dot(a,b)_{i,j,k,a,b,c} = formula

since it gives the dot product when a and b are vectors, or the matrix multiplication when a and b are matrices


As for matmul operation in numpy, it consists of parts of dot result, and it can be defined as

>matmul(a,b)_{i,j,k,c} = formula

So, you can see that matmul(a,b) returns an array with a small shape, which has smaller memory consumption and make more sense in applications. In particular, combining with broadcasting, you can get

matmul(a,b)_{i,j,k,l} = formula

for example.


From the above two definitions, you can see the requirements to use those two operations. Assume a.shape=(s1,s2,s3,s4) and b.shape=(t1,t2,t3,t4)

  • To use dot(a,b) you need

    1. t3=s4;
  • To use matmul(a,b) you need

    1. t3=s4
    2. t2=s2, or one of t2 and s2 is 1
    3. t1=s1, or one of t1 and s1 is 1

Use the following piece of code to convince yourself.

Code sample

import numpy as np
for it in xrange(10000):
    a = np.random.rand(5,6,2,4)
    b = np.random.rand(6,4,3)
    c = np.matmul(a,b)
    d = np.dot(a,b)
    #print 'c shape: ', c.shape,'d shape:', d.shape

    for i in range(5):
        for j in range(6):
            for k in range(2):
                for l in range(3):
                    if not c[i,j,k,l] == d[i,j,k,j,l]:
                        print it,i,j,k,l,c[i,j,k,l]==d[i,j,k,j,l] #you will not see them

Matrix Multiplication in pure Python?

Matrix Multiplication in pure python.

def matmult(m1,m2):
r=[]
m=[]
for i in range(len(m1)):
    for j in range(len(m2[0])):
        sums=0
        for k in range(len(m2)):
            sums=sums+(m1[i][k]*m2[k][j])
        r.append(sums)
    m.append(r)
    r=[]
return m

How to redirect docker container logs to a single file?

docker logs -f docker_container_name >> YOUR_LOG_PATH 2>&1 &

Iteration ng-repeat only X times in AngularJs

in the html :

<div ng-repeat="t in getTimes(4)">text</div>

and in the controller :

$scope.getTimes=function(n){
     return new Array(n);
};

http://plnkr.co/edit/j5kNLY4Xr43CzcjM1gkj

EDIT :

with angularjs > 1.2.x

<div ng-repeat="t in getTimes(4) track by $index">TEXT</div>

T-SQL: How to Select Values in Value List that are NOT IN the Table?

You need to somehow create a table with these values and then use NOT IN. This can be done with a temporary table, a CTE (Common Table Expression) or a Table Values Constructor (available in SQL-Server 2008):

SELECT email
FROM
    ( VALUES 
        ('email1')
      , ('email2')
      , ('email3')
    ) AS Checking (email)
WHERE email NOT IN 
      ( SELECT email 
        FROM Users
      ) 

The second result can be found with a LEFT JOIN or an EXISTS subquery:

SELECT email
     , CASE WHEN EXISTS ( SELECT * 
                          FROM Users u
                          WHERE u.email = Checking.email
                        ) 
            THEN 'Exists'
            ELSE 'Not exists'
       END AS status 
FROM
    ( VALUES 
        ('email1')
      , ('email2')
      , ('email3')
    ) AS Checking (email)

Remove Duplicates from range of cells in excel vba

If you got only one column in the range to clean, just add "(1)" to the end. It indicates in wich column of the range Excel will remove the duplicates. Something like:

 Sub norepeat()

    Range("C8:C16").RemoveDuplicates (1)

End Sub

Regards

What datatype to use when storing latitude and longitude data in SQL databases?

You should take a look at the new Spatial data-types that were introduced in SQL Server 2008. They are specifically designed this kind of task and make indexing and querying the data much easier and more efficient.

http://msdn.microsoft.com/en-us/library/bb933876(v=sql.105).aspx

C# naming convention for constants?

Leave Hungarian to the Hungarians.

In the example I'd even leave out the definitive article and just go with

private const int Answer = 42;

Is that answer or is that the answer?

*Made edit as Pascal strictly correct, however I was thinking the question was seeking more of an answer to life, the universe and everything.

Relation between CommonJS, AMD and RequireJS?

The short answer would be:

CommonJS and AMD are specifications (or formats) on how modules and their dependencies should be declared in javascript applications.

RequireJS is a script loader library that is AMD compliant, curljs being another example.

CommonJS compliant:

Taken from Addy Osmani's book.

// package/lib is a dependency we require
var lib = require( "package/lib" );

// behavior for our module
function foo(){
    lib.log( "hello world!" );
}

// export (expose) foo to other modules as foobar
exports.foobar = foo;

AMD compliant:

// package/lib is a dependency we require
define(["package/lib"], function (lib) {

    // behavior for our module
    function foo() {
        lib.log( "hello world!" );
    }

    // export (expose) foo to other modules as foobar
    return {
        foobar: foo
    }
});

Somewhere else the module can be used with:

require(["package/myModule"], function(myModule) {
    myModule.foobar();
});

Some background:

Actually, CommonJS is much more than an API declaration and only a part of it deals with that. AMD started as a draft specification for the module format on the CommonJS list, but full consensus wasn't reached and further development of the format moved to the amdjs group. Arguments around which format is better state that CommonJS attempts to cover a broader set of concerns and that it's better suited for server side development given its synchronous nature, and that AMD is better suited for client side (browser) development given its asynchronous nature and the fact that it has its roots in Dojo's module declaration implementation.

Sources:

Convert double to string

a = 0.000006;
b = 6;
c = a/b;

textbox.Text = c.ToString("0.000000");

As you requested:

textbox.Text = c.ToString("0.######");

This will only display out to the 6th decimal place if there are 6 decimals to display.

Failed to find 'ANDROID_HOME' environment variable

Execute: sudo gedit ~/.bashrc add

JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export JAVA_HOME
PATH=$PATH:$JAVA_HOME
export PATH
export ANDROID_HOME=~/Android/Sdk 
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

and

source ~/.bashrc

How can I assign an ID to a view programmatically?

Yes, you can call setId(value) in any view with any (positive) integer value that you like and then find it in the parent container using findViewById(value). Note that it is valid to call setId() with the same value for different sibling views, but findViewById() will return only the first one.

error C2220: warning treated as error - no 'object' file generated

This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):

warning C4101: 'i': unreferenced local variable

After I commented this unused i, and compiled it, the other error went away.

Counting Chars in EditText Changed Listener

little few change in your code :

TextView tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        tv.setText(String.valueOf(s.toString().length()));
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
}); 

Getting distance between two points based on latitude/longitude

import numpy as np


def Haversine(lat1,lon1,lat2,lon2, **kwarg):
    """
    This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is, 
    the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points 
    (ignoring any hills they fly over, of course!).
    Haversine
    formula:    a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)
    c = 2 · atan2( va, v(1-a) )
    d = R · c
    where   f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);
    note that angles need to be in radians to pass to trig functions!
    """
    R = 6371.0088
    lat1,lon1,lat2,lon2 = map(np.radians, [lat1,lon1,lat2,lon2])

    dlat = lat2 - lat1
    dlon = lon2 - lon1
    a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2) **2
    c = 2 * np.arctan2(a**0.5, (1-a)**0.5)
    d = R * c
    return round(d,4)

Remove stubborn underline from link

Sometimes what you're seeing is a box shadow, not a text underline.

Try this (using whatever CSS selectors are appropriate for you):

a:hover, a:visited, a:link, a:active {

    text-decoration: none!important;

    -webkit-box-shadow: none!important;
    box-shadow: none!important;
}

Why use armeabi-v7a code over armeabi code?

Depends on what your native code does, but v7a has support for hardware floating point operations, which makes a huge difference. armeabi will work fine on all devices, but will be a lot slower, and won't take advantage of newer devices' CPU capabilities. Do take some benchmarks for your particular application, but removing the armeabi-v7a binaries is generally not a good idea. If you need to reduce size, you might want to have two separate apks for older (armeabi) and newer (armeabi-v7a) devices.

call javascript function onchange event of dropdown list

Your code is working just fine, you have to declare javscript method before DOM ready.

your working example

What does "javascript:void(0)" mean?

Web Developers use javascript:void(0) because it is the easiest way to prevent the default behavior of a tag. void(*anything*) returns undefined and it is a falsy value. and returning a falsy value is like return false in onclick event of a tag that prevents its default behavior.

So I think javascript:void(0) is the simplest way to prevent the default behavior of a tag.

Make first letter of a string upper case (with maximum performance)

As BobBeechey suggests in his response to this question, the following code will work for this:

private void txt_fname_TextChanged(object sender, EventArgs e)
{
    char[] c = txt_fname.Text.ToCharArray();
    int j;
    for (j = 0; j < txt_fname.Text.Length; j++)
    {
        if (j==0) c[j]=c[j].ToString().ToUpper()[0];
        else c[j] = c[j].ToString().ToLower()[0];
    }
    txt_fname.Text = new string(c); 
    txt_fname.Select(txt_fname.Text.Length, 1);
}

Removing Duplicate Values from ArrayList

This will be the best way

    List<String> list = new ArrayList<String>();
    list.add("Krishna");
    list.add("Krishna");
    list.add("Kishan");
    list.add("Krishn");
    list.add("Aryan");
    list.add("Harm");

    Set<String> set=new HashSet<>(list);

Correct way to use Modernizr to detect IE?

Detecting CSS 3D transforms

Modernizr can detect CSS 3D transforms, yeah. The truthiness of Modernizr.csstransforms3d will tell you if the browser supports them.

The above link lets you select which tests to include in a Modernizr build, and the option you're looking for is available there.


Detecting IE specifically

Alternatively, as user356990 answered, you can use conditional comments if you're searching for IE and IE alone. Rather than creating a global variable, you can use HTML5 Boilerplate's <html> conditional comments trick to assign a class:

<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->

If you already have jQuery initialised, you can just check with $('html').hasClass('lt-ie9'). If you need to check which IE version you're in so you can conditionally load either jQuery 1.x or 2.x, you can do something like this:

myChecks.ltIE9 = (function(){
    var htmlElemClasses = document.querySelector('html').className.split(' ');
    if (!htmlElemClasses){return false;}
    for (var i = 0; i < htmlElemClasses.length; i += 1 ){
      var klass = htmlElemClasses[i];
      if (klass === 'lt-ie9'){
        return true;
      }
    }
    return false;
}());

N.B. IE conditional comments are only supported up to IE9 inclusive. From IE10 onwards, Microsoft encourages using feature detection rather than browser detection.


Whichever method you choose, you'd then test with

if ( myChecks.ltIE9 || Modernizr.csstransforms3d ){
    // iframe or flash fallback
} 

Don't take that || literally, of course.

Counting lines, words, and characters within a text file using Python

Functions that might be helpful:

  • open("file").read() which reads the contents of the whole file at once
  • 'string'.splitlines() which separates lines from each other (and discards empty lines)

By using len() and those functions you could accomplish what you're doing.

Why can't variables be declared in a switch statement?

C++ Standard has: It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).

The code to illustrate this rule:

#include <iostream>

using namespace std;

class X {
  public:
    X() 
    {
     cout << "constructor" << endl;
    }
    ~X() 
    {
     cout << "destructor" << endl;
    }
};

template <class type>
void ill_formed()
{
  goto lx;
ly:
  type a;
lx:
  goto ly;
}

template <class type>
void ok()
{
ly:
  type a;
lx:
  goto ly;
}

void test_class()
{
  ok<X>();
  // compile error
  ill_formed<X>();
}

void test_scalar() 
{
  ok<int>();
  ill_formed<int>();
}

int main(int argc, const char *argv[]) 
{
  return 0;
}

The code to show the initializer effect:

#include <iostream>

using namespace std;

int test1()
{
  int i = 0;
  // There jumps fo "case 1" and "case 2"
  switch(i) {
    case 1:
      // Compile error because of the initializer
      int r = 1; 
      break;
    case 2:
      break;
  };
}

void test2()
{
  int i = 2;
  switch(i) {
    case 1:
      int r;
      r= 1; 
      break;
    case 2:
      cout << "r: " << r << endl;
      break;
  };
}

int main(int argc, const char *argv[]) 
{
  test1();
  test2();
  return 0;
}

Change text color with Javascript?

Try below code:

$(document).ready(function(){
$('#about').css({'background-color':'black'});    
});

http://jsfiddle.net/jPCFC/

Android center view in FrameLayout doesn't work

Just follow this order

You can center any number of child in a FrameLayout.

<FrameLayout
    >
    <child1
        ....
        android:layout_gravity="center"
        .....
        />
    <Child2
        ....
        android:layout_gravity="center"
        />
</FrameLayout>

So the key is

adding android:layout_gravity="center"in the child views.

For example:

I centered a CustomView and a TextView on a FrameLayout like this

Code:

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    <com.airbnb.lottie.LottieAnimationView
        android:layout_width="180dp"
        android:layout_height="180dp"
        android:layout_gravity="center"
        app:lottie_fileName="red_scan.json"
        app:lottie_autoPlay="true"
        app:lottie_loop="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="10dp"
        android:textStyle="bold"
        android:padding="10dp"
        android:text="Networks Available: 1\n click to see all"
        android:gravity="center" />
</FrameLayout>

Result:

enter image description here

matplotlib get ylim values

I put above-mentioned methods together using ax instead of plt

import numpy as np
import matplotlib.pyplot as plt

x = range(100)
y = x

fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
ax.plot(x, y);

# method 1
print(ax.get_xlim())
print(ax.get_xlim())
# method 2
print(ax.axis())

enter image description here

How to remove entry from $PATH on mac

Close the terminal(End the current session). Open it again.

Turning off auto indent when pasting text into vim

Here is a post by someone who figured out how to remap the paste event to automatically turn paste mode on and then back off. Works for me in tmux/iTerm on MacOSX.

How to enable TLS 1.2 in Java 7

You can upgrade your Java 7 version to 1.7.0_131-b31

For JRE 1.7.0_131-b31 in Oracle site :

TLSv1.2 and TLSv1.1 are now enabled by default on the TLS client end-points. This is similar behavior to what already happens in JDK 8 releases.

Getting list of tables, and fields in each, in a database

I found an easy way to fetch the details of Tables and columns of a particular DB using SQL developer.

Select *FROM USER_TAB_COLUMNS

Move all files except one

The following is not a 100% guaranteed method, and should not at all be attempted for scripting. But some times it is good enough for quick interactive shell usage. A file file glob like

[abc]*

(which will match all files with names starting with a, b or c) can be negated by inserting a "^" character first, i.e.

[^abc]*

I sometimes use this for not matching the "lost+found" directory, like for instance:

mv /mnt/usbdisk/[^l]* /home/user/stuff/.

Of course if there are other files starting with l I have to process those afterwards.

How to get the file path from HTML input form in Firefox 3

For preview in Firefox works this - attachment is object of attachment element in first example:

           if (attachment.files)
             previewImage.src = attachment.files.item(0).getAsDataURL();
           else
             previewImage.src = attachment.value;

how to configure lombok in eclipse luna

Just remove the 'F:\' from -javaagent

-vm E:\Program Files\Java\jdk1.7.0_60\bin

-vmargs

-Dosgi.requiredJavaVersion=1.7

-javaagent:\Tools\Java Lib\Lombok\lombok.jar

-Xbootclasspath/a:F:\Tools\Java Lib\Lombok\lombok.jar

-Xms40m

-Xmx512m

Android: ScrollView force to bottom

If your minimum SDK is 23 or upper you could use this:

View childView = findViewById(R.id.your_view_id_in_the_scroll_view)
if(childView != null){
  scrollview.post(() -> scrollview.scrollToDescendant(childView));
}

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Mongoimport of json file

A bit late for probable answer, might help new people. In case you have multiple instances of database:

mongoimport --host <host_name>:<host_port> --db <database_name> --collection <collection_name>  --file <path_to_dump_file> -u <my_user> -p <my_pass>

Assuming credentials needed, otherwise remove this option.

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

What is an abstract class in PHP?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.

1. Can not instantiate abstract class: Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract.

Example below :

abstract class AbstractClass
{

    abstract protected function getValue();
    abstract protected function prefixValue($prefix);


    public function printOut() {
        echo "Hello how are you?";
    }
}

$obj=new AbstractClass();
$obj->printOut();
//Fatal error: Cannot instantiate abstract class AbstractClass

2. Any class that contains at least one abstract method must also be abstract: Abstract class can have abstract and non-abstract methods, but it must contain at least one abstract method. If a class has at least one abstract method, then the class must be declared abstract.

Note: Traits support the use of abstract methods in order to impose requirements upon the exhibiting class.

Example below :

class Non_Abstract_Class
{
   abstract protected function getValue();

    public function printOut() {
        echo "Hello how are you?";
    }
}

$obj=new Non_Abstract_Class();
$obj->printOut();
//Fatal error: Class Non_Abstract_Class contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Non_Abstract_Class::getValue)

3. An abstract method can not contain body: Methods defined as abstract simply declare the method's signature - they cannot define the implementation. But a non-abstract method can define the implementation.

abstract class AbstractClass
{
   abstract protected function getValue(){
   return "Hello how are you?";
   }

    public function printOut() {
        echo $this->getValue() . "\n";
    }
}

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";
//Fatal error: Abstract function AbstractClass::getValue() cannot contain body

4. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child :If you inherit an abstract class you have to provide implementations to all the abstract methods in it.

abstract class AbstractClass
{
    // Force Extending class to define this method
    abstract protected function getValue();

    // Common method
    public function printOut() {
        print $this->getValue() . "<br/>";
    }
}

class ConcreteClass1 extends AbstractClass
{
    public function printOut() {
        echo "dhairya";
    }

}
$class1 = new ConcreteClass1;
$class1->printOut();
//Fatal error: Class ConcreteClass1 contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (AbstractClass::getValue)

5. Same (or a less restricted) visibility:When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

Note that abstract method should not be private.

abstract class AbstractClass
{

    abstract public function getValue();
    abstract protected function prefixValue($prefix);

        public function printOut() {
        print $this->getValue();
    }
}

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."<br/>";
//Fatal error: Access level to ConcreteClass1::getValue() must be public (as in class AbstractClass)

6. Signatures of the abstract methods must match:When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child;the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature.

abstract class AbstractClass
{

    abstract protected function prefixName($name);

}

class ConcreteClass extends AbstractClass
{


    public function prefixName($name, $separator = ".") {
        if ($name == "Pacman") {
            $prefix = "Mr";
        } elseif ($name == "Pacwoman") {
            $prefix = "Mrs";
        } else {
            $prefix = "";
        }
        return "{$prefix}{$separator} {$name}";
    }
}

$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "<br/>";
echo $class->prefixName("Pacwoman"), "<br/>";
//output: Mr. Pacman
//        Mrs. Pacwoman

7. Abstract class doesn't support multiple inheritance:Abstract class can extends another abstract class,Abstract class can provide the implementation of interface.But it doesn't support multiple inheritance.

interface MyInterface{
    public function foo();
    public function bar();
}

abstract class MyAbstract1{
    abstract public function baz();
}


abstract class MyAbstract2 extends MyAbstract1 implements MyInterface{
    public function foo(){ echo "foo"; }
    public function bar(){ echo "bar"; }
    public function baz(){ echo "baz"; }
}

class MyClass extends MyAbstract2{
}

$obj=new MyClass;
$obj->foo();
$obj->bar();
$obj->baz();
//output: foobarbaz

Note: Please note order or positioning of the classes in your code can affect the interpreter and can cause a Fatal error. So, when using multiple levels of abstraction, be careful of the positioning of the classes within the source code.

below example will cause Fatal error: Class 'horse' not found

class cart extends horse {
    public function get_breed() { return "Wood"; }
}

abstract class horse extends animal {
    public function get_breed() { return "Jersey"; }
}

abstract class animal {
    public abstract function get_breed();
}

$cart = new cart();
print($cart->get_breed());

Cancel a vanilla ECMAScript 6 Promise chain

While there isn't a standard way of doing this in ES6, there is a library called Bluebird to handle this.

There is also a recommended way described as part of the react documentation. It looks similar to what you have in your 2 and 3rd updates.

const makeCancelable = (promise) => {
  let hasCanceled_ = false;

  const wrappedPromise = new Promise((resolve, reject) => {
    promise.then((val) =>
      hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
    );
    promise.catch((error) =>
      hasCanceled_ ? reject({isCanceled: true}) : reject(error)
    );
  });

  return {
    promise: wrappedPromise,
    cancel() {
      hasCanceled_ = true;
    },
  };
};

const cancelablePromise = makeCancelable(
  new Promise(r => component.setState({...}}))
);

cancelablePromise
  .promise
  .then(() => console.log('resolved'))
  .catch((reason) => console.log('isCanceled', reason.isCanceled));

cancelablePromise.cancel(); // Cancel the promise

Taken from: https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html

use video as background for div

Pure CSS method

It is possible to center a video inside an element just like a cover sized background-image without JS using the object-fit attribute or CSS Transforms.

2021 answer: object-fit

As pointed in the comments, it is possible to achieve the same result without CSS transform, but using object-fit, which I think it's an even better option for the same result:

_x000D_
_x000D_
.video-container {
    height: 300px;
    width: 300px;
    position: relative;
}

.video-container video {
  width: 100%;
  height: 100%;
  position: absolute;
  object-fit: cover;
  z-index: 0;
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}
_x000D_
<div class="video-container">
    <video autoplay muted loop>
        <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
    </video>
    <div class="caption">
      <h2>Your caption here</h2>
    </div>
</div>
_x000D_
_x000D_
_x000D_


Previous answer: CSS Transform

You can set a video as a background to any HTML element easily thanks to transform CSS property.

Note that you can use the transform technique to center vertically and horizontally any HTML element.

_x000D_
_x000D_
.video-container {
  height: 300px;
  width: 300px;
  overflow: hidden;
  position: relative;
}

.video-container video {
  min-width: 100%;
  min-height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}
_x000D_
<div class="video-container">
  <video autoplay muted loop>
    <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
  </video>
  <div class="caption">
    <h2>Your caption here</h2>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Using variable in SQL LIKE statement

As Andrew Brower says, but adding a trim

ALTER PROCEDURE <Name>
(
    @PartialName VARCHAR(50) = NULL
)

SELECT Name 
    FROM <table>
    WHERE Name LIKE '%' + LTRIM(RTRIM(@PartialName)) + '%'

Retrieve last 100 lines logs

You can simply use the following command:-

tail -NUMBER_OF_LINES FILE_NAME

e.g tail -100 test.log

  • will fetch the last 100 lines from test.log

In case, if you want the output of the above in a separate file then you can pipes as follows:-

tail -NUMBER_OF_LINES FILE_NAME > OUTPUT_FILE_NAME

e.g tail -100 test.log > output.log

  • will fetch the last 100 lines from test.log and store them into a new file output.log)

Why Java Calendar set(int year, int month, int date) not returning correct date?

1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:

c1.set(2000, Calendar.JANUARY, 30);

Post parameter is always null

Try creating a class to serve as the data model, then send a JSON object with properties matching the properties of your data model class. (Note: I have tested this and it works with the newest MVC 4 RC 2012 that I just downloaded today).

public HttpResponseMessage Post(ValueModel model)
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, "Value Recieved: " + model.Value);
}

public class ValueModel
{
    public string Value { get; set; }
}

The below JSON object is sent in HTTP-POST body, content-type is application/json

{ "value": "In MVC4 Beta you could map to simple types like string, but testing with RC 2012 I have only been able to map to DataModels and only JSON (application/json) and url-encoded (application/x-www-form-urlencoded body formats have worked. XML is not working for some reason" }

I believe the reason why you have to create a data model class is because simple values are assumed to be from the url parameters, and a single complex value is assumed to be from the body. They do have the [FromBody] and [FromUrl] attributes, but using [FromBody] string value still did not work for me. Seems like they are still working out a lot of bugs so I'm sure this will change in the future.

Edit: Got XML to work in the body. The default XML serializer was changed to DataContractSerializer instead of XmlSerializer. Putting the following line in my Global.asax file fixed this issue (reference)

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

send bold & italic text on telegram bot with html

According to the docs you can set the parse_mode field to:

  • MarkdownV2
  • HTML

Markdown still works but it's now considered a legacy mode.

You can pass the parse_mode parameter like this:

https://api.telegram.org/bot[yourBotKey]/sendMessage?chat_id=[yourChatId]&parse_mode=MarkdownV2&text=[yourMessage]

For bold and italic using MarkdownV2:

*bold text*
_italic text_

And for HTML:

<b>bold</b> or <strong>bold</strong>
<i>italic</I> or <em>italic</em>

Make sure to encode your query-string parameters regardless the format you pick. For example:

val message = "*bold text*";
val encodedMsg = URLEncoder.encode(message, "UTF-8");
  • Javascript (ref)
var message = "*bold text*"
var encodedMsg = encodeURIComponent(message)
$message = "*bold text*";
$encodedMsg = urlencode($message);

Refresh Fragment at reload

You cannot reload the fragment while it is attached to an Activity, where you get "Fragment Already Added" exception.

So the fragment has to be first detached from its activity and then attached. All can be done using the fluent api in one line:

getFragmentManager().beginTransaction().detach(this).attach(this).commit();

Update: This is to incorporate the changes made to API 26 and above:

FragmentTransaction transaction = mActivity.getFragmentManager()
                        .beginTransaction();
                if (Build.VERSION.SDK_INT >= 26) {
                    transaction.setReorderingAllowed(false);
                }
                transaction.detach(this).attach
                        (this).commit();

For more description of the update please see https://stackoverflow.com/a/51327440/4514796

How do I tell CMake to link in a static library in the source directory?

I found this helpful...

http://www.cmake.org/pipermail/cmake/2011-June/045222.html

From their example:

ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)

Display JSON Data in HTML Table

          <table id="myData">

          </table>

           <script type="text/javascript">
              $('#search').click(function() {
                    alert("submit handler has fired");
                    $.ajax({
                        type: 'POST',
                        url: 'cityResults.htm',
                        data: $('#cityDetails').serialize(),

                        success: function(data){ 
                            $.each(data, function( index, value ) {
                               var row = $("<tr><td>" + value.city + "</td><td>" + value.cStatus + "</td></tr>");
                               $("#myData").append(row);
                            });
                        },
                        error: function(jqXHR, textStatus, errorThrown){
                            alert('error: ' + textStatus + ': ' + errorThrown);
                        }
                    });
                    return false;//suppress natural form submission
                }); 

   </script>

loop through the data and append it to a table like the code above.

Is null reference possible?

The answer depends on your view point:


If you judge by the C++ standard, you cannot get a null reference because you get undefined behavior first. After that first incidence of undefined behavior, the standard allows anything to happen. So, if you write *(int*)0, you already have undefined behavior as you are, from a language standard point of view, dereferencing a null pointer. The rest of the program is irrelevant, once this expression is executed, you are out of the game.


However, in practice, null references can easily be created from null pointers, and you won't notice until you actually try to access the value behind the null reference. Your example may be a bit too simple, as any good optimizing compiler will see the undefined behavior, and simply optimize away anything that depends on it (the null reference won't even be created, it will be optimized away).

Yet, that optimizing away depends on the compiler to prove the undefined behavior, which may not be possible to do. Consider this simple function inside a file converter.cpp:

int& toReference(int* pointer) {
    return *pointer;
}

When the compiler sees this function, it does not know whether the pointer is a null pointer or not. So it just generates code that turns any pointer into the corresponding reference. (Btw: This is a noop since pointers and references are the exact same beast in assembler.) Now, if you have another file user.cpp with the code

#include "converter.h"

void foo() {
    int& nullRef = toReference(nullptr);
    cout << nullRef;    //crash happens here
}

the compiler does not know that toReference() will dereference the passed pointer, and assume that it returns a valid reference, which will happen to be a null reference in practice. The call succeeds, but when you try to use the reference, the program crashes. Hopefully. The standard allows for anything to happen, including the appearance of pink elephants.

You may ask why this is relevant, after all, the undefined behavior was already triggered inside toReference(). The answer is debugging: Null references may propagate and proliferate just as null pointers do. If you are not aware that null references can exist, and learn to avoid creating them, you may spend quite some time trying to figure out why your member function seems to crash when it's just trying to read a plain old int member (answer: the instance in the call of the member was a null reference, so this is a null pointer, and your member is computed to be located as address 8).


So how about checking for null references? You gave the line

if( & nullReference == 0 ) // null reference

in your question. Well, that won't work: According to the standard, you have undefined behavior if you dereference a null pointer, and you cannot create a null reference without dereferencing a null pointer, so null references exist only inside the realm of undefined behavior. Since your compiler may assume that you are not triggering undefined behavior, it can assume that there is no such thing as a null reference (even though it will readily emit code that generates null references!). As such, it sees the if() condition, concludes that it cannot be true, and just throw away the entire if() statement. With the introduction of link time optimizations, it has become plain impossible to check for null references in a robust way.


TL;DR:

Null references are somewhat of a ghastly existence:

Their existence seems impossible (= by the standard),
but they exist (= by the generated machine code),
but you cannot see them if they exist (= your attempts will be optimized away),
but they may kill you unaware anyway (= your program crashes at weird points, or worse).
Your only hope is that they don't exist (= write your program to not create them).

I do hope that will not come to haunt you!

How to use GNU Make on Windows?

You can add the application folder to your path from a command prompt using:

setx PATH "%PATH%;c:\MinGW\bin"

Note that you will probably need to open a new command window for the modified path setting to go into effect.

How to add new column to an dataframe (to the front not end)?

The previous answers show 3 approaches

  1. By creating a new data frame
  2. By using "cbind"
  3. By adding column "a", and sort data frame by columns using column names or indexes

Let me show #4 approach "By using "cbind" and "rename" that works for my case

1. Create data frame

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))

2. Get values for "new" column

new_column = c(0, 0, 0)

3. Combine "new" column with existed

df <- cbind(new_column, df)

4. Rename "new" column name

colnames(df)[1] <- "a"

Open JQuery Datepicker by clicking on an image w/ no input field

If you are using an input field and an icon (like this example):

<input name="hasta" id="Hasta"  type="text" readonly  />
<a href="#" id="Hasta_icono" ></a>

You can attach the datepicker to your icon (in my case inside the A tag via CSS) like this:

$("#Hasta").datepicker();
  $("#Hasta_icono").click(function() { 
   $("#Hasta").datepicker( "show" );
  });

How to programmatically set the Image source

Try this:

BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));

Why is the default value of the string type null instead of an empty string?

Why the designers of C# chose to use null as the default value of strings?

Because strings are reference types, reference types are default value is null. Variables of reference types store references to the actual data.

Let's use default keyword for this case;

string str = default(string); 

str is a string, so it is a reference type, so default value is null.

int str = (default)(int);

str is an int, so it is a value type, so default value is zero.

How do I POST JSON data with cURL?

You could also put your JSON content in a file and pass it to curl using the --upload-file option via standard input, like this:

 echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -

How to make a loop in x86 assembly language?

.model small
.stack 100h
.code 
Main proc
Mov cx , 30 ; //that number control the loop 30 means the loop will 
;excite 30 time 
Ioopfront:
Mov ah , 1
Int 21h 
Loop loopfront; 

this cod will take 30 character

Xcode/Simulator: How to run older iOS version?

Choosing older simulator versions is not obvious in Xcode 3.2.5. Older Xcodes had separate lists of "iOS Device SDKs" and "iOS Simulator SDKs" in the "Base SDK" build setting popup menu, but in Xcode 3.2.5 these have been replaced with a single "iOS SDKs" list that only offers 4.2 and "latest".

If you create a new default iOS project, it defaults to 4.2 for both Base SDK and Deployment Target, and in the "Overview" popup in the project's top-left corner, only the 4.2 Simulator is available.

To run an older iOS simulator, you must choose an older iOS version in the "iOS Deployment Target" build setting popup. Only then will the "Overview" popup offer older Simulators: back to 4.0 for iPhone and to 3.2 for iPad.

How to increase number of threads in tomcat thread pool?

From Tomcat Documentation

maxConnections When this number has been reached, the server will accept, but not process, one further connection. once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. (The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.) For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO and NIO2 the default is 10000. For APR/native, the default is 8192. Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.

maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.

Serializing an object as UTF-8 XML in .NET

No, you can use a StringWriter to get rid of the intermediate MemoryStream. However, to force it into XML you need to use a StringWriter which overrides the Encoding property:

public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

Or if you're not using C# 6 yet:

public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding { get { return Encoding.UTF8; } }
}

Then:

var serializer = new XmlSerializer(typeof(SomeSerializableObject));
string utf8;
using (StringWriter writer = new Utf8StringWriter())
{
    serializer.Serialize(writer, entry);
    utf8 = writer.ToString();
}

Obviously you can make Utf8StringWriter into a more general class which accepts any encoding in its constructor - but in my experience UTF-8 is by far the most commonly required "custom" encoding for a StringWriter :)

Now as Jon Hanna says, this will still be UTF-16 internally, but presumably you're going to pass it to something else at some point, to convert it into binary data... at that point you can use the above string, convert it into UTF-8 bytes, and all will be well - because the XML declaration will specify "utf-8" as the encoding.

EDIT: A short but complete example to show this working:

using System;
using System.Text;
using System.IO;
using System.Xml.Serialization;

public class Test
{    
    public int X { get; set; }

    static void Main()
    {
        Test t = new Test();
        var serializer = new XmlSerializer(typeof(Test));
        string utf8;
        using (StringWriter writer = new Utf8StringWriter())
        {
            serializer.Serialize(writer, t);
            utf8 = writer.ToString();
        }
        Console.WriteLine(utf8);
    }


    public class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding => Encoding.UTF8;
    }
}

Result:

<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <X>0</X>
</Test>

Note the declared encoding of "utf-8" which is what we wanted, I believe.

How do I remove trailing whitespace using a regular expression?

In Java:



String str = "    hello world  ";

// prints "hello world" 
System.out.println(str.replaceAll("^(\\s+)|(\\s+)$", ""));


Difference between a User and a Login in SQL Server

In Short,

Logins will have the access of the server.

and

Users will have the access of the database.

Storing query results into a variable and modifying it inside a Stored Procedure

Yup, this is possible of course. Here are several examples.

-- one way to do this
DECLARE @Cnt int

SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn

-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)

-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double

SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

A simple work around(it worked for me) is use the IP address instead of localhost. This should be fine for your development tasks.

If "0" then leave the cell blank

Your question is missing most of the necessary information, so I'm going to make some assumptions:

  1. Column H is your total summation
  2. You're putting this formula into H16
  3. Column G is additions to your summation
  4. Column F is deductions from your summation
  5. You want to leave the summation cell blank if there isn't a debit or credit entered

The answer would be:

=IF(COUNTBLANK(F16:G16)<>2,H15+G16-F16,"")

COUNTBLANK tells you how many cells are unfilled or set to "".
IF lets you conditionally do one of two things based on whether the first statement is true or false. The second comma separated argument is what to do if it's true, the third comma separated argument is what to do if it's false.
<> means "not equal to".

The equation says that if the number of blank cells in the range F16:G16 (your credit and debit cells) is not 2, which means both aren't blank, then calculate the equation you provided in your question. Otherwise set the cell to blank("").
When you copy this equation to new cells in column H other than H16, it will update the row references so the proper rows for the credit and debit amounts are looked at.

CAVEAT: This equation is useful if you are just adding entries for credits and debits to the end of a list and want the running total to update automatically. You'd fill this equation down to some arbitrary long length well past the end of actual data. You wouldn't see the running total past the end of the credit/debit entries then, it would just be blank until you filled in a new credit/debit entry. If you left a blank row in your credit debit entries though, the reference to the previous total, H15, would report blank, which is treated like a 0 in this case.

Move existing, uncommitted work to a new branch in Git

3 Steps to Commit your changes

Suppose you have created a new branch on GitHub with the name feature-branch.

enter image description here

FETCH

    git pull --all         Pull all remote branches
    git branch -a          List all branches now

Checkout and switch to the feature-branch directory. You can simply copy the branch name from the output of branch -a command above

git checkout -b feature-branch

VALIDATE

Next use the git branch command to see the current branch. It will show feature-branch with * In front of it

git branch         

COMMIT

git add .   add all files
git commit -m "Rafactore code or use your message"

Take update and the push changes on the origin server

 git pull origin feature-branch
 git push origin feature-branch

How do you change the character encoding of a postgres database?

# dump into file
pg_dump myDB > /tmp/myDB.sql

# create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'

# import in the new DB
psql -d tempDB -1 -f /tmp/myDB.sql

# rename databases
psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";' 
psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'

# see the result
psql myDB -c "SHOW LC_COLLATE"   

Binding arrow keys in JS/jQuery

This is a bit late, but HotKeys has a very major bug which causes events to get executed multiple times if you attach more than one hotkey to an element. Just use plain jQuery.

$(element).keydown(function(ev) {
    if(ev.which == $.ui.keyCode.DOWN) {
        // your code
        ev.preventDefault();
    }
});

MySQL VARCHAR size?

Actually, it will takes 101 bytes.

MySQL Reference

How to empty the content of a div

In jQuery it would be as simple as $('#yourDivID').empty()

See the documentation.

Unique random string generation

Update 2016/1/23

If you find this answer useful, you may be interested in a simple (~500 SLOC) password generation library I published:

Install-Package MlkPwgen

Then you can generate random strings just like in the answer below:

var str = PasswordGenerator.Generate(length: 10, allowed: Sets.Alphanumerics);

One advantage of the library is that the code is better factored out so you can use secure randomness for more than generating strings. Check out the project site for more details.

Original Answer

Since no one has provided secure code yet, I post the following in case anyone finds it useful.

string RandomString(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
    if (length < 0) throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
    if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty.");

    const int byteSize = 0x100;
    var allowedCharSet = new HashSet<char>(allowedChars).ToArray();
    if (byteSize < allowedCharSet.Length) throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize));

    // Guid.NewGuid and System.Random are not particularly random. By using a
    // cryptographically-secure random number generator, the caller is always
    // protected, regardless of use.
    using (var rng = System.Security.Cryptography.RandomNumberGenerator.Create()) {
        var result = new StringBuilder();
        var buf = new byte[128];
        while (result.Length < length) {
            rng.GetBytes(buf);
            for (var i = 0; i < buf.Length && result.Length < length; ++i) {
                // Divide the byte into allowedCharSet-sized groups. If the
                // random value falls into the last group and the last group is
                // too small to choose from the entire allowedCharSet, ignore
                // the value in order to avoid biasing the result.
                var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);
                if (outOfRangeStart <= buf[i]) continue;
                result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
            }
        }
        return result.ToString();
    }
}

Thanks to Ahmad for pointing out how to get the code working on .NET Core.

Change remote repository credentials (authentication) on Intellij IDEA 14

None of above worked for me. Using Android Studio 3.5 Beta 4. I even selected "do not save, forget passwords after restart" in file>settings>appearance & behavior>System settings>password

So What I did.

VCS>git>remotes

  • remove the repo and add again.
  • will ask for credentials.
  • then try git fetch in terminal.
  • Will prompt for password.
  • Issue fixed. :D

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

How to import a Python class that is in a directory above?

import sys
sys.path.append("..") # Adds higher directory to python modules path.

Python: Binding Socket: "Address already in use"

According to this link

Actually, SO_REUSEADDR flag can lead to much greater consequences: SO_REUSADDR permits you to use a port that is stuck in TIME_WAIT, but you still can not use that port to establish a connection to the last place it connected to. What? Suppose I pick local port 1010, and connect to foobar.com port 300, and then close locally, leaving that port in TIME_WAIT. I can reuse local port 1010 right away to connect to anywhere except for foobar.com port 300.

However you can completely avoid TIME_WAIT state by ensuring that the remote end initiates the closure (close event). So the server can avoid problems by letting the client close first. The application protocol must be designed so that the client knows when to close. The server can safely close in response to an EOF from the client, however it will also need to set a timeout when it is expecting an EOF in case the client has left the network ungracefully. In many cases simply waiting a few seconds before the server closes will be adequate.

I also advice you to learn more about networking and network programming. You should now at least how tcp protocol works. The protocol is quite trivial and small and hence, may save you a lot of time in future.

With netstat command you can easily see which programs ( (program_name,pid) tuple) are binded to which ports and what is the socket current state: TIME_WAIT, CLOSING, FIN_WAIT and so on.

A really good explanation of linux network configurations can be found https://serverfault.com/questions/212093/how-to-reduce-number-of-sockets-in-time-wait.

How do I keep CSS floats in one line?

Wrap your floating <div>s in a container <div> that uses this cross-browser min-width hack:

.minwidth { min-width:100px; width: auto !important; width: 100px; }

You may also need to set "overflow" but probably not.

This works because:

  • The !important declaration, combined with min-width cause everything to stay on the same line in IE7+
  • IE6 does not implement min-width, but it has a bug such that width: 100px overrides the !important declaration, causing the container width to be 100px.

How to set timeout on python's socket recv method?

The typical approach is to use select() to wait until data is available or until the timeout occurs. Only call recv() when data is actually available. To be safe, we also set the socket to non-blocking mode to guarantee that recv() will never block indefinitely. select() can also be used to wait on more than one socket at a time.

import select

mysocket.setblocking(0)

ready = select.select([mysocket], [], [], timeout_in_seconds)
if ready[0]:
    data = mysocket.recv(4096)

If you have a lot of open file descriptors, poll() is a more efficient alternative to select().

Another option is to set a timeout for all operations on the socket using socket.settimeout(), but I see that you've explicitly rejected that solution in another answer.

Enforcing the type of the indexed members of a Typescript object?

You can pass a name to the unknown key and then write your types:

type StuffBody = {
  [key: string]: string;
};

Now you can use it in your type checking:

let stuff: StuffBody = {};

But for FlowType there is no need to have name:

type StuffBody = {
  [string]: string,
};

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

Return a generic 400 status code, and then process that client-side.

Or you can keep the 401, and not return the WWW-Authenticate header, which is really what the browser is responding to with the authentication popup. If the WWW-Authenticate header is missing, then the browser won't prompt for credentials.

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

URL Encode a string in jQuery for an AJAX request

Try encodeURIComponent.

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Example:

var encoded = encodeURIComponent(str);

ng: command not found while creating new project using angular-cli

This worked for me:

  1. Go to C:\Users{{users}}\AppData\Roaming and delete the npm folder
  2. Uninstall node and install it again
  3. Run the command to install angular cli

    npm install -g @angular/cli
    

How can you speed up Eclipse?

I've disabled all unused options in Windows > Preferences > General and it has a huge positive impact on performance, eclipse is still slow when switching tabs, I don't want to increase memory, but it's a lot faster when scrolling. Thx for the tips.

What do multiple arrow functions mean in javascript?

It might be not totally related, but since the question mentioned react uses case (and I keep bumping into this SO thread): There is one important aspect of the double arrow function which is not explicitly mentioned here. Only the 'first' arrow(function) gets named (and thus 'distinguishable' by the run-time), any following arrows are anonymous and from React point of view count as a 'new' object on every render.

Thus double arrow function will cause any PureComponent to rerender all the time.

Example

You have a parent component with a change handler as:

handleChange = task => event => { ... operations which uses both task and event... };

and with a render like:

{ tasks.map(task => <MyTask handleChange={this.handleChange(task)}/> }

handleChange then used on an input or click. And this all works and looks very nice. BUT it means that any change that will cause the parent to rerender (like a completely unrelated state change) will also re-render ALL of your MyTask as well even though they are PureComponents.

This can be alleviated many ways such as passing the 'outmost' arrow and the object you would feed it with or writing a custom shouldUpdate function or going back to basics such as writing named functions (and binding the this manually...)

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

A temporary solution is to place the code below in the module build.gradle :

android { 
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
}

And Sync the Project.

public static const in TypeScript

The following solution also works as of TS 1.7.5.

// Constancts.ts    
export const kNotFoundInArray = -1;
export const AppConnectionError = new Error("The application was unable to connect!");
export const ReallySafeExtensions = ["exe", "virus", "1337h4x"];

To use:

// Main.ts    
import {ReallySafeExtensions, kNotFoundInArray} from "./Constants";

if (ReallySafeExtensions.indexOf("png") === kNotFoundInArray) {
    console.log("PNG's are really unsafe!!!");
}

Ansible: create a user with sudo privileges

To create a user with sudo privileges is to put the user into /etc/sudoers, or make the user a member of a group specified in /etc/sudoers. And to make it password-less is to additionally specify NOPASSWD in /etc/sudoers.

Example of /etc/sudoers:

## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
%wheel  ALL=(ALL)       NOPASSWD: ALL

And instead of fiddling with /etc/sudoers file, we can create a new file in /etc/sudoers.d/ directory since this directory is included by /etc/sudoers by default, which avoids the possibility of breaking existing sudoers file, and also eliminates the dependency on the content inside of /etc/sudoers.

To achieve above in Ansible, refer to the following:

- name: sudo without password for wheel group
  copy:
    content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
    dest: /etc/sudoers.d/wheel_nopasswd
    mode: 0440

You may replace %wheel with other group names like %sudoers or other user names like deployer.

ASP.NET MVC Ajax Error handling

Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);

And handle it as standard HTTP error on client as you like.

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

Check if at least two out of three booleans are true

The simplest form using ternary operators to solve the problem is:

return a ? (b ? true : c) : (b ? c : false);

You may also want to invest finding a solution by using double negation of the requirement, meaning to say, instead of at least two true values, you need to satisfy the condition at most one false value.

Using Linq select list inside list

list.Where(m => m.application == "applicationName" && 
           m.users.Any(u => u.surname=="surname"));

if you want to filter users as TimSchmelter commented, you can use

list.Where(m => m.application == "applicationName")
    .Select(m => new Model
    {
        application = m.application,
        users = m.users.Where(u => u.surname=="surname").ToList()
    });

Formatting a number with exactly two decimals in JavaScript

Put the following in some global scope:

Number.prototype.getDecimals = function ( decDigCount ) {
   return this.toFixed(decDigCount);
}

and then try:

var a = 56.23232323;
a.getDecimals(2); // will return 56.23

Update

Note that toFixed() can only work for the number of decimals between 0-20 i.e. a.getDecimals(25) may generate a javascript error, so to accomodate that you may add some additional check i.e.

Number.prototype.getDecimals = function ( decDigCount ) {
   return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}

DataTable: Hide the Show Entries dropdown but keep the Search box

sDom: "Tfrtip" or via a callback:

"fnHeaderCallback": function(){
    $('#YOURTABLENAME-table_length').hide();
}

A simple algorithm for polygon intersection

Here's a simple-and-stupid approach: on input, discretize your polygons into a bitmap. To intersect, AND the bitmaps together. To produce output polygons, trace out the jaggy borders of the bitmap and smooth the jaggies using a polygon-approximation algorithm. (I don't remember if that link gives the most suitable algorithms, it's just the first Google hit. You might check out one of the tools out there to convert bitmap images to vector representations. Maybe you could call on them without reimplementing the algorithm?)

The most complex part would be tracing out the borders, I think.

Back in the early 90s I faced something like this problem at work, by the way. I muffed it: I came up with a (completely different) algorithm that would work on real-number coordinates, but seemed to run into a completely unfixable plethora of degenerate cases in the face of the realities of floating-point (and noisy input). Perhaps with the help of the internet I'd have done better!

Using quotation marks inside quotation marks

in Python 3.2.2 on Windows,

print(""""A word that needs quotation marks" """) 

is ok. I think it is the enhancement of Python interpretor.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

For Drupal users, this Chris Lane's answer of:

ini_set('memory_limit', '-1');

works but we need to put it just after the opening

<?php

tag in the index.php file in your site's root directory.

MVC which submit button has been pressed

Name both your submit buttons the same

<input name="submit" type="submit" id="submit" value="Save" />
<input name="submit" type="submit" id="process" value="Process" />

Then in your controller get the value of submit. Only the button clicked will pass its value.

public ActionResult Index(string submit)
{
    Response.Write(submit);
    return View();
}

You can of course assess that value to perform different operations with a switch block.

public ActionResult Index(string submit)
{
    switch (submit)
    {
        case "Save":
            // Do something
            break;
        case "Process":
            // Do something
            break;
        default:
            throw new Exception();
            break;
    }

    return View();
}

What is the meaning of prepended double colon "::"?

This ensures that resolution occurs from the global namespace, instead of starting at the namespace you're currently in. For instance, if you had two different classes called Configuration as such:

class Configuration; // class 1, in global namespace
namespace MyApp
{
    class Configuration; // class 2, different from class 1
    function blah()
    {
        // resolves to MyApp::Configuration, class 2
        Configuration::doStuff(...) 
        // resolves to top-level Configuration, class 1
        ::Configuration::doStuff(...)
    }
}

Basically, it allows you to traverse up to the global namespace since your name might get clobbered by a new definition inside another namespace, in this case MyApp.

what is the multicast doing on 224.0.0.251?

If you don't have avahi installed then it's probably cups.

How to use hex() without 0x in Python?

Old style string formatting:

In [3]: "%02x" % 127
Out[3]: '7f'

New style

In [7]: '{:x}'.format(127)
Out[7]: '7f'

Using capital letters as format characters yields uppercase hexadecimal

In [8]: '{:X}'.format(127)
Out[8]: '7F'

Docs are here.

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

The download from java.com which installs in /Library/Internet Plug-Ins is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home which you can then add to Eclipse via Preferences -> Java -> Installed JREs.

Python - IOError: [Errno 13] Permission denied:

Maybe You are trying to open folder with open, check it once.

Git add all files modified, deleted, and untracked?

I'm not sure if it will add deleted files, but git add . from the root will add all untracked files.

How can you flush a write using a file descriptor?

I think what you are looking for may be

int fsync(int fd);

or

int fdatasync(int fd);

fsync will flush the file from kernel buffer to the disk. fdatasync will also do except for the meta data.

100% Min Height CSS layout

First you should create a div with id='footer' after your content div and then simply do this.

Your HTML should look like this:

<html>
    <body>
        <div id="content">
            ...
        </div>
        <div id="footer"></div>
    </body>
</html>

And the CSS:

?html, body {
    height: 100%;   
}
#content {
    height: 100%;
}
#footer {
    clear: both;        
}

grep output to show only matching file

Also remember one thing. Very important
You have to specify the command something like this to be more precise
grep -l "pattern" *

jQuery - Call ajax every 10 seconds

You could try setInterval() instead:

var i = setInterval(function(){
   //Call ajax here
},10000)

How to add a "open git-bash here..." context menu to the windows explorer?

When you install git-scm found in "https://git-scm.com/downloads" uncheck the "Only show new options" located at the very bottom of the installation window

Make sure you check

  • Windows Explorer integration
    • Git Bash Here
    • Git GUI Here

Click Next and you're good to go!

Generating a unique machine id

What about just using the UniqueID of the processor?

jQuery document.createElement equivalent?

var mydiv = $('<div />') // also works

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

I'd like explain the different alter table syntaxes - See the MySQL documentation

For adding/removing defaults on a column:

ALTER TABLE table_name
ALTER COLUMN col_name {SET DEFAULT literal | DROP DEFAULT}

For renaming a column, changing it's data type and optionally changing the column order:

ALTER TABLE table_name
CHANGE [COLUMN] old_col_name new_col_name column_definition
[FIRST|AFTER col_name]

For changing a column's data type and optionally changing the column order:

ALTER TABLE table_name
MODIFY [COLUMN] col_name column_definition
[FIRST | AFTER col_name]

Where is the WPF Numeric UpDown control?

This is example of my own UserControl with Up and Down key catching.

Xaml code:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="13" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="13" />
        <RowDefinition Height="13" />
    </Grid.RowDefinitions>
    <TextBox Name="NUDTextBox"  Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" TextAlignment="Right" PreviewKeyDown="NUDTextBox_PreviewKeyDown" PreviewKeyUp="NUDTextBox_PreviewKeyUp" TextChanged="NUDTextBox_TextChanged"/>
    <RepeatButton Name="NUDButtonUP"  Grid.Column="1" Grid.Row="0" FontSize="8" FontFamily="Marlett" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Click="NUDButtonUP_Click">5</RepeatButton>
    <RepeatButton Name="NUDButtonDown"  Grid.Column="1" Grid.Row="1" FontSize="8"  FontFamily="Marlett" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Height="13" VerticalAlignment="Bottom" Click="NUDButtonDown_Click">6</RepeatButton>
</Grid>

And the code:

public partial class NumericUpDown : UserControl
{
    int minvalue = 0, 
        maxvalue = 100,
        startvalue = 10;
    public NumericUpDown()
    {
        InitializeComponent();
        NUDTextBox.Text = startvalue.ToString();
    }

    private void NUDButtonUP_Click(object sender, RoutedEventArgs e)
    {
        int number;
        if (NUDTextBox.Text != "") number = Convert.ToInt32(NUDTextBox.Text);
        else number = 0;
        if (number < maxvalue)
            NUDTextBox.Text = Convert.ToString(number + 1); 
    }

    private void NUDButtonDown_Click(object sender, RoutedEventArgs e)
    {
        int number;
        if (NUDTextBox.Text != "") number = Convert.ToInt32(NUDTextBox.Text);
        else number = 0;
        if (number > minvalue)
            NUDTextBox.Text = Convert.ToString(number - 1); 
    }

    private void NUDTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {

        if (e.Key == Key.Up)
        {
            NUDButtonUP.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonUP, new object[] { true }); 
        }


        if (e.Key == Key.Down)
        {
            NUDButtonDown.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonDown, new object[] { true }); 
        }
    }

    private void NUDTextBox_PreviewKeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Up)
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonUP, new object[] { false });

        if (e.Key == Key.Down)
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonDown, new object[] { false });
    }

    private void NUDTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        int number = 0;
        if (NUDTextBox.Text!="")
            if (!int.TryParse(NUDTextBox.Text, out number)) NUDTextBox.Text = startvalue.ToString();
        if (number > maxvalue)  NUDTextBox.Text = maxvalue.ToString();
        if (number < minvalue) NUDTextBox.Text = minvalue.ToString();
        NUDTextBox.SelectionStart = NUDTextBox.Text.Length;

    }

}

Download all stock symbol list of a market

There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).

You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:

Company:  Vodafone
------------------
LSE symbol:    VOD
 in Google:    LON:VOD
 in Yahoo:     VOD.L
NASDAQ symbol: VOD
 in Google:    NASDAQ:VOD
 in Yahoo:     VOD

python int( ) function

import random
import time
import sys
while True:
    x=random.randint(1,100)
    print('''Guess my number--it's from 1 to 100.''')
    z=0
    while True:
        z=z+1
        xx=int(str(sys.stdin.readline()))
        if xx > x:
            print("Too High!")
        elif xx < x:
            print("Too Low!")
        elif xx==x:
            print("You Win!! You used %s guesses!"%(z))
            print()
            break
        else:
            break

in this, I first string the number str(), which converts it into an inoperable number. Then, I int() integerize it, to make it an operable number. I just tested your problem on my IDLE GUI, and it said that 49.8 < 50.

How do you align left / right a div without using float?

It is dirty better use the overflow: hidden; hack:

<div class="container">
  <div style="float: left;">Left Div</div>
  <div style="float: right;">Right Div</div>
</div>

.container { overflow: hidden; }

Or if you are going to do some fancy CSS3 drop-shadow stuff and you get in trouble with the above solution:

http://web.archive.org/web/20120414135722/http://fordinteractive.com/2009/12/goodbye-overflow-clearing-hack

PS

If you want to go for clean I would rather worry about that inline javascript rather than the overflow: hidden; hack :)

Cannot create SSPI context

We had this issue on instances in which we changed the service user from Domain1\ServiceUser to Domain2\ServiceUser. The SPNs remained registered under Domain1\ServiceUser, and never registered under Domain2\ServiceUser. We registered the SPNs under Domain2\ServiceUser, but the issue persisted. We then removed the SPNs under Domain1\ServiceUser, and the issue was resolved.

How can I select all options of multi-select select box on click?

For jQuery versions 1.6+ then

$('#select_all').click( function() {
    $('#countries option').prop('selected', true);
});

Or for older versions:

$('#select_all').click( function() {
    $('#countries option').attr('selected', 'selected');
});

LIVE DEMO

Using async/await for multiple tasks

I just want to add to all great answers above, that if you write a library it's a good practice to use ConfigureAwait(false) and get better performance, as said here.

So this snippet seems to be better:

 public static async Task DoWork() 
 {
     int[] ids = new[] { 1, 2, 3, 4, 5 };
     await Task.WhenAll(ids.Select(i => DoSomething(1, i))).ConfigureAwait(false);
 }

A full fiddle link here.

Why is Android Studio reporting "URI is not registered"?

Started getting this again, What actually works now is to add some rubbish inside build.gradle. Then try and sync. When it fails remove the rubbish and re-sync. After indexing, it works.

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

How about a solution where you put the actual "data" of the table inside its own div, with overflow: scroll;? Then the browser will automatically create scrollbars for the portion of the "table" you do not want to lock, and you can put the "table header"/first row just above that <div>.

Not sure how that would work with scrolling horizontally though.

Catch paste input

$("#textboxid").on('input propertychange', function () {
    //perform operation
        });

It will work fine.

How to perform a sum of an int[] array

int sum=0;
for(int i:A)
  sum+=i;

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

Bash can get the last part of a path without having to call the external basename:

subdir="/path/to/whatever/${1##*/}"

change PATH permanently on Ubuntu

Add

export PATH=$PATH:/home/me/play

to your ~/.profile and execute

source ~/.profile 

in order to immediately reflect changes to your current terminal instance.

How to implement and do OCR in a C# project?

If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:

  1. Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(https://github.com/charlesw/tesseract).
  2. Go to the Downloads section of the official Tesseract project (https://code.google.com/p/tesseract-ocr/ EDIT: It's now located here: https://github.com/tesseract-ocr/langdata).
  3. Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. Create tessdata directory in your project and place the language data files in it.
  5. Go to Properties of the newly added files and set them to copy on build.
  6. Add a reference to System.Drawing.
  7. From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
  8. Create the following two files in your project (just to get started):

Program.cs

using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
            {
                testImagePath = args[0];
            }

            try
            {
                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using (var img = Pix.LoadFromFile(testImagePath))
                    {
                        using (logger.Begin("Process image"))
                        {
                            var i = 1;
                            using (var page = engine.Process(img))
                            {
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                {
                                    iter.Begin();
                                    do
                                    {
                                        if (i % 2 == 0)
                                        {
                                            using (logger.Begin("Line {0}", i))
                                            {
                                                do
                                                {
                                                    using (logger.Begin("Word Iteration"))
                                                    {
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                        {
                                                            logger.Log("New block");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                        {
                                                            logger.Log("New paragraph");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                        {
                                                            logger.Log("New line");
                                                        }
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                    }
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                            }
                                        }
                                        i++;
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }



        private class ResultPrinter
        {
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
            {
                this.logger = logger;
            }

            public void Print(ResultIterator iter)
            {
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
            }
        }
    }
}

FormattedConsoleLogger.cs

using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
{
    public class FormattedConsoleLogger
    {
        const string Tab = "    ";
        private class Scope : DisposableBase
        {
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
            {
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                {
                    indent.Append(Tab);
                }
                this.indent = indent.ToString();
            }

            public void Log(string format, object[] args)
            {
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                {
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i += 2;
                    }
                    else if (message[i] == '\r' || message[i] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i++;
                    }
                    else
                    {
                        if (isNewLine)
                        {
                            indentedMessage.Append(indent);
                            isNewLine = false;
                        }
                        indentedMessage.Append(message[i]);
                        i++;
                    }
                }

                Console.WriteLine(indentedMessage.ToString());

            }

            public Scope Begin()
            {
                return new Scope(container, indentLevel + 1);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    var scope = container.scopes.Pop();
                    if (scope != this)
                    {
                        throw new InvalidOperationException("Format scope removed out of order.");
                    }
                }
            }
        }

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
        {
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
            {
                scope = new Scope(this, 1);
            }
            else
            {
                scope = ActiveScope.Begin();
            }
            scopes.Push(scope);
            return scope;
        }

        public void Log(string format, params object[] args)
        {
            if (scopes.Count > 0)
            {
                ActiveScope.Log(format, args);
            }
            else
            {
                Console.WriteLine(String.Format(format, args));
            }
        }

        private Scope ActiveScope
        {
            get
            {
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;
            }
        }
    }
}

Use grep to report back only line numbers

I recommend the answers with sed and awk for just getting the line number, rather than using grep to get the entire matching line and then removing that from the output with cut or another tool. For completeness, you can also use Perl:

perl -nE '/pattern/ && say $.' filename

or Ruby:

ruby -ne 'puts $. if /pattern/' filename

How to replace plain URLs with links?

Replacing URLs with links (Answer to the General Problem)

The regular expression in the question misses a lot of edge cases. When detecting URLs, it's always better to use a specialized library that handles international domain names, new TLDs like .museum, parentheses and other punctuation within and at the end of the URL, and many other edge cases. See the Jeff Atwood's blog post The Problem With URLs for an explanation of some of the other issues.

The best summary of URL matching libraries is in Dan Dascalescu's Answer +100
(as of Feb 2014)


"Make a regular expression replace more than one match" (Answer to the specific problem)

Add a "g" to the end of the regular expression to enable global matching:

/ig;

But that only fixes the problem in the question where the regular expression was only replacing the first match. Do not use that code.

Evaluate a string with a switch in C++

You can't. Full stop.

switch is only for integral types, if you want to branch depending on a string you need to use if/else.

How do I resolve "Cannot find module" error using Node.js?

For TypeScript users, if you are importing a built-in Node module (such as http, path or url) and you are getting an error such as "Cannot find module "x" then the error can be fixed by running

npm install @types/node --save-dev

The command will import the NodeJS TypeScript definitions into your project, allowing you to use Node's built-in modules.

How do I remove a CLOSE_WAIT socket connection

You can forcibly close sockets with ss command; the ss command is a tool used to dump socket statistics and displays information in similar fashion (although simpler and faster) to netstat.

To kill any socket in CLOSE_WAIT state, run this (as root)

$ ss --tcp state CLOSE-WAIT --kill

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

npm install error - unable to get local issuer certificate

Well this is not a right answer but can be consider as a quick workaround. Right answer is turn off Strict SSL.

I am having the same error

PhantomJS not found on PATH
Downloading https://github.com/Medium/phantomjs/releases/download/v2.1.1/phantomjs-2.1.1-windows.zip
Saving to C:\Users\Sam\AppData\Local\Temp\phantomjs\phantomjs-2.1.1-windows.zip
Receiving...

Error making request.
Error: unable to get local issuer certificate
at TLSSocket. (_tls_wrap.js:1105:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket._finishInit (_tls_wrap.js:639:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:469:38)

So the after reading the error.

Just downloaded the file manually and placed it on the required path. i.e

C:\Users\Sam\AppData\Local\Temp\phantomjs\

This solved my problem.

    PhantomJS not found on PATH                                                                                                
Download already available at C:\Users\sam\AppData\Local\Temp\phantomjs\phantomjs-2.1.1-windows.zip                    
Verified checksum of previously downloaded file                                                                            
Extracting zip contents                                    

How to execute a MySQL command from a shell script?

To "automate" the process of importing the generated .sql file, while avoiding all the traps that can be hidden in trying to pass files through stdin and stdout, just tell MySQL to execute the generated .sql file using the SOURCE command in MySQL.

The syntax in the short, but excellent, answer, from Kshitij Sood, gives the best starting point. In short, modify the OP's command according to Kshitij Sood's syntax and replace the commands in that with the SOURCE command:

#!/bin/bash
mysql -u$user -p$password $dbname -Bse "SOURCE ds_fbids.sql
SOURCE ds_fbidx.sql"

If the database name is included in the generated .sql file, it can be dropped from the command.

The presumption here is that the generated file is valid as an .sql file on its own. By not having the file redirected, piped, or in any other manner handled by the shell, there is no issue with needing to escape any of the characters in the generated output because of the shell. The rules with respect to what needs to be escaped in an .sql file, of course, still apply.

How to deal with the security issues around the password on the command line, or in a my.cnf file, etc., has been well addressed in other answers, with some excellent suggestions. My favorite answer, from Danny, covers that, including how to handle the issue when dealing with cron jobs, or anything else.


To address a comment (question?) on the short answer I mentioned: No, it cannot be used with a HEREDOC syntax, as that shell command is given. HEREDOC can be used in the redirection version syntax, (without the -Bse option), since I/O redirection is what HEREDOC is built around. If you need the functionality of HEREDOC, it would be better to use it in the creation of a .sql file, even if it's a temporary one, and use that file as the "command" to execute with the MySQL batch line.

#!/bin/bash
cat >temp.sql <<SQL_STATEMENTS
...
SELECT \`column_name\` FROM \`table_name\` WHERE \`column_name\`='$shell_variable';
...
SQL_STATEMENTS
mysql -u $user -p$password $db_name -Be "SOURCE temp.sql"
rm -f temp.sql

Bear in mind that because of shell expansion you can use shell and environment variables within the HEREDOC. The down-side is that you must escape each and every backtick. MySQL uses them as the delimiters for identifiers but the shell, which gets the string first, uses them as executable command delimiters. Miss the escape on a single backtick of the MySQL commands, and the whole thing explodes with errors. The whole issue can be solved by using a quoted LimitString for the HEREDOC:

#!/bin/bash
cat >temp.sql <<'SQL_STATEMENTS'
...
SELECT `column_name` FROM `table_name` WHERE `column_name`='constant_value';
...
SQL_STATEMENTS
mysql -u $user -p$password $db_name -Be "SOURCE temp.sql"
rm -f temp.sql

Removing shell expansion that way eliminates the need to escape the backticks, and other shell-special characters. It also removes the ability to use shell and environment variables within it. That pretty much removes the benefits of using a HEREDOC inside the shell script to begin with.

The other option is to use the multi-line quoted strings allowed in Bash with the batch syntax version (with the -Bse). I don't know other shells, so I cannot say if they work therein as well. You would need to use this for executing more than one .sql file with the SOURCE command anyway, since that is not terminated by a ; as other MySQL commands are, and only one is allowed per line. The multi-line string can be either single or double quoted, with the normal effects on shell expansion. It also has the same caveats as using the HEREDOC syntax does for backticks, etc.

A potentially better solution would be to use a scripting language, Perl, Python, etc., to create the .sql file, as the OP did, and SOURCE that file using the simple command syntax at the top. The scripting languages are much better at string manipulation than the shell is, and most have in-built procedures to handle the quoting and escaping needed when dealing with MySQL.

Twitter bootstrap hide element on small devices

Bootstrap 4

The display (hidden/visible) classes are changed in Bootstrap 4. To hide on the xs viewport use:

d-none d-sm-block

Also see: Missing visible-** and hidden-** in Bootstrap v4


Bootstrap 3 (original answer)

Use the hidden-xs utility class..

<nav class="col-sm-3 hidden-xs">
        <ul class="list-unstyled">
        <li>Text 10</li>
        <li>Text 11</li>
        <li>Text 12</li>
        </ul>
</nav>

http://bootply.com/90722

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

For me the issue was signing into my Google account on the debug Chrome window. This had been working fine for me until I signed in. Once I signed out of that instance of Chrome AND choose to delete all of my settings via the checkbox, the debugger worked fine again.

My non-debugging instance of Chrome was still signed into Google and unaffected. The main issue is that my lovely plugins are gone from the debug version, but at least I can step through client code again.

SFTP Libraries for .NET

For comprehensive SFTP support in .NET try edtFTPnet/PRO. It's been around a long time with support for many different SFTP servers.

We also sell an SFTP server for Windows, CompleteFTP, which is an inexpensive way to get support for SFTP on your Windows machine. Also has FTP and FTPS.

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

Authenticated HTTP proxy with Java

You're almost there, you just have to append:

-Dhttp.proxyUser=someUserName
-Dhttp.proxyPassword=somePassword

Getting time elapsed in Objective-C

Use the timeIntervalSinceDate method

NSTimeInterval secondsElapsed = [secondDate timeIntervalSinceDate:firstDate];

NSTimeInterval is just a double, define in NSDate like this:

typedef double NSTimeInterval;

Unable to install boto3

Try this it works sudo apt install python-pip pip install boto3

How do you modify a CSS style in the code behind file for divs in ASP.NET?

If you're newing up an element with initializer syntax, you can do something like this:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Attributes = { ["style"] = "min-width: 35px;" }
    },
  }
};

Or if using the CssStyleCollection specifically:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Style = { ["min-width"] = "35px" }
    },
  }
};

Check if string contains \n Java

If the string was constructed in the same program, I would recommend using this:

String newline = System.getProperty("line.separator");
boolean hasNewline = word.contains(newline);

But if you are specced to use \n, this driver illustrates what to do:

class NewLineTest {
    public static void main(String[] args) {
        String hasNewline = "this has a newline\n.";
        String noNewline = "this doesn't";

        System.out.println(hasNewline.contains("\n"));
        System.out.println(hasNewline.contains("\\n"));
        System.out.println(noNewline.contains("\n"));
        System.out.println(noNewline.contains("\\n"));

    }

}

Resulted in

true
false
false
false

In reponse to your comment:

class NewLineTest {
    public static void main(String[] args) {
        String word = "test\n.";
        System.out.println(word.length());
        System.out.println(word);
        word = word.replace("\n","\n ");
        System.out.println(word.length());
        System.out.println(word);

    }

}

Results in

6
test
.
7
test
 .

Passing an array of parameters to a stored procedure

If you are using Sql Server 2008 or better, you can use something called a Table-Valued Parameter (TVP) instead of serializing & deserializing your list data every time you want to pass it to a stored procedure.

Let's start by creating a simple schema to serve as our playground:

CREATE DATABASE [TestbedDb]
GO


USE [TestbedDb]
GO

    /* First, setup the sample program's account & credentials*/
CREATE LOGIN [testbedUser] WITH PASSWORD=N'µ×?
?S[°¿Q­¥½q?_Ĭ¼Ð)3õļ%dv', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON
GO

CREATE USER [testbedUser] FOR LOGIN [testbedUser] WITH DEFAULT_SCHEMA=[dbo]
GO

EXEC sp_addrolemember N'db_owner', N'testbedUser'
GO


    /* Now setup the schema */
CREATE TABLE dbo.Table1 ( t1Id INT NOT NULL PRIMARY KEY );
GO

INSERT INTO dbo.Table1 (t1Id)
VALUES
    (1),
    (2),
    (3),
    (4),
    (5),
    (6),
    (7),
    (8),
    (9),
    (10);
GO

With our schema and sample data in place, we are now ready to create our TVP stored procedure:

CREATE TYPE T1Ids AS Table (
        t1Id INT
);
GO


CREATE PROCEDURE dbo.FindMatchingRowsInTable1( @Table1Ids AS T1Ids READONLY )
AS
BEGIN
        SET NOCOUNT ON;

        SELECT Table1.t1Id FROM dbo.Table1 AS Table1
        JOIN @Table1Ids AS paramTable1Ids ON Table1.t1Id = paramTable1Ids.t1Id;
END
GO

With both our schema and API in place, we can call the TVP stored procedure from our program like so:

        // Curry the TVP data
        DataTable t1Ids = new DataTable( );
        t1Ids.Columns.Add( "t1Id",
                           typeof( int ) );

        int[] listOfIdsToFind = new[] {1, 5, 9};
        foreach ( int id in listOfIdsToFind )
        {
            t1Ids.Rows.Add( id );
        }
        // Prepare the connection details
        SqlConnection testbedConnection =
                new SqlConnection(
                        @"Data Source=.\SQLExpress;Initial Catalog=TestbedDb;Persist Security Info=True;User ID=testbedUser;Password=letmein12;Connect Timeout=5" );

        try
        {
            testbedConnection.Open( );

            // Prepare a call to the stored procedure
            SqlCommand findMatchingRowsInTable1 = new SqlCommand( "dbo.FindMatchingRowsInTable1",
                                                                  testbedConnection );
            findMatchingRowsInTable1.CommandType = CommandType.StoredProcedure;

            // Curry up the TVP parameter
            SqlParameter sqlParameter = new SqlParameter( "Table1Ids",
                                                          t1Ids );
            findMatchingRowsInTable1.Parameters.Add( sqlParameter );

            // Execute the stored procedure
            SqlDataReader sqlDataReader = findMatchingRowsInTable1.ExecuteReader( );

            while ( sqlDataReader.Read( ) )
            {
                Console.WriteLine( "Matching t1ID: {0}",
                                   sqlDataReader[ "t1Id" ] );
            }
        }
        catch ( Exception e )
        {
            Console.WriteLine( e.ToString( ) );
        }
  /* Output:
   * Matching t1ID: 1
   * Matching t1ID: 5
   * Matching t1ID: 9
   */

There is probably a less painful way to do this using a more abstract API, such as Entity Framework. However, I do not have the time to see for myself at this time.

Example on ToggleButton

I think what are attempting is semantically same as a radio button when 1 is when one of the options is selected and 0 is the other option.

I suggest using the radio button provided by Android by default.

Here is how to use it- http://www.mkyong.com/android/android-radio-buttons-example/

and the android documentation is here-

http://developer.android.com/guide/topics/ui/controls/radiobutton.html

Thanks.

ORA-00918: column ambiguously defined in SELECT *

You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:

SELECT DISTINCT
    coaches.id,
    people.*,
    users.*,
    coaches.*
FROM "COACHES"
    INNER JOIN people ON people.id = coaches.person_id
    INNER JOIN users ON coaches.person_id = users.person_id
    LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
    rownum <= 25

It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.

How do you connect to multiple MySQL databases on a single webpage?

if you are using mysqli and have two db_connection file. like first one is

define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define('**DB1**','database_name1');

$connMitra = new mysqli(HOST, USER, PASS, **DB1**);

second one is

    define('HOST','localhost');
    define('USER','user');
    define('PASS','passs');
    define(**'DB2**','database_name1');

    $connMitra = new mysqli(HOST, USER, PASS, **DB2**);

SO just change the name of parameter pass in mysqli like DB1 and DB2. if you pass same parameter in mysqli suppose DB1 in both file then second database will no connect any more. So remember when you use two or more connection pass different parameter name in mysqli function

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

I use the following maven dependencies to get java mail working. The first one includes the javax.mail API (with no implementation) and the second one is the SUN implementation of the javax.mail API.

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.5.5</version>
</dependency>
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.5.5</version>
</dependency>

SQL select only rows with max value on a column

I would use this:

select t.*
from test as t
join
   (select max(rev) as rev
    from test
    group by id) as o
on o.rev = t.rev

Subquery SELECT is not too eficient maybe, but in JOIN clause seems to be usable. I'm not an expert in optimizing queries, but I've tried at MySQL, PostgreSQL, FireBird and it does work very good.

You can use this schema in multiple joins and with WHERE clause. It is my working example (solving identical to yours problem with table "firmy"):

select *
from platnosci as p
join firmy as f
on p.id_rel_firmy = f.id_rel
join (select max(id_obj) as id_obj
      from firmy
      group by id_rel) as o
on o.id_obj = f.id_obj and p.od > '2014-03-01'

It is asked on tables having teens thusands of records, and it takes less then 0,01 second on really not too strong machine.

I wouldn't use IN clause (as it is mentioned somewhere above). IN is given to use with short lists of constans, and not as to be the query filter built on subquery. It is because subquery in IN is performed for every scanned record which can made query taking very loooong time.

Using OR & AND in COUNTIFS

There is probably a more efficient solution to your question, but following formula should do the trick:

=SUM(COUNTIFS(J1:J196,"agree",A1:A196,"yes"),COUNTIFS(J1:J196,"agree",A1:A196,"no"))

Custom ImageView with drop shadow

Here the Implementation of Paul Burkes answer:

public class ShadowImageView extends ImageView {

    public ShadowImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ShadowImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ShadowImageView(Context context) {
        super(context);
    }

    private Paint createShadow() {
        Paint mShadow = new Paint();

        float radius = 10.0f;
        float xOffset = 0.0f;
        float yOffset = 2.0f;

        // color=black
        int color = 0xFF000000;
        mShadow.setShadowLayer(radius, xOffset, yOffset, color);


        return mShadow;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint mShadow = createShadow();
        Drawable d = getDrawable();
        if (d != null){
            setLayerType(LAYER_TYPE_SOFTWARE, mShadow);
            Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
            canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
        } else {
            super.onDraw(canvas);
        }

    };

}

TODO: execute setLayerType(LAYER_TYPE_SOFTWARE, mShadow); only if API Level is > 10

How to increase heap size of an android application?

Use second process. Declare at AndroidManifest new Service with

android:process=":second"

Exchange between first and second process over BroadcastReceiver

How to shrink temp tablespace in oracle?

You should have written what version of Oracle you use. You most likely use something else than Oracle 11g, that's why you can't shrink a temp tablespace.

Alternatives:

1) alter database tempfile '[your_file]' resize 128M; which will probably fail
2) Drop and recreate the tablespace. If the temporary tablespace you want to shrink is your default temporary tablespace, you may have to first create a new temporary tablespace, set it as the default temporary tablespace then drop your old default temporary tablespace and recreate it. Afterwards drop the second temporary table created. 3) For Oracle 9i and higher you could just drop the tempfile(s) and add a new one(s)

Everything is described here in great detail.


See this link: http://databaseguide.blogspot.com/2008/06/resizing-temporary-tablespace.html
It was already linked, but maybe you missed it, so here it is again.

Where value in column containing comma delimited values

The solution tbaxter120 suggested worked for me but I needed something that will be supported both in MySQL & Oracle & MSSQL, and here it is:

WHERE (CONCAT(',' ,CONCAT(RTRIM(MyColumn), ','))) LIKE CONCAT('%,' , CONCAT(@search , ',%'))

Python Unicode Encode Error

Try adding the following line at the top of your python script.

# _*_ coding:utf-8 _*_

How to call a method in another class of the same package?

You can either create a static method or use the other class as a member of your class calling the function in the constructor.

public class aClass {
      private SomeOtherClass oc;
      public class aClass( SomeOtherClass otherClass) {
         oc = otherClass;
      }

      public callOtherClassMethod() {
         oc.otherClassMethod();
       }
    }

Purpose of #!/usr/bin/python3 shebang

The exec system call of the Linux kernel understands shebangs (#!) natively

When you do on bash:

./something

on Linux, this calls the exec system call with the path ./something.

This line of the kernel gets called on the file passed to exec: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_script.c#L25

if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))

It reads the very first bytes of the file, and compares them to #!.

If the comparison is true, then the rest of the line is parsed by the Linux kernel, which makes another exec call with path /usr/bin/python3 and current file as the first argument:

/usr/bin/python3 /path/to/script.py

and this works for any scripting language that uses # as a comment character.

And analogously, if you decide to use env instead, which you likely should always do to work on systems that have the python3 in a different location, notably pyenv, see also this question, the shebang:

#!/usr/bin/env python3

ends up calling analogously:

/usr/bin/env python3 /path/to/script.py

which does what you expect from env python3: searches PATH for python3 and runs /usr/bin/python3 /path/to/script.py.

And yes, you can make an infinite loop with:

printf '#!/a\n' | sudo tee /a
sudo chmod +x /a
/a

Bash recognizes the error:

-bash: /a: /a: bad interpreter: Too many levels of symbolic links

#! just happens to be human readable, but that is not required.

If the file started with different bytes, then the exec system call would use a different handler. The other most important built-in handler is for ELF executable files: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_elf.c#L1305 which checks for bytes 7f 45 4c 46 (which also happens to be human readable for .ELF). Let's confirm that by reading the 4 first bytes of /bin/ls, which is an ELF executable:

head -c 4 "$(which ls)" | hd 

output:

00000000  7f 45 4c 46                                       |.ELF|
00000004                                                                 

So when the kernel sees those bytes, it takes the ELF file, puts it into memory correctly, and starts a new process with it. See also: How does kernel get an executable binary file running under linux?

Finally, you can add your own shebang handlers with the binfmt_misc mechanism. For example, you can add a custom handler for .jar files. This mechanism even supports handlers by file extension. Another application is to transparently run executables of a different architecture with QEMU.

I don't think POSIX specifies shebangs however: https://unix.stackexchange.com/a/346214/32558 , although it does mention in on rationale sections, and in the form "if executable scripts are supported by the system something may happen". macOS and FreeBSD also seem to implement it however.

PATH search motivation

Likely, one big motivation for the existence of shebangs is the fact that in Linux, we often want to run commands from PATH just as:

basename-of-command

instead of:

/full/path/to/basename-of-command

But then, without the shebang mechanism, how would Linux know how to launch each type of file?

Hardcoding the extension in commands:

 basename-of-command.py

or implementing PATH search on every interpreter:

python3 basename-of-command

would be a possibility, but this has the major problem that everything breaks if we ever decide to refactor the command into another language.

Shebangs solve this problem beautifully.

See also: Why do people write #!/usr/bin/env python on the first line of a Python script?

Is there a way for non-root processes to bind to "privileged" ports on Linux?

Since the OP is just development/testing, less than sleek solutions may be helpful:

setcap can be used on a script's interpreter to grant capabilities to scripts. If setcaps on the global interpreter binary is not acceptable, make a local copy of the binary (any user can) and get root to setcap on this copy. Python2 (at least) works properly with a local copy of the interpreter in your script development tree. No suid is needed so the root user can control to what capabilities users have access.

If you need to track system-wide updates to the interpreter, use a shell script like the following to run your script:

#!/bin/sh
#
#  Watch for updates to the Python2 interpreter

PRG=python_net_raw
PRG_ORIG=/usr/bin/python2.7

cmp $PRG_ORIG $PRG || {
    echo ""
    echo "***** $PRG_ORIG has been updated *****"
    echo "Run the following commands to refresh $PRG:"
    echo ""
    echo "    $ cp $PRG_ORIG $PRG"
    echo "    # setcap cap_net_raw+ep $PRG"
    echo ""
    exit
}

./$PRG $*

How to display and hide a div with CSS?

you can use any of the following five ways to hide element, depends upon your requirements.

Opacity

.hide {
  opacity: 0;
}

Visibility

.hide {
   visibility: hidden;
}

Display

.hide {
   display: none;
}

Position

.hide {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

clip-path

.hide {
  clip-path: polygon(0px 0px,0px 0px,0px 0px,0px 0px);
}

To show use any of the following: opacity: 1; visibility: visible; display: block;

Source : https://www.sitepoint.com/five-ways-to-hide-elements-in-css/

jQuery toggle animation

onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');" 

onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"

Just put two stops -- one onmouseover and one onmouseout.

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

Using Java to find substring of a bigger string using Regular Expression

If you simply need to get whatever is between [], the you can use \[([^\]]*)\] like this:

Pattern regex = Pattern.compile("\\[([^\\]]*)\\]");
Matcher m = regex.matcher(str);
if (m.find()) {
    result = m.group();
}

If you need it to be of the form identifier + [ + content + ] then you can limit extracting the content only when the identifier is a alphanumerical:

[a-zA-Z][a-z-A-Z0-9_]*\s*\[([^\]]*)\]

This will validate things like Foo [Bar], or myDevice_123["input"] for instance.

Main issue

The main problem is when you want to extract the content of something like this:

FOO[BAR[CAT[123]]+DOG[FOO]]

The Regex won't work and will return BAR[CAT[123 and FOO.
If we change the Regex to \[(.*)\] then we're OK but then, if you're trying to extract the content from more complex things like:

FOO[BAR[CAT[123]]+DOG[FOO]] = myOtherFoo[BAR[5]]

None of the Regexes will work.

The most accurate Regex to extract the proper content in all cases would be a lot more complex as it would need to balance [] pairs and give you they content.

A simpler solution

If your problems is getting complex and the content of the [] arbitrary, you could instead balance the pairs of [] and extract the string using plain old code rathe than a Regex:

int i;
int brackets = 0;
string c;
result = "";
for (i = input.indexOf("["); i < str.length; i++) {
    c = str.substring(i, i + 1);
    if (c == '[') {
        brackets++;
    } else if (c == ']') {
        brackets--;
        if (brackets <= 0) 
            break;
    }
    result = result + c;
}   

This is more pseudo-code than real code, I'm not a Java coder so I don't know if the syntax is correct, but it should be easy enough to improve upon.
What count is that this code should work and allow you to extract the content of the [], however complex it is.

Error - is not marked as serializable

You need to add a Serializable attribute to the class which you want to serialize.

[Serializable]
public class OrgPermission

What are XAND and XOR

Guys, don´t scare the crap out of others (hey! just kidding), but it´s really all a question of equivalences and synonyms:

firstly:

"XAND" doesn´t exist logically, neither does "XNAND", however "XAND" is normally thought-up by a studious but confused initiating logic student.(wow!). It com from the thought that, if there´s a XOR(exclusive OR) it´s logical to exist a "XAND"("exclusive" AND). The rational suggestion would be an "IAND"("inclusive" AND), which isn´t used or recognised as well. So:

 XNOR <=> !XOR <=> EQV

And all this just discribes a unique operator, called the equivalency operator(<=>, EQV) so:

A  |  B  | A <=> B | A XAND B | A XNOR B | A !XOR B | ((NOT(A) AND B)AND(A AND NOT(B)))
---------------------------------------------------------------------------------------
T  |  T  |    T    |     T    |     T    |     T    |                T    
T  |  F  |    F    |     F    |     F    |     F    |                F    
F  |  T  |    F    |     F    |     F    |     F    |                F    
F  |  F  |    T    |     T    |     T    |     T    |                T    

And just a closing comment: The 'X' prefix is only possible if and only if the base operator isn´t unary. So, XNOR <=> NOT XOR <=/=> X NOR.

Peace.

How do you perform a left outer join using linq extension methods

Group Join method is unnecessary to achieve joining of two data sets.

Inner Join:

var qry = Foos.SelectMany
            (
                foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id),
                (foo, bar) => new
                    {
                    Foo = foo,
                    Bar = bar
                    }
            );

For Left Join just add DefaultIfEmpty()

var qry = Foos.SelectMany
            (
                foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id).DefaultIfEmpty(),
                (foo, bar) => new
                    {
                    Foo = foo,
                    Bar = bar
                    }
            );

EF and LINQ to SQL correctly transform to SQL. For LINQ to Objects it is beter to join using GroupJoin as it internally uses Lookup. But if you are querying DB then skipping of GroupJoin is AFAIK as performant.

Personlay for me this way is more readable compared to GroupJoin().SelectMany()

How to provide shadow to Button

you can use this great library https://github.com/BluRe-CN/ComplexView and it is really easy to use

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

I'm getting the same solution as @camino's comment on https://stackoverflow.com/a/19365454/10593190 and XavierStuvw's reply.

I got it to work (for installing ffmpeg) by simply reinstalling the whole thing from the beginning with all instances of $ ./configure replaced by $ ./configure --enable-shared (first make sure to delete all the folders and files including the .so files from the previous attempt).

Apparently this works because https://stackoverflow.com/a/13812368/10593190.

Calculate the number of business days between two dates?

Define an Extension Method on DateTime like so:

public static class DateTimeExtensions
{
    public static bool IsWorkingDay(this DateTime date)
    {
        return date.DayOfWeek != DayOfWeek.Saturday
            && date.DayOfWeek != DayOfWeek.Sunday;
    }
}

Then, use is within a Where clause to filter a broader list of dates:

var allDates = GetDates(); // method which returns a list of dates

// filter dates by working day's  
var countOfWorkDays = allDates
     .Where(day => day.IsWorkingDay())
     .Count() ;

How do I set the eclipse.ini -vm option?

Assuming you have a jre folder, which contains bin, lib, etc files copied from a Java Runtime distribution, in the same folder as eclipse.ini, you can set in your eclilpse.ini

-vm
jre\bin\javaw.exe

How do I use Comparator to define a custom sort order?

I think this can be done as follows:

class ColorComparator implements Comparator<CarSort>
{
    private List<String> sortOrder;
    public ColorComparator (List<String> sortOrder){
        this.sortOrder = sortOrder;
    }

    public int compare(CarSort c1, CarSort c2)
    {
        String a1 = c1.getColor();
        String a2 = c2.getColor();
        return sortOrder.indexOf(a1) - sortOrder.indexOf(a2);
     }
 }

For sorting use this:

Collections.sort(carList, new ColorComparator(sortOrder));

Android Use Done button on Keyboard to click button

Your Last Edittext .setOnEditorActionListener call this method automatic hit api

I was Call in LoginActivity in et_password

 et_Pass.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {

                    Log.i(TAG,"Enter pressed");
                    Log.i(Check Internet," and Connect To Server");

                }
                return false;
            }
        });

Working Fine

Which characters are valid/invalid in a JSON key name?

No. Any valid string is a valid key. It can even have " as long as you escape it:

{"The \"meaning\" of life":42}

There is perhaps a chance you'll encounter difficulties loading such values into some languages, which try to associate keys with object field names. I don't know of any such cases, however.

Differences between TCP sockets and web sockets, one more time

When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.

But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.

Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.

To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data to an array before not after you try to slice it:

R = np.array(mean_data)[:,0]

instead of

R = np.array(mean_data[:,0])

But, assuming mean_data has a shape nx3, instead of

R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]

You can simply do

A = np.array(mean_data).mean(axis=0)

which averages over the 0th axis and returns a length-n array

But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:

How to get current screen width in CSS?

Use the CSS3 Viewport-percentage feature.

Viewport-Percentage Explanation

Assuming you want the body width size to be a ratio of the browser's view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <title>Styles</title>_x000D_
_x000D_
    <style>_x000D_
        @media screen and (min-width: 480px) {_x000D_
            body {_x000D_
                background-color: skyblue;_x000D_
                width: 90vw;_x000D_
                height: 90vh;_x000D_
                border: groove black;_x000D_
            }_x000D_
_x000D_
            div#main {_x000D_
                font-size: 3vw;_x000D_
            }_x000D_
        }_x000D_
    </style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
    <div id="main">_x000D_
        Viewport-Percentage Test_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

cannot find zip-align when publishing app

I had the same problem. And to fix it, I copy the Zipalign file from sdk/build-tools/android-4.4W folder to sdk/tools/

Edited: Since Google updated SDK for Android, new build-tools does fix this problem. So I encouraged everyone to update to Android SDK Build-tools 20 as suggested by Pang in the post below.

How do I put my website's logo to be the icon image in browser tabs?

It is called 'favicon' and you need to add below code to the header section of your website.

Simply add this to the <head> section.

<link rel="icon" href="/your_path_to_image/favicon.jpg">

Invoking a static method using reflection

String methodName= "...";
String[] args = {};

Method[] methods = clazz.getMethods();
for (Method m : methods) {
    if (methodName.equals(m.getName())) {
        // for static methods we can use null as instance of class
        m.invoke(null, new Object[] {args});
        break;
    }
}

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Update: Incredibly frustrating, but the Google redirect of the maven.google.com repo seems to mess with loading the resources. If you instead set your repository to maven { url 'https://dl.google.com/dl/android/maven2' } the files will resolve. You can prove this out by attempting to get the fully qualified resource at https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.0.0-alpha1/gradle-3.0.0-alpha1.pom 3.0.0 Alpha

This is because currently the gradle:3.0.0-alpha1 is only being served via the new 'https://maven.google.com' repository, but the site currently 404s at that location otherwise, being a public directory, you'd see a tree listing of all the files available by simply navigating to that location in your browser. When they resolve their outage, your CI build should pass immediately.

What is the preferred syntax for defining enums in JavaScript?

I wasn't satisfied with any of the answers, so I made Yet Another Enum (YEA!).

This implementation:

  • uses more up-to-date JS
  • requires just the declaration of this one class to easily create enums
  • has mapping by name (colors.RED), string (colors["RED"]), and index (colors[0]), but you only need to pass in the strings as an array
  • binds equivalent toString() and valueOf() functions to each enum object (if this is somehow not desired, one can simply remove it - small overhead for JS though)
  • has optional global naming/storage by name string
  • freezes the enum object once created so that it can't be modified

Special thanks to Andre 'Fi''s answer for some inspiration.


The codes:

class Enums {
  static create({ name = undefined, items = [] }) {
    let newEnum = {};
    newEnum.length = items.length;
    newEnum.items = items;
    for (let itemIndex in items) {
      //Map by name.
      newEnum[items[itemIndex]] = parseInt(itemIndex, 10);
      //Map by index.
      newEnum[parseInt(itemIndex, 10)] = items[itemIndex];
    }
    newEnum.toString = Enums.enumToString.bind(newEnum);
    newEnum.valueOf = newEnum.toString;
    //Optional naming and global registration.
    if (name != undefined) {
      newEnum.name = name;
      Enums[name] = newEnum;
    }
    //Prevent modification of the enum object.
    Object.freeze(newEnum);
    return newEnum;
  }
  static enumToString() {
    return "Enum " +
      (this.name != undefined ? this.name + " " : "") +
      "[" + this.items.toString() + "]";
  }
}

Usage:

let colors = Enums.create({
  name: "COLORS",
  items: [ "RED", "GREEN", "BLUE", "PORPLE" ]
});

//Global access, if named.
Enums.COLORS;

colors.items; //Array(4) [ "RED", "GREEN", "BLUE", "PORPLE" ]
colors.length; //4

colors.RED; //0
colors.GREEN; //1
colors.BLUE; //2
colors.PORPLE; //3
colors[0]; //"RED"
colors[1]; //"GREEN"
colors[2]; //"BLUE"
colors[3]; //"PORPLE"

colors.toString(); //"Enum COLORS [RED,GREEN,BLUE,PORPLE]"

//Enum frozen, makes it a real enum.
colors.RED = 9001;
colors.RED; //0

Jenkins, specifying JAVA_HOME

I was facing the same issue and for me downgrading the JAVA_HOME from jdk12 was not the plausible option like said in the answer. So I did a trial and error experiment and I got the Jenkins running without even downgrading the version of JAVA_HOME.

Steps:

  • open configuration $ sudo vi /etc/init.d/jenkins
  • Comment following line:
 #JAVA=`type -p java`
  • Introduced the line mentioned below. (Note: Insert the specific path of JDK in your machine.)
 JAVA=`type -p /usr/lib/jdk8/bin/java`
  • Reload systemd manager configuration: $ sudo systemctl daemon-reload
  • Start Jenkins service: $ sudo systemctl start jenkins
    ? jenkins.service - LSB: Start Jenkins at boot time
       Loaded: loaded (/etc/init.d/jenkins; generated)
       Active: active (exited) since Sun 2020-05-31 21:05:30 CEST; 9min ago
         Docs: man:systemd-sysv-generator(8)
      Process: 9055 ExecStart=/etc/init.d/jenkins start (code=exited, status=0/SUCCESS)
    

Test if a string contains any of the strings from an array

The below should work for you assuming Strings is the array that you are searching within:

Arrays.binarySearch(Strings,"mykeytosearch",mysearchComparator);

where mykeytosearch is the string that you want to test for existence within the array. mysearchComparator - is a comparator that would be used to compare strings.

Refer to Arrays.binarySearch for more information.

Formatting a float to 2 decimal places

string outString= number.ToString("####0.00");

In Angular, how to redirect with $location.path as $http.post success callback

I am doing the below for page redirection(from login to home page). I have to pass the user object also to the home page. so, i am using windows localstorage.

    $http({
        url:'/login/user',
        method : 'POST',
        headers: {
            'Content-Type': 'application/json'
          },
        data: userData
    }).success(function(loginDetails){
        $scope.updLoginDetails = loginDetails;
        if($scope.updLoginDetails.successful == true)
            {
                loginDetails.custId = $scope.updLoginDetails.customerDetails.cust_ID;
                loginDetails.userName = $scope.updLoginDetails.customerDetails.cust_NM;
                window.localStorage.setItem("loginDetails", JSON.stringify(loginDetails));
                $window.location='/login/homepage';
            }
        else
        alert('No access available.');

    }).error(function(err,status){
        alert('No access available.');      
    });

And it worked for me.

Align labels in form next to input

While the solutions here are workable, more recent technology has made for what I think is a better solution. CSS Grid Layout allows us to structure a more elegant solution.

The CSS below provides a 2-column "settings" structure, where the first column is expected to be a right-aligned label, followed by some content in the second column. More complicated content can be presented in the second column by wrapping it in a <div>.

[As a side-note: I use CSS to add the ':' that trails each label, as this is a stylistic element - my preference.]

_x000D_
_x000D_
/* CSS */_x000D_
_x000D_
div.settings {_x000D_
    display:grid;_x000D_
    grid-template-columns: max-content max-content;_x000D_
    grid-gap:5px;_x000D_
}_x000D_
div.settings label       { text-align:right; }_x000D_
div.settings label:after { content: ":"; }
_x000D_
<!-- HTML -->_x000D_
_x000D_
<div class="settings">_x000D_
    <label>Label #1</label>_x000D_
    <input type="text" />_x000D_
_x000D_
    <label>Long Label #2</label>_x000D_
    <span>Display content</span>_x000D_
_x000D_
    <label>Label #3</label>_x000D_
    <input type="text" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to create an array containing 1...N

no for create array in ES6 solutions

js no for 100 array

1. padStart


// string arr
const arr = [...``.padStart(100, ` `)].map((item, i) => i + 1 + ``);

// (100) ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100"]


// number arr
const arr = [...``.padStart(100, ` `)].map((item, i) => i + 1);

// (100) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]


2. Typed Arrays

Uint8Array

// number arr
const arr = new Uint8Array(100).map((item, i) => i + 1);

// Uint8Array(100) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

// string arr
const arr = [...new Uint8Array(100).map((item, i) => i + 1)].map((item, i) => i + 1 + ``);

// (100) ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100"]

Returning string from C function

Your pointer is pointing to local variable of the function. So as soon as you return from the function, memory gets deallocated. You have to assign memory on heap in order to use it in other functions.

Instead char *rtnPtr = word;

do this char *rtnPtr = malloc(length);

So that it is available in the main function. After it is used free the memory.

How to change the session timeout in PHP?

You can override values in php.ini from your PHP code using ini_set().

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

How can I check what version/edition of Visual Studio is installed programmatically?

For anyone stumbling on this question, here is the answer if you are doing C++: You can check in your cpp code for vs version like the example bellow which links against a library based on vs version being 2015 or higher:

#if (_MSC_VER > 1800)
#pragma comment (lib, "legacy_stdio_definitions.lib")
#endif

This is done at link time and no extra run-time cost.

Android Studio - How to increase Allocated Heap Size

You can try any one of the following

1)Change the gradle.properties file and change the heap size as per your requirement.

If org.gradle.jvmargs=-Xmx2048M is not sufficient then change to 4096 as given

org.gradle.jvmargs=-Xmx4096M enter image description here

2)"Edit Custom VM Options" from the Help menu.

It will open studio.vmoptions / studio64.exe.vmoptions file.

enter image description here Change the content to

-Xms128m

-Xmx4096m

-XX:MaxPermSize=1024m

-XX:ReservedCodeCacheSize=200m

-XX:+UseCompressedOops

Save the the file and restart Android Studio.

Passing parameter to controller from route in laravel

You don't need anything special for adding paramaters. Just like you had it.

Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups@show'));


class Groups_Controller extends Base_Controller {

    public $restful = true;    

    public function get_show($groupID) {
        return 'I am group id ' . $groupID;
    }  


}

What is the reason behind "non-static method cannot be referenced from a static context"?

The answers so far describe why, but here is a something else you might want to consider:

You can can call a method from an instantiable class by appending a method call to its constructor,

Object instance = new Constuctor().methodCall();

or

primitive name = new Constuctor().methodCall();

This is useful it you only wish to use a method of an instantiable class once within a single scope. If you are calling multiple methods from an instantiable class within a single scope, definitely create a referable instance.

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

pg_dump as insert statements 
pg_dump -d -O database filename
-d ( data as inserts ) -O ( capital O is no owner )

Then pipe the backup file back in to PostgreSQL using:

psql -d database -U username -h hostname < filename

As there is no owner included then all of the created table, schema, etc, are created under the login user you specify.

I have read this could be a good approach for migrating between PostgreSQL versions as well.

How to undo a git pull?

Reset the master branch:

git reset --hard origin/master

Netbeans 8.0.2 The module has not been deployed

I had the same error here but with glassfish server. Maybe it can help. I needed to configure the glassfish-web.xml file with the content inside the <resources> from glassfish-resources.xml. As I got another error I could find this annotation in the server log:

Caused by: java.lang.RuntimeException: Error in parsing WEB-INF/glassfish-web.xml for archive [file:/C:/Users/Win/Documents/NetBeansProjects/svad/build/web/]: The xml element should be [glassfish-web-app] rather than [resources]

All I did then was to change the <resources> tag and apply <glassfish-web-app> in the glassfish-web.xml file.

How can VBA connect to MySQL database in Excel?

Just a side note for anyone that stumbles onto this same inquiry... My Operating System is 64 bit - so of course I downloaded the 64 bit MySQL driver... however, my Office applications are 32 bit... Once I downloaded the 32 bit version, the error went away and I could move forward.

How should I validate an e-mail address?

Simplest Kotlin solution using extension functions:

fun String.isEmailValid() =
            Pattern.compile(
                    "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
                            "\\@" +
                            "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
                            "(" +
                            "\\." +
                            "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
                            ")+"
            ).matcher(this).matches()

and then you can validate like this:

"[email protected]".isEmailValid()

If you are in kotlin-multiplatform without access to Pattern, this is the equivalent:

fun String.isValidEmail() = Regex(emailRegexStr).matches(this)