Programs & Examples On #Unexpectendoffile

How to extract year and month from date in PostgreSQL without using to_char() function?

date_part(text, timestamp)

e.g.

date_part('month', timestamp '2001-02-16 20:38:40'),
date_part('year', timestamp '2001-02-16 20:38:40') 

http://www.postgresql.org/docs/8.0/interactive/functions-datetime.html

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Try to change the compatibility level, worked for me.

Verify what level it is

USE VJ_DATABASE;
GO
SELECT compatibility_level
FROM sys.databases WHERE name = 'VJ_DATABASE';
GO

Then make it compatible with the older version

ALTER DATABASE VJ_DATABASE
SET COMPATIBILITY_LEVEL = 110;   
GO
  • 100 = Sql Server 2008
  • 110 = Sql Server 2012
  • 120 = Sql Server 2014

By default, Sql Server 2014 will change the db versions compatibility to only 2014, using the @@ version you should be able to tell, which version Sql Server is.

Then run the command above to change it the version you have.

Additional step: Ensure you look at the accessibility of the DB is not reset, do this by right clicking on properties of the folder and the database. (make sure you have rights so you don't get an access denied)

How to call a method in MainActivity from another class?

But an error occurred which says java.lang.NullPointerException.

Thats because, you never initialized your MainActivity. you should initialize your object before you call its methods.

MainActivity mActivity = new MainActivity();//make sure that you pass the appropriate arguments if you have an args constructor
mActivity.startChronometer();

Abstract class in Java

An abstract class is a class which cannot be instantiated. An abstract class is used by creating an inheriting subclass that can be instantiated. An abstract class does a few things for the inheriting subclass:

  1. Define methods which can be used by the inheriting subclass.
  2. Define abstract methods which the inheriting subclass must implement.
  3. Provide a common interface which allows the subclass to be interchanged with all other subclasses.

Here's an example:

abstract public class AbstractClass
{
    abstract public void abstractMethod();
    public void implementedMethod() { System.out.print("implementedMethod()"); }
    final public void finalMethod() { System.out.print("finalMethod()"); }
}

Notice that "abstractMethod()" doesn't have any method body. Because of this, you can't do the following:

public class ImplementingClass extends AbstractClass
{
    // ERROR!
}

There's no method that implements abstractMethod()! So there's no way for the JVM to know what it's supposed to do when it gets something like new ImplementingClass().abstractMethod().

Here's a correct ImplementingClass.

public class ImplementingClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("abstractMethod()"); }
}

Notice that you don't have to define implementedMethod() or finalMethod(). They were already defined by AbstractClass.

Here's another correct ImplementingClass.

public class ImplementingClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("abstractMethod()"); }
    public void implementedMethod() { System.out.print("Overridden!"); }
}

In this case, you have overridden implementedMethod().

However, because of the final keyword, the following is not possible.

public class ImplementingClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("abstractMethod()"); }
    public void implementedMethod() { System.out.print("Overridden!"); }
    public void finalMethod() { System.out.print("ERROR!"); }
}

You can't do this because the implementation of finalMethod() in AbstractClass is marked as the final implementation of finalMethod(): no other implementations will be allowed, ever.

Now you can also implement an abstract class twice:

public class ImplementingClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("abstractMethod()"); }
    public void implementedMethod() { System.out.print("Overridden!"); }
}

// In a separate file.
public class SecondImplementingClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("second abstractMethod()"); }
}

Now somewhere you could write another method.

public tryItOut()
{
    ImplementingClass a = new ImplementingClass();
    AbstractClass b = new ImplementingClass();

    a.abstractMethod();    // prints "abstractMethod()"
    a.implementedMethod(); // prints "Overridden!"     <-- same
    a.finalMethod();       // prints "finalMethod()"

    b.abstractMethod();    // prints "abstractMethod()"
    b.implementedMethod(); // prints "Overridden!"     <-- same
    b.finalMethod();       // prints "finalMethod()"

    SecondImplementingClass c = new SecondImplementingClass();
    AbstractClass d = new SecondImplementingClass();

    c.abstractMethod();    // prints "second abstractMethod()"
    c.implementedMethod(); // prints "implementedMethod()"
    c.finalMethod();       // prints "finalMethod()"

    d.abstractMethod();    // prints "second abstractMethod()"
    d.implementedMethod(); // prints "implementedMethod()"
    d.finalMethod();       // prints "finalMethod()"
}

Notice that even though we declared b an AbstractClass type, it displays "Overriden!". This is because the object we instantiated was actually an ImplementingClass, whose implementedMethod() is of course overridden. (You may have seen this referred to as polymorphism.)

If we wish to access a member specific to a particular subclass, we must cast down to that subclass first:

// Say ImplementingClass also contains uniqueMethod()
// To access it, we use a cast to tell the runtime which type the object is
AbstractClass b = new ImplementingClass();
((ImplementingClass)b).uniqueMethod();

Lastly, you cannot do the following:

public class ImplementingClass extends AbstractClass, SomeOtherAbstractClass
{
    ... // implementation
}

Only one class can be extended at a time. If you need to extend multiple classes, they have to be interfaces. You can do this:

public class ImplementingClass extends AbstractClass implements InterfaceA, InterfaceB
{
    ... // implementation
}

Here's an example interface:

interface InterfaceA
{
    void interfaceMethod();
}

This is basically the same as:

abstract public class InterfaceA
{
    abstract public void interfaceMethod();
}

The only difference is that the second way doesn't let the compiler know that it's actually an interface. This can be useful if you want people to only implement your interface and no others. However, as a general beginner rule of thumb, if your abstract class only has abstract methods, you should probably make it an interface.

The following is illegal:

interface InterfaceB
{
    void interfaceMethod() { System.out.print("ERROR!"); }
}

You cannot implement methods in an interface. This means that if you implement two different interfaces, the different methods in those interfaces can't collide. Since all the methods in an interface are abstract, you have to implement the method, and since your method is the only implementation in the inheritance tree, the compiler knows that it has to use your method.

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

Send cookies with curl

Very annoying, no cookie file exmpale on the official website https://ec.haxx.se/http/http-cookies.

Finnaly, I find it does not work, if your file content is just copyied like this

foo1=bar;foo2=bar2

I gusess the format must looks the style said by @Agustí Sánchez . You can test it by -c to create a cookie file on a website.

So try this way, it works

curl -H "Cookie:`cat ./my.cookie`"   http://xxxx.com

You can just copy the cookie from chrome console network tab.

Python read-only property

Here is a way to avoid the assumption that

all users are consenting adults, and thus are responsible for using things correctly themselves.

please see my update below

Using @property, is very verbose e.g.:

   class AClassWithManyAttributes:
        '''refactored to properties'''
        def __init__(a, b, c, d, e ...)
             self._a = a
             self._b = b
             self._c = c
             self.d = d
             self.e = e

        @property
        def a(self):
            return self._a
        @property
        def b(self):
            return self._b
        @property
        def c(self):
            return self._c
        # you get this ... it's long

Using

No underscore: it's a public variable.
One underscore: it's a protected variable.
Two underscores: it's a private variable.

Except the last one, it's a convention. You can still, if you really try hard, access variables with double underscore.

So what do we do? Do we give up on having read only properties in Python?

Behold! read_only_properties decorator to the rescue!

@read_only_properties('readonly', 'forbidden')
class MyClass(object):
    def __init__(self, a, b, c):
        self.readonly = a
        self.forbidden = b
        self.ok = c

m = MyClass(1, 2, 3)
m.ok = 4
# we can re-assign a value to m.ok
# read only access to m.readonly is OK 
print(m.ok, m.readonly) 
print("This worked...")
# this will explode, and raise AttributeError
m.forbidden = 4

You ask:

Where is read_only_properties coming from?

Glad you asked, here is the source for read_only_properties:

def read_only_properties(*attrs):

    def class_rebuilder(cls):
        "The class decorator"

        class NewClass(cls):
            "This is the overwritten class"
            def __setattr__(self, name, value):
                if name not in attrs:
                    pass
                elif name not in self.__dict__:
                    pass
                else:
                    raise AttributeError("Can't modify {}".format(name))

                super().__setattr__(name, value)
        return NewClass
    return class_rebuilder

update

I never expected this answer will get so much attention. Surprisingly it does. This encouraged me to create a package you can use.

$ pip install read-only-properties

in your python shell:

In [1]: from rop import read_only_properties

In [2]: @read_only_properties('a')
   ...: class Foo:
   ...:     def __init__(self, a, b):
   ...:         self.a = a
   ...:         self.b = b
   ...:         

In [3]: f=Foo('explodes', 'ok-to-overwrite')

In [4]: f.b = 5

In [5]: f.a = 'boom'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-a5226072b3b4> in <module>()
----> 1 f.a = 'boom'

/home/oznt/.virtualenvs/tracker/lib/python3.5/site-packages/rop.py in __setattr__(self, name, value)
    116                     pass
    117                 else:
--> 118                     raise AttributeError("Can't touch {}".format(name))
    119 
    120                 super().__setattr__(name, value)

AttributeError: Can't touch a

C/C++ include header file order

To add my own brick to the wall.

  1. Each header needs to be self-sufficient, which can only be tested if it's included first at least once
  2. One should not mistakenly modify the meaning of a third-party header by introducing symbols (macro, types, etc.)

So I usually go like this:

// myproject/src/example.cpp
#include "myproject/example.h"

#include <algorithm>
#include <set>
#include <vector>

#include <3rdparty/foo.h>
#include <3rdparty/bar.h>

#include "myproject/another.h"
#include "myproject/specific/bla.h"

#include "detail/impl.h"

Each group separated by a blank line from the next one:

  • Header corresponding to this cpp file first (sanity check)
  • System headers
  • Third-party headers, organized by dependency order
  • Project headers
  • Project private headers

Also note that, apart from system headers, each file is in a folder with the name of its namespace, just because it's easier to track them down this way.

How to set a cookie for another domain

Here is what I've used. Note, this cookie is passed in the open (http) and is therefore insecure. I don't use it for anything which requires security.

  1. Site A generates a token and passes as a URL parameter to site B.
  2. Site B takes the token and sets it as a session cookie.

You could probably add encryption/signatures to make this secure. Do your research on how to do that correctly.

How to know what the 'errno' means?

When you use strace (on Linux) to run your binary, it will output the returns from system calls and what the error number means. This may sometimes be useful to you.

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

You can use below command to open it in VIM editor.

export VISUAL=vim; crontab -e

Note: Please make sure VIM editor is installed on your server.

jQuery - Dynamically Create Button and Attach Event Handler

You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html() call will not serialize the event.

Connecting to local SQL Server database using C#

If you're using SQL Server express, change

SqlConnection conn = new SqlConnection("Server=localhost;" 
       + "Database=Database1;");

to

SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;" 
       + "Database=Database1;");

That, and hundreds more connection strings can be found at http://www.connectionstrings.com/

Java, How to add library files in netbeans?

How to import a commons-library into netbeans.

  1. Evaluate the error message in NetBeans:

    java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    
  2. NoClassDeffFoundError means somewhere under the hood in the code you used, a method called another method which invoked a class that cannot be found. So what that means is your code did this: MyFoobarClass foobar = new MyFoobarClass() and the compiler is confused because nowhere is defined this MyFoobarClass. This is why you get an error.

  3. To know what to do next, you have to look at the error message closely. The words 'org/apache/commons' lets you know that this is the codebase that provides the tools you need. You have a choice, either you can import EVERYTHING in apache commons, or you could import JUST the LogFactory class, or you could do something in between. Like for example just get the logging bit of apache commons.

  4. You'll want to go the middle of the road and get commons-logging. Excellent choice, fire up the google and search for apache commons-logging. The first link takes you to http://commons.apache.org/proper/commons-logging/. Go to downloads. There you will find the most up-to-date ones. If your project was compiled under ancient versions of commons-logging, then use those same ancient ones because if you use the newer ones, the code may fail because the newer versions are different.

  5. You're going to want to download the commons-logging-1.1.3-bin.zip or something to that effect. Read what the name is saying. The .zip means it's a compressed file. commons-logging means that this one should contain the LogFactory class you desire. the middle 1.1.3 means that is the version. if you are compiling for an old version, you'll need to match these up, or else you risk the code not compiling right due to changes due to upgrading.

  6. Download that zip. Unzip it. Search around for things that end in .jar. In netbeans right click your project, click properties, click libraries, click "add jar/folder" and import those jars. Save the project, and re-run, and the errors should be gone.

The binaries don't include the source code, so you won't be able to drill down and see what is happening when you debug. As programmers you should be downloading "the source" of apache commons and compiling from source, generating the jars yourself and importing those for experience. You should be smart enough to understand and correct the source code you are importing. These ancient versions of apache commons might have been compiled under an older version of Java, so if you go too far back, they may not even compile unless you compile them under an ancient version of java.

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

How to check that Request.QueryString has a specific value or not in ASP.NET?

To resolve your problem, write the following line on your page's Page_Load method.

if (String.IsNullOrEmpty(Request.QueryString["aspxerrorpath"])) return;

.Net 4.0 provides more closer look to null, empty or whitespace strings, use it as shown in the following line:

if(string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"])) return;

This will not run your next statements (your business logics) if query string does not have aspxerrorpath.

how to parse JSONArray in android

getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for

{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"

but you need to get into the array and then do a search for "characters"

try this

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";

    JSONObject jsonResponse;
    try {
        ArrayList<String> temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters");
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

checked it :)

In Postgresql, force unique on combination of two columns

CREATE TABLE someTable (
    id serial PRIMARY KEY,
    col1 int NOT NULL,
    col2 int NOT NULL,
    UNIQUE (col1, col2)
)

autoincrement is not postgresql. You want a serial.

If col1 and col2 make a unique and can't be null then they make a good primary key:

CREATE TABLE someTable (
    col1 int NOT NULL,
    col2 int NOT NULL,
    PRIMARY KEY (col1, col2)
)

Update a table using JOIN in SQL Server?

Aaron's approach above worked perfectly for me. My update statement was slightly different because I needed to join based on two fields concatenated in one table to match a field in another table.

 --update clients table cell field from custom table containing mobile numbers

update clients
set cell = m.Phone
from clients as c
inner join [dbo].[COSStaffMobileNumbers] as m 
on c.Last_Name + c.First_Name = m.Name

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

Git ignore local file changes

You probably need to do a git stash before you git pull, this is because it is reading your old config file. So do:

git stash
git pull
git commit -am <"say first commit">
git push

Also see git-stash(1) Manual Page.

Extract month and year from a zoo::yearmon object

The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:

cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012

How can I hide or encrypt JavaScript code?

JavaScript is a scripting language and therefore stays in human readable form until it is time for it to be interpreted and executed by the JavaScript runtime.

The only way to partially hide it, at least from the less technical minds, is to obfuscate.

Obfuscation makes it harder for humans to read it, but not impossible for the technically savvy.

Android: Tabs at the BOTTOM

There are two ways to display tabs at the bottom of a tab activity.

  1. Using relative layout
  2. Using Layout_weight attribute

Please check the link for more details.

Declare an empty two-dimensional array in Javascript?

If you want to be able access the matrix like so matrix[i][j]

I find it the most convinient to init it in a loop.

var matrix = [],
    cols = 3;

//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
    matrix[i] = []; 
}

this will give you [ [], [], [] ]

so matrix[0][0] matrix[1][0] return undefined and not the error "Uncaught TypeError: Cannot set property '0' of undefined"

How can I read inputs as numbers?

Multiple questions require input for several integers on single line. The best way is to input the whole string of numbers one one line and then split them to integers. Here is a Python 3 version:

a = []
p = input()
p = p.split()      
for i in p:
    a.append(int(i))

Also a list comprehension can be used

p = input().split("whatever the seperator is")

And to convert all the inputs from string to int we do the following

x = [int(i) for i in p]
print(x, end=' ')

shall print the list elements in a straight line.

How do I remove the passphrase for the SSH key without having to create a new key?

On the Mac you can store the passphrase for your private ssh key in your Keychain, which makes the use of it transparent. If you're logged in, it is available, when you are logged out your root user cannot use it. Removing the passphrase is a bad idea because anyone with the file can use it.

ssh-keygen -K

Add this to ~/.ssh/config

UseKeychain yes

Relative frequencies / proportions with dplyr

This answer is based upon Matifou's answer.

First I modified it to ensure that I don't get the freq column returned as a scientific notation column by using the scipen option.

Then I multiple the answer by 100 to get a percent rather than decimal to make the freq column easier to read as a percentage.

getOption("scipen") 
options("scipen"=10) 
mtcars %>%
count(am, gear) %>% 
mutate(freq = (n / sum(n)) * 100)

How do you exit from a void function in C++?

You mean like this?

void foo ( int i ) {
    if ( i < 0 ) return; // do nothing
    // do something
}

Authenticate with GitHub using a token

Automation / Git automation with OAuth tokens

$ git clone https://github.com/username/repo.git
  Username: your_token
  Password:

It also works in the git push command.

Reference: https://help.github.com/articles/git-automation-with-oauth-tokens/

User GETDATE() to put current date into SQL variable

You don't need the SELECT

DECLARE @LastChangeDate as date
SET @LastChangeDate = GetDate()

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

Here is an effective solution from didi to solve this problem, Since this bug is very common and difficult to find the cause, It looks more like a system problem, Why can't we ignore it directly?Of course we can ignore it, Here is the sample code:

final Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = 
        Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if (t.getName().equals("FinalizerWatchdogDaemon") && e instanceof TimeoutException) {
        } else {
            defaultUncaughtExceptionHandler.uncaughtException(t, e);
        }
    }
});

By setting a special default uncaught exception handler, application can change the way in which uncaught exceptions are handled for those threads that would already accept whatever default behavior the system provided. When an uncaught TimeoutException is thrown from a thread named FinalizerWatchdogDaemon, this special handler will block the handler chain, the system handler will not be called, so crash will be avoided.

Through practice, no other bad effects were found. The GC system is still working, timeouts are alleviated as CPU usage decreases.

For more details see: https://mp.weixin.qq.com/s/uFcFYO2GtWWiblotem2bGg

set date in input type date

Your code would have worked if it had been in this format: YYYY-MM-DD, this is the computer standard for date formats http://en.wikipedia.org/wiki/ISO_8601

How to remove a class from elements in pure JavaScript?

var elems = document.querySelectorAll(".widget.hover");

[].forEach.call(elems, function(el) {
    el.classList.remove("hover");
});

You can patch .classList into IE9. Otherwise, you'll need to modify the .className.

var elems = document.querySelectorAll(".widget.hover");

[].forEach.call(elems, function(el) {
    el.className = el.className.replace(/\bhover\b/, "");
});

The .forEach() also needs a patch for IE8, but that's pretty common anyway.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

I face this issue because I messed return keyword in custom rendering in Columns section

columns: [
    {....
        'data': function(row, type, val, meta) {
            if (row.LetterStatus)
                 return '@CultureHelper.GetCurrentCulture()' == 'ar'? row.LetterStatus.NameInArabic: row.LetterStatus.NameInEnglish;
            else row.LetterStatusID.toString();// here is the problem because I messed the Return key keyword
          },
     ......
    }

the problem in my code is because I messed the Return keyword in the else clause

so I changed it to

....
else return row.LetterStatusID.toString();// messed return keyword added
.....

C#: how to get first char of a string?

getting a char from a string may depend on the enconding (string default is UTF-16)

https://stackoverflow.com/a/32141891

string str = new String(new char[] { '\uD800', '\uDC00', 'z' });
string first = str.Substring(0, char.IsHighSurrogate(str[0]) ? 2 : 1);

How to print (using cout) a number in binary form?

The easiest way is probably to create an std::bitset representing the value, then stream that to cout.

#include <bitset>
...

char a = -58;
std::bitset<8> x(a);
std::cout << x << '\n';

short c = -315;
std::bitset<16> y(c);
std::cout << y << '\n';

How to create NSIndexPath for TableView

indexPathForRow is a class method!

The code should read:

NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;

How to use onClick with divs in React.js

For future googlers (thousands have now googled this question):

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.

These are right:

<div onClick={doThis}>
<div onClick={() => doThis()}>

These are wrong:

<div onClick={doThis()}>
<div onClick={() => doThis}>

(and don't forget to close your tags... Watch for this:

<div onClick={doThis}

missing closing tag on the div)

Converting 'ArrayList<String> to 'String[]' in Java

You can convert List to String array by using this method:

 Object[] stringlist=list.toArray();

The complete example:

ArrayList<String> list=new ArrayList<>();
    list.add("Abc");
    list.add("xyz");

    Object[] stringlist=list.toArray();

    for(int i = 0; i < stringlist.length ; i++)
    {
          Log.wtf("list data:",(String)stringlist[i]);
    }

postgreSQL - psql \i : how to execute script in a given path

Postgres started on Linux/Unix. I suspect that reversing the slash with fix it.

\i somedir/script2.sql 

If you need to fully qualify something

\i c:/somedir/script2.sql

If that doesn't fix it, my next guess would be you need to escape the backslash.

\i somedir\\script2.sql

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

How to empty/destroy a session in rails?

to delete a user's session

session.delete(:user_id)

Android Device not recognized by adb

Set your environmental variable Path to point to where the adb application is at: [directory of sdk folder]\platform-tools

Iterating through struct fieldnames in MATLAB

You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

for i = 1:numel(fields)
  teststruct.(fields{i})
end

Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed

How to get some values from a JSON string in C#?

Following code is working for me.

Usings:

using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;

Code:

 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            string json = responseReader.ReadToEnd();
                            string data = JObject.Parse(json)["id"].ToString();
                        }
                    }
                }

//json = {"kind": "ALL", "id": "1221455", "longUrl": "NewURL"}

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

Since the beginning, Swift has provided some facilities for making ObjC and C more Swifty, adding more with each version. Now, in Swift 3, the new "import as member" feature lets frameworks with certain styles of C API -- where you have a data type that works sort of like a class, and a bunch of global functions to work with it -- act more like Swift-native APIs. The data types import as Swift classes, their related global functions import as methods and properties on those classes, and some related things like sets of constants can become subtypes where appropriate.

In Xcode 8 / Swift 3 beta, Apple has applied this feature (along with a few others) to make the Dispatch framework much more Swifty. (And Core Graphics, too.) If you've been following the Swift open-source efforts, this isn't news, but now is the first time it's part of Xcode.

Your first step on moving any project to Swift 3 should be to open it in Xcode 8 and choose Edit > Convert > To Current Swift Syntax... in the menu. This will apply (with your review and approval) all of the changes at once needed for all the renamed APIs and other changes. (Often, a line of code is affected by more than one of these changes at once, so responding to error fix-its individually might not handle everything right.)

The result is that the common pattern for bouncing work to the background and back now looks like this:

// Move to a background thread to do some long running work
DispatchQueue.global(qos: .userInitiated).async {
    let image = self.loadOrGenerateAnImage()
    // Bounce back to the main thread to update the UI
    DispatchQueue.main.async {
        self.imageView.image = image
    }
}

Note we're using .userInitiated instead of one of the old DISPATCH_QUEUE_PRIORITY constants. Quality of Service (QoS) specifiers were introduced in OS X 10.10 / iOS 8.0, providing a clearer way for the system to prioritize work and deprecating the old priority specifiers. See Apple's docs on background work and energy efficiency for details.

By the way, if you're keeping your own queues to organize work, the way to get one now looks like this (notice that DispatchQueueAttributes is an OptionSet, so you use collection-style literals to combine options):

class Foo { 
    let queue = DispatchQueue(label: "com.example.my-serial-queue",
                           attributes: [.serial, .qosUtility])
    func doStuff() {
        queue.async {
            print("Hello World")
        }
    }
}

Using dispatch_after to do work later? That's a method on queues, too, and it takes a DispatchTime, which has operators for various numeric types so you can just add whole or fractional seconds:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // in half a second...
    print("Are we there yet?")
}

You can find your way around the new Dispatch API by opening its interface in Xcode 8 -- use Open Quickly to find the Dispatch module, or put a symbol (like DispatchQueue) in your Swift project/playground and command-click it, then brouse around the module from there. (You can find the Swift Dispatch API in Apple's spiffy new API Reference website and in-Xcode doc viewer, but it looks like the doc content from the C version hasn't moved into it just yet.)

See the Migration Guide for more tips.

Construct pandas DataFrame from list of tuples of (row,col,values)

I submit that it is better to leave your data stacked as it is:

df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])

# Possibly also this if these can always be the indexes:
# df = df.set_index(['R_Number', 'C_Number'])

Then it's a bit more intuitive to say

df.set_index(['R_Number', 'C_Number']).Avg.unstack(level=1)

This way it is implicit that you're seeking to reshape the averages, or the standard deviations. Whereas, just using pivot, it's purely based on column convention as to what semantic entity it is that you are reshaping.

How to send an object from one Android Activity to another using Intents?

First implement Parcelable in your class. Then pass object like this.

SendActivity.java

ObjectA obj = new ObjectA();

// Set values etc.

Intent i = new Intent(this, MyActivity.class);
i.putExtra("com.package.ObjectA", obj);

startActivity(i);

ReceiveActivity.java

Bundle b = getIntent().getExtras();
ObjectA obj = b.getParcelable("com.package.ObjectA");

The package string isn't necessary, just the string needs to be the same in both Activities

REFERENCE

matplotlib: how to draw a rectangle on image

You can add a Rectangle patch to the matplotlib Axes.

For example (using the image from the tutorial here):

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image

im = Image.open('stinkbug.png')

# Create figure and axes
fig, ax = plt.subplots()

# Display the image
ax.imshow(im)

# Create a Rectangle patch
rect = patches.Rectangle((50, 100), 40, 30, linewidth=1, edgecolor='r', facecolor='none')

# Add the patch to the Axes
ax.add_patch(rect)

plt.show()

enter image description here

Having trouble setting working directory

I just had this error message happen. When searching for why, I figured out that there's a related issue that can occur if you're not paying attention - the same error occurs if the directory you are trying to move into does not exist.

Online SQL syntax checker conforming to multiple databases

Only know about this. Not sure how well does it against MySQL http://developer.mimer.se/validator/

How to get image size (height & width) using JavaScript?

var imgSrc, imgW, imgH;
function myFunction(image){
    var img = new Image();
    img.src = image;
    img.onload = function() {   
        return {
            src:image,
            width:this.width,
            height:this.height};
        }
    return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
    //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load',function(){
    imgSrc = x.src;
    imgW = x.width;
    imgH = x.height;
});
x.addEventListener('load',function(){
    console.log(imgW+'x'+imgH);//276x110
});
console.log(imgW);//undefined.
console.log(imgH);//undefined.
console.log(imgSrc);//undefined.

This is my method, hope this helpful. :)

Iterating a JavaScript object's properties using jQuery

$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

each

What is the most effective way to get the index of an iterator of an std::vector?

Here is an example to find "all" occurrences of 10 along with the index. Thought this would be of some help.

void _find_all_test()
{
    vector<int> ints;
    int val;
    while(cin >> val) ints.push_back(val);

    vector<int>::iterator it;
    it = ints.begin();
    int count = ints.size();
    do
    {
        it = find(it,ints.end(), 10);//assuming 10 as search element
        cout << *it << " found at index " << count -(ints.end() - it) << endl;
    }while(++it != ints.end()); 
}

CSS Box Shadow Bottom Only

try this to get the box-shadow under your full control.

    <html>

    <head>
        <style> 
            div {
                width:300px;
                height:100px;
                background-color:yellow;
                box-shadow: 0 10px black inset,0 -10px red inset, -10px 0 blue inset, 10px 0 green inset;
           }
        </style>
    </head>
    <body>
        <div>
        </div>
    </body>

    </html>

this would apply to outer box-shadow as well.

Why can't I use a list as a dict key in python?

Here's an answer http://wiki.python.org/moin/DictionaryKeys

What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?

Looking up different lists with the same contents would produce different results, even though comparing lists with the same contents would indicate them as equivalent.

What about Using a list literal in a dictionary lookup?

How to increase the gap between text and underlining in CSS

If you want:

  • multiline
  • dotted
  • with custom bottom padding
  • without wrappers

underline, you can use 1 pixel height background image with repeat-x and 100% 100% position:

display: inline;
background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAYAAAD0In+KAAAAEUlEQVQIW2M0Lvz//2w/IyMAFJoEAis2CPEAAAAASUVORK5CYII=') repeat-x 100% 100%;

You can replace the second 100% by something else like px or em to adjust the vertical position of the underline. Also you can use calc if you want to add vertical padding, e.g.:

padding-bottom: 5px;
background-position-y: calc(100% - 5px);

Of course you can also make your own base64 png pattern with another color, height and design, e.g. here: http://www.patternify.com/ - just set square width & height at 2x1.

Source of inspiration: http://alistapart.com/article/customunderlines

Spring Boot how to hide passwords in properties file

To the already proposed solutions I can add an option to configure an external Secrets Manager such as Vault.

  1. Configure Vault Server vault server -dev (Only for DEV and not for PROD)
  2. Write secrets vault write secret/somename key1=value1 key2=value2
  3. Verify secrets vault read secret/somename

Add the following dependency to your SpringBoot project:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-vault-config</artifactId>
</dependency>

Add Vault config properties:

spring.cloud.vault.host=localhost
spring.cloud.vault.port=8200
spring.cloud.vault.scheme=http
spring.cloud.vault.authentication=token
spring.cloud.vault.token=${VAULT_TOKEN}

Pass VAULT_TOKEN as an environment variable.

Refer to the documentation here.

There is a Spring Vault project which is also can be used for accessing, storing and revoking secrets.

Dependency:

<dependency>
    <groupId>org.springframework.vault</groupId>
    <artifactId>spring-vault-core</artifactId>
</dependency>

Configuring Vault Template:

@Configuration
class VaultConfiguration extends AbstractVaultConfiguration {

  @Override
  public VaultEndpoint vaultEndpoint() {
    return new VaultEndpoint();
  }

  @Override
  public ClientAuthentication clientAuthentication() {
    return new TokenAuthentication("…");
  }
}

Inject and use VaultTemplate:

public class Example {

  @Autowired
  private VaultOperations operations;

  public void writeSecrets(String userId, String password) {
      Map<String, String> data = new HashMap<String, String>();
      data.put("password", password);
      operations.write(userId, data);
  }

  public Person readSecrets(String userId) {
      VaultResponseSupport<Person> response = operations.read(userId, Person.class);
      return response.getBody();
  }
}

Use Vault PropertySource:

@VaultPropertySource(value = "aws/creds/s3",
  propertyNamePrefix = "aws."
  renewal = Renewal.RENEW)
public class Config {

}

Usage example:

public class S3Client {

  // inject the actual values
  @Value("${aws.access_key}")
  private String awsAccessKey;
  @Value("${aws.secret_key}")
  private String awsSecretKey;

  public InputStream getFileFromS3(String filenname) {
    // …
  }
}

Update int column in table with unique incrementing values

simple query would be, just set a variable to some number you want. then update the column you need by incrementing 1 from that number. for all the rows it'll update each row id by incrementing 1

SET @a  = 50000835 ;  
UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1 
WHERE external_identifier IS NULL;

Vlookup referring to table data in a different sheet

I have faced similar problem and it was returning #N/A. That means matching data is present but you might having extra space in the M3 column record, that may prevent it from getting exact value. Because you have set last parameter as FALSE, it is looking for "exact match". This formula is correct: =VLOOKUP(M3,Sheet1!$A$2:$Q$47,13,FALSE)

Find which commit is currently checked out in Git

You have at least 5 different ways to view the commit you currently have checked out into your working copy during a git bisect session (note that options 1-4 will also work when you're not doing a bisect):

  1. git show.
  2. git log -1.
  3. Bash prompt.
  4. git status.
  5. git bisect visualize.

I'll explain each option in detail below.

Option 1: git show

As explained in this answer to the general question of how to determine which commit you currently have checked-out (not just during git bisect), you can use git show with the -s option to suppress patch output:

$ git show --oneline -s
a9874fd Merge branch 'epic-feature'

Option 2: git log -1

You can also simply do git log -1 to find out which commit you're currently on.

$ git log -1 --oneline
c1abcde Add feature-003

Option 3: Bash prompt

In Git version 1.8.3+ (or was it an earlier version?), if you have your Bash prompt configured to show the current branch you have checked out into your working copy, then it will also show you the current commit you have checked out during a bisect session or when you're in a "detached HEAD" state. In the example below, I currently have c1abcde checked out:

# Prompt during a bisect
user ~ (c1abcde...)|BISECTING $

# Prompt at detached HEAD state 
user ~ (c1abcde...) $

Option 4: git status

Also as of Git version 1.8.3+ (and possibly earlier, again not sure), running git status will also show you what commit you have checked out during a bisect and when you're in detached HEAD state:

$ git status
# HEAD detached at c1abcde <== RIGHT HERE

Option 5: git bisect visualize

Finally, while you're doing a git bisect, you can also simply use git bisect visualize or its built-in alias git bisect view to launch gitk, so that you can graphically view which commit you are on, as well as which commits you have marked as bad and good so far. I'm pretty sure this existed well before version 1.8.3, I'm just not sure in which version it was introduced:

git bisect visualize 
git bisect view # shorter, means same thing

enter image description here

How to allow download of .json file with ASP.NET

  1. Navigate to C:\Users\username\Documents\IISExpress\config
  2. Open applicationhost.config with Visual Studio or your favorite text-editor.
  3. Search for the word mimeMap, you should find lots of 'em.
  4. Add the following line to the top of the list: .

Xcode 6 Bug: Unknown class in Interface Builder file

I had the same problem with Xcode 6.3 when I add files to "myapp". That's because I choose "create folder reference" instead of "create groups".I delete these files and add them again with the "create groups" option.And the problem fixed.

How to change the playing speed of videos in HTML5?

You can use this code:

var vid = document.getElementById("video1");

function slowPlaySpeed() { 
    vid.playbackRate = 0.5;
} 

function normalPlaySpeed() { 
    vid.playbackRate = 1;
} 

function fastPlaySpeed() { 
    vid.playbackRate = 2;
}

In which conda environment is Jupyter executing?

Adding to the above answers, you can also use

!which python

Type this in a cell and this will show the path of the environment. I'm not sure of the reason, but in my installation, there is no segregation of environments in the notebook, but on activating the environment and launching jupyter notebook, the path used is the python installed in the environment.

Git: Merge a Remote branch locally

Fetch the remote branch from the origin first.

git fetch origin remote_branch_name

Merge the remote branch to the local branch

git merge origin/remote_branch_name

How to use EOF to run through a text file in C?

How you detect EOF depends on what you're using to read the stream:

function                  result on EOF or error                    
--------                  ----------------------
fgets()                   NULL
fscanf()                  number of succesful conversions
                            less than expected
fgetc()                   EOF
fread()                   number of elements read
                            less than expected

Check the result of the input call for the appropriate condition above, then call feof() to determine if the result was due to hitting EOF or some other error.

Using fgets():

 char buffer[BUFFER_SIZE];
 while (fgets(buffer, sizeof buffer, stream) != NULL)
 {
   // process buffer
 }
 if (feof(stream))
 {
   // hit end of file
 }
 else
 {
   // some other error interrupted the read
 }

Using fscanf():

char buffer[BUFFER_SIZE];
while (fscanf(stream, "%s", buffer) == 1) // expect 1 successful conversion
{
  // process buffer
}
if (feof(stream)) 
{
  // hit end of file
}
else
{
  // some other error interrupted the read
}

Using fgetc():

int c;
while ((c = fgetc(stream)) != EOF)
{
  // process c
}
if (feof(stream))
{
  // hit end of file
}
else
{
  // some other error interrupted the read
}

Using fread():

char buffer[BUFFER_SIZE];
while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1 
                                                     // element of size
                                                     // BUFFER_SIZE
{
   // process buffer
}
if (feof(stream))
{
  // hit end of file
}
else
{
  // some other error interrupted read
}

Note that the form is the same for all of them: check the result of the read operation; if it failed, then check for EOF. You'll see a lot of examples like:

while(!feof(stream))
{
  fscanf(stream, "%s", buffer);
  ...
}

This form doesn't work the way people think it does, because feof() won't return true until after you've attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief.

Best way to check for null values in Java?

if you do not have an access to the commons apache library, the following probably will work ok

if(null != foo && foo.bar()) {
//do something
}

How can I pass variable to ansible playbook in the command line?

ansible-playbok -i <inventory> <playbook-name> -e "proc_name=sshd"

You can use the above command in below playbooks.

---
- name: Service Status
gather_facts: False
tasks:
- name: Check Service Status (Linux)
shell: pgrep "{{ proc_name }}"
register: service_status
ignore_errors: yes
debug: var=service_status.rc`

python modify item in list, save back in list

For Python 3:

ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
    ListOfStrings[idx] = "bar"

Jquery show/hide table rows

The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:

    var black = $('.black');
    var white = $('.white');

The selector will find every element classed under black or white. Button functions stay as stated above:

    $('#showBlackButton').click(function() {
           black.show();
           white.hide();
    });

    $('#showWhiteButton').click(function() {
           white.show();
           black.hide();
    });

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

EventListener Enter Key

You could listen to the 'keydown' event and then check for an enter key.

Your handler would be like:

function (e) {
  if (13 == e.keyCode) {
     ... do whatever ...
  }
}

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

Define your own parse format string to use.

string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);

In case you got a datetime having milliseconds, use the following formatString

string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);

Thanks

Print execution time of a shell command

root@hostname:~# time [command]

It also distinguishes between real time used and system time used.

How can I write data in YAML format in a file?

Link to the PyYAML documentation showing the difference for the default_flow_style parameter. To write it to a file in block mode (often more readable):

d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)

produces:

A: a
B:
  C: c
  D: d
  E: e

How does JavaScript .prototype work?

It's just that you already have an object with Object.new but you still don't have an object when using the constructor syntax.

How to calculate cumulative normal distribution?

Adapted from here http://mail.python.org/pipermail/python-list/2000-June/039873.html

from math import *
def erfcc(x):
    """Complementary error function."""
    z = abs(x)
    t = 1. / (1. + 0.5*z)
    r = t * exp(-z*z-1.26551223+t*(1.00002368+t*(.37409196+
        t*(.09678418+t*(-.18628806+t*(.27886807+
        t*(-1.13520398+t*(1.48851587+t*(-.82215223+
        t*.17087277)))))))))
    if (x >= 0.):
        return r
    else:
        return 2. - r

def ncdf(x):
    return 1. - 0.5*erfcc(x/(2**0.5))

How do I check if a string contains another string in Swift?

Swift 3: Here you can see my smart search extension fro string that let you make a search on string for seeing if it contains, or maybe to filter a collection based on a search text.

https://github.com/magonicolas/Swift-Smart-String-Search

How do I revert my changes to a git submodule?

my way to reset all submodules (WITHOUT detaching & keeping their "master" branch):

git submodule foreach 'git checkout master && git reset --hard $sha1'

Removing whitespace from strings in Java

I am trying an aggregation answer where I test all ways of removing all whitespaces in a string. Each method is ran 1 million times and then then the average is taken. Note: Some compute will be used on summing up all the runs.


Results:

1st place from @jahir 's answer

  • StringUtils with short text: 1.21E-4 ms (121.0 ms)
  • StringUtils with long text: 0.001648 ms (1648.0 ms)

2nd place

  • String builder with short text: 2.48E-4 ms (248.0 ms)
  • String builder with long text: 0.00566 ms (5660.0 ms)

3rd place

  • Regex with short text: 8.36E-4 ms (836.0 ms)
  • Regex with long text: 0.008877 ms (8877.0 ms)

4th place

  • For loop with short text: 0.001666 ms (1666.0 ms)
  • For loop with long text: 0.086437 ms (86437.0 ms)

Here is the code:

public class RemoveAllWhitespaces {
    public static String Regex(String text){
        return text.replaceAll("\\s+", "");
    }

    public static String ForLoop(String text) {
        for (int i = text.length() - 1; i >= 0; i--) {
            if(Character.isWhitespace(text.codePointAt(i))) {
                text = text.substring(0, i) + text.substring(i + 1);
            }
        }

        return text;
    }

    public static String StringBuilder(String text){
        StringBuilder builder = new StringBuilder(text);
        for (int i = text.length() - 1; i >= 0; i--) {
            if(Character.isWhitespace(text.codePointAt(i))) {
                builder.deleteCharAt(i);
            }
        }

        return builder.toString();
    }
}

Here are the tests:

import org.junit.jupiter.api.Test;

import java.util.function.Function;
import java.util.stream.IntStream;

import static org.junit.jupiter.api.Assertions.*;

public class RemoveAllWhitespacesTest {
    private static final String longText = "123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222";
    private static final String expected = "1231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc222";

    private static final String shortText = "123 123 \t 1adc \n 222";
    private static final String expectedShortText = "1231231adc222";

    private static final int numberOfIterations = 1000000;

    @Test
    public void Regex_LongText(){
        RunTest("Regex_LongText", text -> RemoveAllWhitespaces.Regex(text), longText, expected);
    }

    @Test
    public void Regex_ShortText(){
        RunTest("Regex_LongText", text -> RemoveAllWhitespaces.Regex(text), shortText, expectedShortText);

    }

    @Test
    public void For_LongText(){
        RunTest("For_LongText", text -> RemoveAllWhitespaces.ForLoop(text), longText, expected);
    }

    @Test
    public void For_ShortText(){
        RunTest("For_LongText", text -> RemoveAllWhitespaces.ForLoop(text), shortText, expectedShortText);
    }

    @Test
    public void StringBuilder_LongText(){
        RunTest("StringBuilder_LongText", text -> RemoveAllWhitespaces.StringBuilder(text), longText, expected);
    }

    @Test
    public void StringBuilder_ShortText(){
        RunTest("StringBuilder_ShortText", text -> RemoveAllWhitespaces.StringBuilder(text), shortText, expectedShortText);
    }

    private void RunTest(String testName, Function<String,String> func, String input, String expected){
        long startTime = System.currentTimeMillis();
        IntStream.range(0, numberOfIterations)
                .forEach(x -> assertEquals(expected, func.apply(input)));
        double totalMilliseconds = (double)System.currentTimeMillis() - (double)startTime;
        System.out.println(
                String.format(
                        "%s: %s ms (%s ms)",
                        testName,
                        totalMilliseconds / (double)numberOfIterations,
                        totalMilliseconds
                )
        );
    }
}

PHP namespaces and "use"

If you need to order your code into namespaces, just use the keyword namespace:

file1.php

namespace foo\bar;

In file2.php

$obj = new \foo\bar\myObj();

You can also use use. If in file2 you put

use foo\bar as mypath;

you need to use mypath instead of bar anywhere in the file:

$obj  = new mypath\myObj();

Using use foo\bar; is equal to use foo\bar as bar;.

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
{
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
    {
        this.Name = name;
        this.Artist = artist;
        this.Year = year;
    }
}

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994
};

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 
}

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"
};

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

Converting NumPy array into Python List structure?

Use tolist():

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)

How to calculate the median of an array?

Arrays.sort(numArray);
int middle = ((numArray.length) / 2);
if(numArray.length % 2 == 0){
 int medianA = numArray[middle];
 int medianB = numArray[middle-1];
 median = (medianA + medianB) / 2;
} else{
 median = numArray[middle + 1];
}

EDIT: I initially had medianB setting to middle+1 in the even length arrays, this was wrong due to arrays starting count at 0. I have updated it to use middle-1 which is correct and should work properly for an array with an even length.

How to toggle a boolean?

Let's see this in action:

_x000D_
_x000D_
var b = true;_x000D_
_x000D_
console.log(b); // true_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // false_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // true
_x000D_
_x000D_
_x000D_

Anyways, there is no shorter way than what you currently have.

How to convert String to Date value in SAS?

You don't need substr or strip.

input(monyy,date9.);

QR Code encoding and decoding using zxing

For what it's worth, my groovy spike seems to work with both UTF-8 and ISO-8859-1 character encodings. Not sure what will happen when a non zxing decoder tries to decode the UTF-8 encoded image though... probably varies depending on the device.

// ------------------------------------------------------------------------------------
// Requires: groovy-1.7.6, jdk1.6.0_03, ./lib with zxing core-1.7.jar, javase-1.7.jar 
// Javadocs: http://zxing.org/w/docs/javadoc/overview-summary.html
// Run with: groovy -cp "./lib/*" zxing.groovy
// ------------------------------------------------------------------------------------

import com.google.zxing.*
import com.google.zxing.common.*
import com.google.zxing.client.j2se.*

import java.awt.image.BufferedImage
import javax.imageio.ImageIO

def class zxing {
    def static main(def args) {
        def filename = "./qrcode.png"
        def data = "This is a test to see if I can encode and decode this data..."
        def charset = "UTF-8" //"ISO-8859-1" 
        def hints = new Hashtable<EncodeHintType, String>([(EncodeHintType.CHARACTER_SET): charset])

        writeQrCode(filename, data, charset, hints, 100, 100)

        assert data == readQrCode(filename, charset, hints)
    }

    def static writeQrCode(def filename, def data, def charset, def hints, def width, def height) {
        BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height, hints)
        MatrixToImageWriter.writeToFile(matrix, filename.substring(filename.lastIndexOf('.')+1), new File(filename))
    }

    def static readQrCode(def filename, def charset, def hints) {
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filename)))))
        Result result = new MultiFormatReader().decode(binaryBitmap, hints)

        result.getText()        
    }

}

How can I add a custom HTTP header to ajax request with js or jQuery?

You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
    this.setRequestHeader('x-my-custom-header', 'some value');
    this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Go to Control Panel>>System and Security>>System>>Advance system settings>>Environment Variables then set variable value of ANDROID_HOME set it like this "C:\Users\username\AppData\Local\Android\sdk" set username as your pc name, then restart your android studio. after that you can create your AVD again than the error will gone than it will start the virtual device.

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

__proto__ VS. prototype in JavaScript

I've made for myself a small drawing that represents the following code snippet:

var Cat = function() {}
var tom = new Cat()

Understanding __proto__ and prototype

I have a classical OO background, so it was helpful to represent the hierarchy in this manner. To help you read this diagram, treat the rectangles in the image as JavaScript objects. And yes, functions are also objects. ;)

Objects in JavaScript have properties and __proto__ is just one of them.

The idea behind this property is to point to the ancestor object in the (inheritance) hierarchy.

The root object in JavaScript is Object.prototype and all other objects are descendants of this one. The __proto__ property of the root object is null, which represents the end of inheritance chain.

You'll notice that prototype is a property of functions. Cat is a function, but also Function and Object are (native) functions. tom is not a function, thus it does not have this property.

The idea behind this property is to point to an object which will be used in the construction, i.e. when you call the new operator on that function.

Note that prototype objects (yellow rectangles) have another property called constructor which points back to the respective function object. For brevity reasons this was not depicted.

Indeed, when we create the tom object with new Cat(), the created object will have the __proto__ property set to the prototype object of the constructor function.

In the end, let us play with this diagram a bit. The following statements are true:

  • tom.__proto__ property points to the same object as Cat.prototype.

  • Cat.__proto__ points to the Function.prototype object, just like Function.__proto__ and Object.__proto__ do.

  • Cat.prototype.__proto__ and tom.__proto__.__proto__ point to the same object and that is Object.prototype.

Cheers!

Postgres - Transpose Rows to Columns

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
   $$
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:

Detailed explanation and instructions here:

And in particular, for "extra columns":

The special difficulties here are:

  • The lack of key names.
    -> We substitute with row_number() in a subquery.

  • The varying number of emails.
    -> We limit to a max. of three in the outer SELECT
    and use crosstab() with two parameters, providing a list of possible keys.

Pay attention to NULLS LAST in the ORDER BY.

How to add new column to MYSQL table?

Based on your comment it looks like your'e only adding the new column if: mysql_query("SELECT * FROM assessment"); returns false. That's probably not what you wanted. Try removing the '!' on front of $sql in the first 'if' statement. So your code will look like:

$sql=mysql_query("SELECT * FROM assessment");
if ($sql) {
 mysql_query("ALTER TABLE assessment ADD q6 INT(1) NOT NULL AFTER q5");
 echo 'Q6 created'; 
}else...

Install / upgrade gradle on Mac OS X

And using ports:

port install gradle

Ports , tested on El Capitan

How to set Spinner default value to null?

Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView method.

This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

How to pass parameter to a promise function

Try this:

function someFunction(username, password) {
      return new Promise((resolve, reject) => {
        // Do something with the params username and password...
        if ( /* everything turned out fine */ ) {
          resolve("Stuff worked!");
        } else {
          reject(Error("It didn't work!"));
        }
      });
    }
    
    someFunction(username, password)
      .then((result) => {
        // Do something...
      })
      .catch((err) => {
        // Handle the error...
      });

Where can I find Android's default icons?

you can use

android.R.drawable.xxx

(use autocomplete to see whats in there)

Or download the stuff from http://developer.android.com/design/downloads/index.html

Showing all errors and warnings

You can see a detailed description here.

ini_set('display_errors', 1);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Changelog

  • 5.4.0 E_STRICT became part of E_ALL

  • 5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.

  • 5.2.0 E_RECOVERABLE_ERROR introduced.

  • 5.0.0 E_STRICT introduced (not part of E_ALL).

Passing variable from Form to Module in VBA

Don't declare the variable in the userform. Declare it as Public in the module.

Public pass As String

In the Userform

Private Sub CommandButton1_Click()
    pass = UserForm1.TextBox1
    Unload UserForm1
End Sub

In the Module

Public pass As String

Public Sub Login()
    '
    '~~> Rest of the code
    '
    UserForm1.Show
    driver.findElementByName("PASSWORD").SendKeys pass
    '
    '~~> Rest of the code
    '
End Sub

You might want to also add an additional check just before calling the driver.find... line?

If Len(Trim(pass)) <> 0 Then

This will ensure that a blank string is not passed.

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

How to write file in UTF-8 format?

This works for me. :)

$f=fopen($filename,"w"); 
# Now UTF-8 - Add byte order mark 
fwrite($f, pack("CCC",0xef,0xbb,0xbf)); 
fwrite($f,$content); 
fclose($f); 

Check if list contains element that contains a string and get that element

It is possible to combine Any, Where, First and FirstOrDefault; or just place the predicate in any of those methods depending on what is needed.

You should probably avoid using First unless you want to have an exception thrown when no match is found. FirstOrDefault is usually the better option as long as you know it will return the type's default if no match is found (string's default is null, int is 0, bool is false, etc).

using System.Collections.Generic;
using System.Linq;


bool exists;
string firstMatch;
IEnumerable<string> matchingList;

var myList = new List<string>() { "foo", "bar", "foobar" };

exists = myList.Any(x => x.Contains("o"));
// exists => true

firstMatch = myList.FirstOrDefault(x => x.Contains("o"));
firstMatch = myList.First(x => x.Contains("o"));
// firstMatch => "foo"

firstMatch = myList.First(x => x.Contains("dark side"));
// throws exception because no element contains "dark side"

firstMatch = myList.FirstOrDefault(x => x.Contains("dark side"));
// firstMatch => null

matchingList = myList.Where(x => x.Contains("o")); 
// matchingList => { "foo", "foobar" }

Test this code @ https://rextester.com/TXDL57489

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

Here is a more elegant, fail-safe, quick & dirty method, combining the answers provided above.

Usage

  1. include sh_lock_functions.sh
  2. init using sh_lock_init
  3. lock using sh_acquire_lock
  4. check lock using sh_check_lock
  5. unlock using sh_remove_lock

Script File

sh_lock_functions.sh

#!/bin/bash

function sh_lock_init {
    sh_lock_scriptName=$(basename $0)
    sh_lock_dir="/tmp/${sh_lock_scriptName}.lock" #lock directory
    sh_lock_file="${sh_lock_dir}/lockPid.txt" #lock file
}

function sh_acquire_lock {
    if mkdir $sh_lock_dir 2>/dev/null; then #check for lock
        echo "$sh_lock_scriptName lock acquired successfully.">&2
        touch $sh_lock_file
        echo $$ > $sh_lock_file # set current pid in lockFile
        return 0
    else
        touch $sh_lock_file
        read sh_lock_lastPID < $sh_lock_file
        if [ ! -z "$sh_lock_lastPID" -a -d /proc/$sh_lock_lastPID ]; then # if lastPID is not null and a process with that pid exists
            echo "$sh_lock_scriptName is already running.">&2
            return 1
        else
            echo "$sh_lock_scriptName stopped during execution, reacquiring lock.">&2
            echo $$ > $sh_lock_file # set current pid in lockFile
            return 2
        fi
    fi
    return 0
}

function sh_check_lock {
    [[ ! -f $sh_lock_file ]] && echo "$sh_lock_scriptName lock file removed.">&2 && return 1
    read sh_lock_lastPID < $sh_lock_file
    [[ $sh_lock_lastPID -ne $$ ]] && echo "$sh_lock_scriptName lock file pid has changed.">&2  && return 2
    echo "$sh_lock_scriptName lock still in place.">&2
    return 0
}

function sh_remove_lock {
    rm -r $sh_lock_dir
}

Usage example

sh_lock_usage_example.sh

#!/bin/bash
. /path/to/sh_lock_functions.sh # load sh lock functions

sh_lock_init || exit $?

sh_acquire_lock
lockStatus=$?
[[ $lockStatus -eq 1 ]] && exit $lockStatus
[[ $lockStatus -eq 2 ]] && echo "lock is set, do some resume from crash procedures";

#monitoring example
cnt=0
while sh_check_lock # loop while lock is in place
do
    echo "$sh_scriptName running (pid $$)"
    sleep 1
    let cnt++
    [[ $cnt -gt 5 ]] && break
done

#remove lock when process finished
sh_remove_lock || exit $?

exit 0

Features

  • Uses a combination of file, directory and process id to lock to make sure that the process is not already running
  • You can detect if the script stopped before lock removal (eg. process kill, shutdown, error etc.)
  • You can check the lock file, and use it to trigger a process shutdown when the lock is missing
  • Verbose, outputs error messages for easier debug

Scroll to the top of the page using JavaScript?

This will work:

window.scrollTo(0, 0);

No == operator found while comparing structs in C++

In C++, structs do not have a comparison operator generated by default. You need to write your own:

bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return /* your comparison code goes here */
}

Effect of NOLOCK hint in SELECT statements

1) Yes, a select with NOLOCK will complete faster than a normal select.

2) Yes, a select with NOLOCK will allow other queries against the effected table to complete faster than a normal select.

Why would this be?

NOLOCK typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous.

You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a NOLOCK read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed.

You really have no way to know what the state of the data is.

If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then NOLOCK is a good way to boost performance for these queries and avoid having them negatively impact database performance.

Always use the NOLOCK hint with great caution and treat any data it returns suspiciously.

How can I present a file for download from an MVC controller?

mgnoonan,

You can do this to return a FileStream:

/// <summary>
/// Creates a new Excel spreadsheet based on a template using the NPOI library.
/// The template is changed in memory and a copy of it is sent to
/// the user computer through a file stream.
/// </summary>
/// <returns>Excel report</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult NPOICreate()
{
    try
    {
        // Opening the Excel template...
        FileStream fs =
            new FileStream(Server.MapPath(@"\Content\NPOITemplate.xls"), FileMode.Open, FileAccess.Read);

        // Getting the complete workbook...
        HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);

        // Getting the worksheet by its name...
        HSSFSheet sheet = templateWorkbook.GetSheet("Sheet1");

        // Getting the row... 0 is the first row.
        HSSFRow dataRow = sheet.GetRow(4);

        // Setting the value 77 at row 5 column 1
        dataRow.GetCell(0).SetCellValue(77);

        // Forcing formula recalculation...
        sheet.ForceFormulaRecalculation = true;

        MemoryStream ms = new MemoryStream();

        // Writing the workbook content to the FileStream...
        templateWorkbook.Write(ms);

        TempData["Message"] = "Excel report created successfully!";

        // Sending the server processed data back to the user computer...
        return File(ms.ToArray(), "application/vnd.ms-excel", "NPOINewFile.xls");
    }
    catch(Exception ex)
    {
        TempData["Message"] = "Oops! Something went wrong.";

        return RedirectToAction("NPOI");
    }
}

What is the difference between Html.Hidden and Html.HiddenFor

Every method in HtmlHelper class has a twin with For suffix. Html.Hidden takes a string as an argument that you must provide but Html.HiddenFor takes an Expression that if you view is a strongly typed view you can benefit from this and feed that method a lambda expression like this

o=>o.SomeProperty 

instead of "SomeProperty" in the case of using Html.Hidden method.

With android studio no jvm found, JAVA_HOME has been set

Here is the tutorial :- http://javatechig.com/android/installing-android-studio and http://codearetoy.wordpress.com/2010/12/23/jdk-not-found-on-installing-android-sdk/

Adding a system variable JDK_HOME with value c:\Program Files\Java\jdk1.7.0_21\ worked for me. The latest Java release can be downloaded here. Additionally, make sure the variable JAVA_HOME is also set with the above location.

Please note that the above location is my java location. Please post your location in the path

Converting serial port data to TCP/IP in a Linux environment

You can create a serial-over-LAN (SOL) connection by using socat. It can be used to 'forward' a ttyS to another machine so it appears as a local one or you can access it via a TCP/IP port.

Django: Get list of model fields?

At least with Django 1.9.9 -- the version I'm currently using --, note that .get_fields() actually also "considers" any foreign model as a field, which may be problematic. Say you have:

class Parent(models.Model):
    id = UUIDField(primary_key=True)

class Child(models.Model):
    parent = models.ForeignKey(Parent)

It follows that

>>> map(lambda field:field.name, Parent._model._meta.get_fields())
['id', 'child']

while, as shown by @Rockallite

>>> map(lambda field:field.name, Parent._model._meta.local_fields)
['id']

MySQL Trigger after update only if row has changed

Use the following query to see which rows have changes:

(select * from inserted) except (select * from deleted)

The results of this query should consist of all the new records that are different from the old ones.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.

:first-child not working as expected

For that particular case you can use:

.detail_container > ul + h1{ 
    color: blue; 
}

But if you need that same selector on many cases, you should have a class for those, like BoltClock said.

How do I limit the number of results returned from grep?

Awk approach:

awk '/pattern/{print; count++; if (count==10) exit}' file

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

Sending images using Http Post

Version 4.3.5 Updated Code

  • httpclient-4.3.5.jar
  • httpcore-4.3.2.jar
  • httpmime-4.3.5.jar

Since MultipartEntity has been deprecated. Please see the code below.

String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);

HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);

if (career != null)
    builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
    builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
    builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
    builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
    builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
    builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
    builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());

post.setEntity(builder.build());

try {
    responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
//  System.out.println("Response from Server ==> " + responseBody);

    JSONObject object = new JSONObject(responseBody);
    Boolean success = object.optBoolean("success");
    String message = object.optString("error");

    if (!success) {
        responseBody = message;
    } else {
        responseBody = "success";
    }

} catch (Exception e) {
    e.printStackTrace();
} finally {
    client.getConnectionManager().shutdown();
}

MySQL - count total number of rows in php

<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>

Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php

Permissions error when connecting to EC2 via SSH on Mac OSx

Are you sure you have used the right instance? I ran into this problem and realized that something like 4 of the ubuntu instances i tried did not have SSH servers installed on them.

For a list of good servers see "Getting the images" about half way down. Sounds like you may be using something else... the default username is ubuntu on these images.

https://help.ubuntu.com/community/EC2StartersGuide

How can I ping a server port with PHP?

You can use exec function

 exec("ping ".$ip);

here an example

How to do the equivalent of pass by reference for primitives in Java

Make a

class PassMeByRef { public int theValue; }

then pass a reference to an instance of it. Note that a method that mutates state through its arguments is best avoided, especially in parallel code.

Convert character to ASCII numeric value in java

Just cast the char to an int.

char character = 'a';
int number = (int) character;

The value of number will be 97.

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

AndroidManifest.xml:

<uses-sdk
    android:minSdkVersion=...
    android:targetSdkVersion="11" />

and

Project Properties -> Project Build Target = 11 or above

These 2 things fixed the problem for me!

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.

Right-click project in Package explorer Build path -> Add external archives...

Select your ojdbc6.jar archive

Press OK

Or

Go through this link and read and do carefully.

The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

@Html.Partial("nameOfPartial", Model)

Update

protected string RenderPartialViewToString(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model;

    using (StringWriter sw = new StringWriter()) {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

Copy values from one column to another in the same table

try following:

UPDATE `list` SET `test` = `number` 

it creates copy of all values from "number" and paste it to "test"

Notepad++ - How can I replace blank lines

This will remove any number of blank lines

CTRL + H to replace

Select Extended search mode

replace all \r\n with (space)

then switch to regular expression and replace all \s+ with \n

Convert Dictionary to JSON in Swift

Swift 5:

let dic = ["2": "B", "1": "A", "3": "C"]
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dic) {
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString)
    }
}

Note that keys and values must implement Codable. Strings, Ints, and Doubles (and more) are already Codable. See Encoding and Decoding Custom Types.

How to make CREATE OR REPLACE VIEW work in SQL Server?

Edit: Although this question has been marked as a duplicate, it has still been getting attention. The answer provided by @JaKXz is correct and should be the accepted answer.


You'll need to check for the existence of the view. Then do a CREATE VIEW or ALTER VIEW depending on the result.

IF OBJECT_ID('dbo.data_VVVV') IS NULL
BEGIN
    CREATE VIEW dbo.data_VVVV
    AS
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
END
ELSE
    ALTER VIEW dbo.data_VVVV
    AS
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
BEGIN
END

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

Iterate through string array in Java

String[] elements = { "a", "a", "a", "a" };

for( int i = 0; i < elements.length - 1; i++)
{
    String element = elements[i];
    String nextElement = elements[i+1];
}

Note that in this case, elements.length is 4, so you want to iterate from [0,2] to get elements 0,1, 1,2 and 2,3.

Switch statement with returns -- code correctness

Remove them. It's idiomatic to return from case statements, and it's "unreachable code" noise otherwise.

Formatting floats in a numpy array

You can use round function. Here some example

numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53,   8.13,   3.97,  10.08])

IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.

>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']

SVN Commit specific files

Sure. Just list the files:

$ svn ci -m "Fixed all those horrible crashes" foo bar baz graphics/logo.png

I'm not aware of a way to tell it to ignore a certain set of files. Of course, if the files you do want to commit are easily listed by the shell, you can use that:

$ svn ci -m "No longer sets printer on fire" printer-driver/*.c

You can also have the svn command read the list of files to commit from a file:

$ svn ci -m "Now works" --targets fix4711.txt

Differences between strong and weak in Objective-C

It may be helpful to think about strong and weak references in terms of balloons.

A balloon will not fly away as long as at least one person is holding on to a string attached to it. The number of people holding strings is the retain count. When no one is holding on to a string, the ballon will fly away (dealloc). Many people can have strings to that same balloon. You can get/set properties and call methods on the referenced object with both strong and weak references.

A strong reference is like holding on to a string to that balloon. As long as you are holding on to a string attached to the balloon, it will not fly away.

A weak reference is like looking at the balloon. You can see it, access it's properties, call it's methods, but you have no string to that balloon. If everyone holding onto the string lets go, the balloon flies away, and you cannot access it anymore.

How do I upgrade the Python installation in Windows 10?

Installing/Upgrading Python Using the Chocolatey Windows Package Manager

Let's say you have Python 2.7.16:

    C:\Windows\system32>python --version
    python2 2.7.16

...and you want to upgrade to the (now current) 3.x.y version. There is a simple way to install a parallel installation of Python 3.x.y using a Windows package management tool.

Now that modern Windows has package management, just like Debian Linux distributions have apt-get, and RedHat has dnf: we can put it to work for us! It's called Chocolatey.

What's Chocolatey?

Chocolatey is a scriptable, command line tool that is based on .NET 4.0 and the nuget package manager baked into Visual Studio.

If you want to learn about Chocolatey and why to use it, which some here reading this might find particularly useful, go to https://chocolatey.org/docs/why

Installing Chocolatey

To get the Chocolatey Package Manager, you follow a process that is described at https://chocolatey.org/docs/installation#installing-chocolatey,

I'll summarize it for you here. There are basically two options: using the cmd prompt, or using the PowerShell prompt.

CMD Prompt Chocolatey Installation

Launch an administrative command prompt. On Windows 10, to do this:

  • Windows+R
  • Type cmd
  • Press ctrl+shift+Enter

If you don't have administrator rights on the system, go to the Chocolatey website. You may not be completely out of luck and can perform a limited local install, but I won't cover that here.

  • Copy the string below into your command prompt and type Enter:
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

Chocolatey will be downloaded and installed for you as below:

Getting latest version of the Chocolatey package for download.
Getting Chocolatey from https://chocolatey.org/api/v2/package/chocolatey/0.10.11.
Downloading 7-Zip commandline tool prior to extraction.
Extracting C:\Users\blahblahblah\AppData\Local\Temp\chocolatey\chocInstall\chocolatey.zip to C:\Users\blahblahblah\AppData\Local\Temp\chocolatey\chocInstall...
Installing chocolatey on this machine
Creating ChocolateyInstall as an environment variable (targeting 'Machine')
  Setting ChocolateyInstall to 'C:\ProgramData\chocolatey'
WARNING: It's very likely you will need to close and reopen your shell
  before you can use choco.
Restricting write permissions to Administrators
We are setting up the Chocolatey package repository.
The packages themselves go to 'C:\ProgramData\chocolatey\lib'
  (i.e. C:\ProgramData\chocolatey\lib\yourPackageName).
A shim file for the command line goes to 'C:\ProgramData\chocolatey\bin'
  and points to an executable in 'C:\ProgramData\chocolatey\lib\yourPackageName'.

Creating Chocolatey folders if they do not already exist.

WARNING: You can safely ignore errors related to missing log files when
  upgrading from a version of Chocolatey less than 0.9.9.
  'Batch file could not be found' is also safe to ignore.
  'The system cannot find the file specified' - also safe.
chocolatey.nupkg file not installed in lib.
 Attempting to locate it from bootstrapper.
PATH environment variable does not have C:\ProgramData\chocolatey\bin in it. Adding...
WARNING: Not setting tab completion: Profile file does not exist at 'C:\Users\blahblahblah\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'.
Chocolatey (choco.exe) is now ready.
You can call choco from anywhere, command line or powershell by typing choco.
Run choco /? for a list of functions.
You may need to shut down and restart powershell and/or consoles
 first prior to using choco.
Ensuring chocolatey commands are on the path
Ensuring chocolatey.nupkg is in the lib folder

Either Exit the CMD prompt or type the following command to reload the environment variables:

refreshenv

PowerShell Chocolatey Installation

If you prefer PowerShell to the cmd prompt, you can do this directly from there, however you will have to tell PowerShell to run with a proper script execution policy to get it to work. On Windows 10, the simplest way I have found to do this is to type the following into the Cortana search bar next to the Windows button:

PowerShell.exe

Next, right click on the 'Best Match' choice in the menu that pops up and select 'Run as Administrator'

Now that you're in PowerShell, hopefully running with Administrator privileges, execute the following to install Chocolatey:

Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

PowerShell will download Chocolatey for you and launch the installation. It only takes a few moments. It looks exactly like the CMD installation, save perhaps some fancy colored text.

Either Exit PowerShell or type the following command to reload the environment variables:

refreshenv

Upgrading Python

The choco command is the same whether you use PowerShell or the cmd prompt. Launch your favorite using the instructions as above. I'll use the administrator cmd prompt:

C:\WINDOWS\system32>choco upgrade python -y

Essentially, chocolatey will tell you "Hey, Python isn't installed" since you're coming from 2.7.x and it treats the 2.7 version as completely separate. It is only going to give you the most current version, 3.x.y (as of this writing, 3.7.2, but that will change in a few months):

Chocolatey v0.10.11
Upgrading the following packages:
python
By upgrading you accept licenses for the packages.
python is not installed. Installing...

python3 v3.x.y [Approved]
python3 package files upgrade completed. Performing other installation steps.
Installing 64-bit python3...
python3 has been installed.
Installed to: 'C:\Python37' 
  python3 can be automatically uninstalled.
Environment Vars (like PATH) have changed. Close/reopen your shell to
 see the changes (or in powershell/cmd.exe just type `refreshenv`).
 The upgrade of python3 was successful.
  Software installed as 'exe', install location is likely default.

python v3.x.y [Approved]
python package files upgrade completed. Performing other installation steps.
 The upgrade of python was successful.
  Software install location not explicitly set, could be in package or
  default install location if installer.

Chocolatey upgraded 2/2 packages.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).

Either exit out of the cmd/Powershell prompt and re-enter it, or use refreshenv then type py --version

C:\Windows\System32>refreshenv
Refreshing environment variables from registry for cmd.exe. Please wait...Finished..

C:\Windows\system32>py --version
Python 3.7.2

Note that the most recent Python install will now take over when you type Python at the command line. You can run either version by using the following commands:

py -2
Python 2.7.16 (v2.7.16:413a49145e, Mar  4 2019, 01:37:19) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

C:\>py -3
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>exit()
C:\>

From here I suggest you use the Python pip utility to install whatever packages you need. For example, let's say you wanted to install Flask. The commands below first upgrade pip, then install Flask

C:\>py -3 -m pip install --upgrade pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/d8/f3/413bab4ff08e1fc4828dfc59996d721917df8e8583ea85385d51125dceff/pip-19.0.3-py2.py3-none-any.whl (1.4MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 1.4MB 1.6MB/s
Installing collected packages: pip
  Found existing installation: pip 18.1
    Uninstalling pip-18.1:
      Successfully uninstalled pip-18.1
Successfully installed pip-19.0.3

c:\>py -3 -m pip install Flask

...will do the trick. Happy Pythoning!

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

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

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

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

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

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

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

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

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

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Is it possible to start a shell session in a running container (without ssh)

There is actually a way to have a shell in the container.

Assume your /root/run.sh launches the process, process manager (supervisor), or whatever.

Create /root/runme.sh with some gnu-screen tricks:

# Spawn a screen with two tabs
screen -AdmS 'main' /root/run.sh
screen -S 'main' -X screen bash -l
screen -r 'main'

Now, you have your daemons in tab 0, and an interactive shell in tab 1. docker attach at any time to see what's happening inside the container.

Another advice is to create a "development bundle" image on top of the production image with all the necessary tools, including this screen trick.

Comparing two collections for equality irrespective of the order of items in them

If comparing for the purpose of Unit Testing Assertions, it may make sense to throw some efficiency out the window and simply convert each list to a string representation (csv) before doing the comparison. That way, the default test Assertion message will display the differences within the error message.

Usage:

using Microsoft.VisualStudio.TestTools.UnitTesting;

// define collection1, collection2, ...

Assert.Equal(collection1.OrderBy(c=>c).ToCsv(), collection2.OrderBy(c=>c).ToCsv());

Helper Extension Method:

public static string ToCsv<T>(
    this IEnumerable<T> values,
    Func<T, string> selector,
    string joinSeparator = ",")
{
    if (selector == null)
    {
        if (typeof(T) == typeof(Int16) ||
            typeof(T) == typeof(Int32) ||
            typeof(T) == typeof(Int64))
        {
            selector = (v) => Convert.ToInt64(v).ToStringInvariant();
        }
        else if (typeof(T) == typeof(decimal))
        {
            selector = (v) => Convert.ToDecimal(v).ToStringInvariant();
        }
        else if (typeof(T) == typeof(float) ||
                typeof(T) == typeof(double))
        {
            selector = (v) => Convert.ToDouble(v).ToString(CultureInfo.InvariantCulture);
        }
        else
        {
            selector = (v) => v.ToString();
        }
    }

    return String.Join(joinSeparator, values.Select(v => selector(v)));
}

Checkout multiple git repos into same Jenkins workspace

Checking out more than one repo at a time in a single workspace is not possible with Jenkins + Git Plugin.

As a workaround, you can either have multiple upstream jobs which checkout a single repo each and then copy to your final project workspace (Problematic on a number of levels), or you can set up a shell scripting step which checks out each needed repo to the job workspace at build time.

Previously the Multiple SCM plugin could help with this issue but it is now deprecated. From the Multiple SCM plugin page: "Users should migrate to https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin . Pipeline offers a better way of checking out of multiple SCMs, and is supported by the Jenkins core development team."

Extract matrix column values by matrix column name

Yes. But place your "test" after the comma if you want the column...

> A <- matrix(sample(1:12,12,T),ncol=4)

> rownames(A) <- letters[1:3]

> colnames(A) <- letters[11:14]
> A[,"l"]
 a  b  c 
 6 10  1 

see also help(Extract)

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

Invoke-WebRequest follows the RFC2617 as @briantist noted, however there are some systems (e.g. JFrog Artifactory) that allow anonymous usage if the Authorization header is absent, but will respond with 401 Forbidden if the header contains invalid credentials.

This can be used to trigger the 401 Forbidden response and get -Credentials to work.

$login = Get-Credential -Message "Enter Credentials for Artifactory"

                              #Basic foo:bar
$headers = @{ Authorization = "Basic Zm9vOmJhcg==" }  

Invoke-WebRequest -Credential $login -Headers $headers -Uri "..."

This will send the invalid header the first time, which will be replaced with the valid credentials in the second request since -Credentials overrides the Authorization header.

Tested with Powershell 5.1

Is Python interpreted, or compiled, or both?

According to the official Python site, it's interpreted.

https://www.python.org/doc/essays/blurb/

Python is an interpreted, object-oriented, high-level programming language...

...

Since there is no compilation step ...

...

The Python interpreter and the extensive standard library are available...

...

Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace.

Combining Two Images with OpenCV

For cases where your images happen to be the same size (which is a common case for displaying image processing results), you can use numpy's concatenate to simplify your code.

To stack vertically (img1 over img2):

vis = np.concatenate((img1, img2), axis=0)

To stack horizontally (img1 to the left of img2):

vis = np.concatenate((img1, img2), axis=1)

To verify:

import cv2
import numpy as np
img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')
vis = np.concatenate((img1, img2), axis=1)
cv2.imwrite('out.png', vis)

The out.png image will contain img1 on the left and img2 on the right.

DateTimePicker: pick both date and time

Unfortunately, this is one of the many misnomers in the framework, or at best a violation of SRP.

To use the DateTimePicker for times, set the Format property to either Time or Custom (Use Custom if you want to control the format of the time using the CustomFormat property). Then set the ShowUpDown property to true.

Although a user may set the date and time together manually, they cannot use the GUI to set both.

Dynamically Add Variable Name Value Pairs to JSON Object

I'm assuming each entry in "ips" can have multiple name value pairs - so it's nested. You can achieve this data structure as such:

var ips = {}

function addIpId(ipID, name, value) {
    if (!ips[ipID]) ip[ipID] = {};
    var entries = ip[ipID];
    // you could add a check to ensure the name-value par's not already defined here
    var entries[name] = value;
}

Incrementing a variable inside a Bash loop

while read -r country _; do
  if [[ $country = 'US' ]]; then
    ((USCOUNTER++))
    echo "US counter $USCOUNTER"
  fi
done < "$FILE"

sed one-liner to convert all uppercase to lowercase?

You also can do this very easily with awk, if you're willing to consider a different tool:

echo "UPPER" | awk '{print tolower($0)}'

Set encoding and fileencoding to utf-8 in Vim

set encoding=utf-8  " The encoding displayed.
set fileencoding=utf-8  " The encoding written to file.

You may as well set both in your ~/.vimrc if you always want to work with utf-8.

Finding moving average from data points in Python

As numpy.convolve is pretty slow, those who need a fast performing solution might prefer an easier to understand cumsum approach. Here is the code:

cumsum_vec = numpy.cumsum(numpy.insert(data, 0, 0)) 
ma_vec = (cumsum_vec[window_width:] - cumsum_vec[:-window_width]) / window_width

where data contains your data, and ma_vec will contain moving averages of window_width length.

On average, cumsum is about 30-40 times faster than convolve.

How to keep footer at bottom of screen

You could use position:fixed; to bottom.

eg:

#footer{
 position:fixed;
 bottom:0;
 left:0;
}

C++ style cast from unsigned char * to const char *

Hope it help. :)

const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;

Select multiple records based on list of Id's with linq

You can use Contains() for that. It will feel a little backwards when you're really trying to produce an IN clause, but this should do it:

var userProfiles = _dataContext.UserProfile
                               .Where(t => idList.Contains(t.Id));

I'm also assuming that each UserProfile record is going to have an int Id field. If that's not the case you'll have to adjust accordingly.

How can I start InternetExplorerDriver using Selenium WebDriver

In c#, This can bypass changing protected zone settings.

var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
options.ElementScrollBehavior = InternetExplorerElementScrollBehavior.Bottom;

Regex pattern to match at least 1 number and 1 character in a string

While the accepted answer is correct, I find this regex a lot easier to read:

REGEX = "([A-Za-z]+[0-9]|[0-9]+[A-Za-z])[A-Za-z0-9]*"

Convert IEnumerable to DataTable

A 2019 answer if you're using .NET Core - use the Nuget ToDataTable library. Advantages:

Disclaimer - I'm the author of ToDataTable

Performance - I span up some Benchmark .Net tests and included them in the ToDataTable repo. The results were as follows:

Creating a 100,000 Row Datatable:

Reflection                 818.5 ms
DataTableProxy           1,068.8 ms
ToDataTable                449.0 ms

Set width to match constraints in ConstraintLayout

If you want TextView in the center of parent..
Your main layout is Constraint Layout

<androidx.appcompat.widget.AppCompatTextView
     android:layout_width="0dp"
     android:layout_height="wrap_content"
     android:text="@string/logout"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     android:gravity="center">
</androidx.appcompat.widget.AppCompatTextView>

importing pyspark in python shell

I had the same problem.

Also make sure you are using right python version and you are installing it with right pip version. in my case: I had both python 2.7 and 3.x. I have installed pyspark with

pip2.7 install pyspark

and it worked.

$(window).width() not the same as media query

If you don't have to support IE9 you can just use window.matchMedia() (MDN documentation).

function checkPosition() {
    if (window.matchMedia('(max-width: 767px)').matches) {
        //...
    } else {
        //...
    }
}

window.matchMedia is fully consistent with the CSS media queries and the browser support is quite good: http://caniuse.com/#feat=matchmedia

UPDATE:

If you have to support more browsers you can use Modernizr's mq method, it supports all browsers that understand media queries in CSS.

if (Modernizr.mq('(max-width: 767px)')) {
    //...
} else {
    //...
}

How to add parameters to a HTTP GET request in Android?

The method

setParams() 

like

httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));

only adds HttpProtocol parameters.

To execute the httpGet you should append your parameters to the url manually

HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo&param2=bar");

or use the post request the difference between get and post requests are explained here, if you are interested

How to delete a folder in C++?

//For windows:

#include <direct.h>


if(_rmdir("FILEPATHHERE") != -1)
{
  //success     
} else {
  //failure
}

Unable to find a @SpringBootConfiguration when doing a JpaTest

This is more the the error itself, not answering the original question:

We were migrating from java 8 to java 11. Application compiled successfully, but the errors Unable to find a @SpringBootConfiguration started to appear in the integration tests when ran from command line using maven (from IntelliJ it worked).

It appeared that maven-failsafe-plugin stopped seeing the classes on classpath, we fixed that by telling failsafe plugin to include the classes manually:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <configuration>
                <additionalClasspathElements>
                    <additionalClasspathElement>${basedir}/target/classes</additionalClasspathElement>
                </additionalClasspathElements>
            </configuration>
            ...
        </plugin>

How to edit default dark theme for Visual Studio Code?

Any color theme can be changed in this settings section on VS Code version 1.12 or higher:

 // Overrides colors from the currently selected color theme.
  "workbench.colorCustomizations": {}

See https://code.visualstudio.com/docs/getstarted/themes#_customize-a-color-theme

Available values to edit: https://code.visualstudio.com/docs/getstarted/theme-color-reference

EDIT: To change syntax colors, see here: https://code.visualstudio.com/docs/extensions/themes-snippets-colorizers#_syntax-highlighting-colors and here: https://www.sublimetext.com/docs/3/scope_naming.html

Lotus Notes email as an attachment to another email

Copy the mail as a document link (right click on the mail and you should get this option) and paste it in the new mail. This worked for me

Facebook user url by id

The easiest and the most correct (and legal) way is to use graph api.

Just perform the request: http://graph.facebook.com/4

which returns

{
   "id": "4",
   "name": "Mark Zuckerberg",
   "first_name": "Mark",
   "last_name": "Zuckerberg",
   "link": "http://www.facebook.com/zuck",
   "username": "zuck",
   "gender": "male",
   "locale": "en_US"
}

and take the link key.

You can also reduce the traffic by using fields parameter: http://graph.facebook.com/4?fields=link to get only what you need:

{
   "link": "http://www.facebook.com/zuck",
   "id": "4"
}

PHP Configuration: It is not safe to rely on the system's timezone settings

try this, it works for me.

date_default_timezone_set('America/New_York');

In the actual file that was complaining.

Use latest version of Internet Explorer in the webbrowser control

Combine the answers of RooiWillie and MohD
and remember to run your app with administrative right.

var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";

RegistryKey Regkey = null;
try
{
    int BrowserVer, RegVal;

    // get the installed IE version
    using (WebBrowser Wb = new WebBrowser())
        BrowserVer = Wb.Version.Major;

    // set the appropriate IE version
    if (BrowserVer >= 11)
        RegVal = 11001;
    else if (BrowserVer == 10)
        RegVal = 10001;
    else if (BrowserVer == 9)
        RegVal = 9999;
    else if (BrowserVer == 8)
        RegVal = 8888;
    else
        RegVal = 7000;

    //For 64 bit Machine 
    if (Environment.Is64BitOperatingSystem)
        Regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
    else  //For 32 bit Machine 
        Regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);

    //If the path is not correct or 
    //If user't have priviledges to access registry 
    if (Regkey == null)
    {
        MessageBox.Show("Registry Key for setting IE WebBrowser Rendering Address Not found. Try run the program with administrator's right.");
        return;
    }

    string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

    //Check if key is already present 
    if (FindAppkey == RegVal.ToString())
    {
        Regkey.Close();
        return;
    }

    Regkey.SetValue(appName, RegVal, RegistryValueKind.DWord);
}
catch (Exception ex)
{
    MessageBox.Show("Registry Key for setting IE WebBrowser Rendering failed to setup");
    MessageBox.Show(ex.Message);
}
finally
{
    //Close the Registry 
    if (Regkey != null)
        Regkey.Close();
}

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

You should use Java's built in serialization mechanism. To use it, you need to do the following:

  1. Declare the Club class as implementing Serializable:

    public class Club implements Serializable {
        ...
    }
    

    This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.

  2. To write your list to a file do the following:

    FileOutputStream fos = new FileOutputStream("t.tmp");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(clubs);
    oos.close();
    
  3. To read the list from a file, do the following:

    FileInputStream fis = new FileInputStream("t.tmp");
    ObjectInputStream ois = new ObjectInputStream(fis);
    List<Club> clubs = (List<Club>) ois.readObject();
    ois.close();
    

HTML form with two submit buttons and two "target" attributes

HTML:

<form method="get">
<input type="text" name="id" value="123"/>
<input type="submit" name="action" value="add"/>
<input type="submit" name="action" value="delete"/>
</form>

JS:

$('form').submit(function(ev){ 
ev.preventDefault();
console.log('clicked',ev.originalEvent,ev.originalEvent.explicitOriginalTarget) 
})

http://jsfiddle.net/arzo/unhc3/

Pick any kind of file via an Intent in Android

This gives me the best result:

    Intent intent;
    if (android.os.Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
        intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
        intent.putExtra("CONTENT_TYPE", "*/*");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
    } else {

        String[] mimeTypes =
                {"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
                        "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
                        "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
                        "text/plain",
                        "application/pdf",
                        "application/zip", "application/vnd.android.package-archive"};

        intent = new Intent(Intent.ACTION_GET_CONTENT); // or ACTION_OPEN_DOCUMENT
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    }

How to wait for 2 seconds?

The documentation for WAITFOR() doesn't explicitly lay out the required string format.

This will wait for 2 seconds:

WAITFOR DELAY '00:00:02';

The format is hh:mi:ss.mmm.

Play/pause HTML 5 video using JQuery

_x000D_
_x000D_
var vid = document.getElementById("myVideo"); _x000D_
function playVid() { _x000D_
  vid.play(); _x000D_
} _x000D_
function pauseVid() { _x000D_
  vid.pause(); _x000D_
} 
_x000D_
<video id="myVideo" width="320" height="176">_x000D_
  <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">_x000D_
  <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.ogg" type="video/ogg">_x000D_
  Your browser does not support HTML5 video._x000D_
</video>_x000D_
<button onclick="playVid()" type="button">Play Video</button>_x000D_
<button onclick="pauseVid()" type="button">Pause Video</button><br> 
_x000D_
_x000D_
_x000D_

Get decimal portion of a number with JavaScript

You can use parseInt() function to get the integer part than use that to extract the decimal part

var myNumber = 3.2;
var integerPart = parseInt(myNumber);
var decimalPart = myNumber - integerPart;

Or you could use regex like:

splitFloat = function(n){
   const regex = /(\d*)[.,]{1}(\d*)/;
   var m;

   if ((m = regex.exec(n.toString())) !== null) {
       return {
          integer:parseInt(m[1]),
          decimal:parseFloat(`0.${m[2]}`)
       }
   }
}

Spring Could not Resolve placeholder

in my case, the war file generated didn't pick up the properties file so had to clean install again in IntelliJ editor.

Effective way to find any file's Encoding

The following code works fine for me, using the StreamReader class:

  using (var reader = new StreamReader(fileName, defaultEncodingIfNoBom, true))
  {
      reader.Peek(); // you need this!
      var encoding = reader.CurrentEncoding;
  }

The trick is to use the Peek call, otherwise, .NET has not done anything (and it hasn't read the preamble, the BOM). Of course, if you use any other ReadXXX call before checking the encoding, it works too.

If the file has no BOM, then the defaultEncodingIfNoBom encoding will be used. There is also a StreamReader without this overload method (in this case, the Default (ANSI) encoding will be used as defaultEncodingIfNoBom), but I recommand to define what you consider the default encoding in your context.

I have tested this successfully with files with BOM for UTF8, UTF16/Unicode (LE & BE) and UTF32 (LE & BE). It does not work for UTF7.

Anybody knows any knowledge base open source?

Here comes another vote in favor of PHPKB knowledge base software. We came to know about PHPKB from this post on StackOverflow and bought it as recommended by Julien and Ricardo. I am glad to inform that it was a right decision. Although we had to get certain features customized according to our needs but their support team exceeded our expectations. So, I just thought of sharing the news here. We are fully satisfied with PHPKB knowledge base software.

Logging request/response messages when using HttpClient

Network tracing also available for next objects (see article on msdn)

  • System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
  • System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
  • System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
  • System.Net.Cache Some private and internal methods in System.Net.Cache.
  • System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
  • System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.

Put next lines of code to the configuration file

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Cache">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Http">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Sockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.WebSockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <add name="System.Net" value="Verbose"/>  
      <add name="System.Net.Cache" value="Verbose"/>  
      <add name="System.Net.Http" value="Verbose"/>  
      <add name="System.Net.Sockets" value="Verbose"/>  
      <add name="System.Net.WebSockets" value="Verbose"/>  
    </switches>  
    <sharedListeners>  
      <add name="System.Net"  
        type="System.Diagnostics.TextWriterTraceListener"  
        initializeData="network.log"  
      />  
    </sharedListeners>  
    <trace autoflush="true"/>  
  </system.diagnostics>  
</configuration>  

How do I inject a controller into another controller in AngularJS

I'd suggest the question you should be asking is how to inject services into controllers. Fat services with skinny controllers is a good rule of thumb, aka just use controllers to glue your service/factory (with the business logic) into your views.

Controllers get garbage collected on route changes, so for example, if you use controllers to hold business logic that renders a value, your going to lose state on two pages if the app user clicks the browser back button.

var app = angular.module("testApp", ['']);

app.factory('methodFactory', function () {
    return { myMethod: function () {
            console.log("methodFactory - myMethod");
    };
};

app.controller('TestCtrl1', ['$scope', 'methodFactory', function ($scope,methodFactory) {  //Comma was missing here.Now it is corrected.
    $scope.mymethod1 = methodFactory.myMethod();
}]);

app.controller('TestCtrl2', ['$scope', 'methodFactory', function ($scope, methodFactory) {
    $scope.mymethod2 = methodFactory.myMethod();
}]);

Here is a working demo of factory injected into two controllers

Also, I'd suggest having a read of this tutorial on services/factories.

Viewing full version tree in git

There is a very good answer to the same question.
Adding following lines to "~/.gitconfig":

[alias]
lg1 = log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
lg = !"git lg1"

Best practices with STDIN in Ruby?

Following are some things I found in my collection of obscure Ruby.

So, in Ruby, a simple no-bells implementation of the Unix command cat would be:

#!/usr/bin/env ruby
puts ARGF.read

ARGF is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.

ARGF.each_with_index do |line, idx|
    print ARGF.filename, ":", idx, ";", line
end

# print all the lines in every file passed via command line that contains login
ARGF.each do |line|
    puts line if line =~ /login/
end

Thank goodness we didn’t get the diamond operator in Ruby, but we did get ARGF as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, -i) to every file mentioned on the command-line:

#!/usr/bin/env ruby -i

Header = DATA.read

ARGF.each_line do |e|
  puts Header if ARGF.pos - e.length == 0
  puts e
end

__END__
#--
# Copyright (C) 2007 Fancypants, Inc.
#++

Credit to:

How to tar certain file types in all subdirectories?

One method is:

tar -cf my_archive.tar $( find -name "*.php" -or -name "*.html" )

There are some caveats with this method however:

  1. It will fail if there are any files or directories with spaces in them, and
  2. it will fail if there are so many files that the maximum command line length is full.

A workaround to these could be to output the contents of the find command into a file, and then use the "-T, --files-from FILE" option to tar.

Refused to execute script, strict MIME type checking is enabled?

Add the code snippet as shown below to the entry html. i.e "index.html" in reactjs

_x000D_
_x000D_
<div id="wrapper"></div>_x000D_
<base href="/" />
_x000D_
_x000D_
_x000D_

javascript: get a function's variable's value within another function

Your nameContent variable is inside the function scope and not visible outside that function so if you want to use the nameContent outside of the function then declare it global inside the <script> tag and use inside functions without the var keyword as follows

<script language="javascript" type="text/javascript">
    var nameContent; // In the global scope
    function first(){
        nameContent=document.getElementById('full_name').value;
    }

    function second() {
        first();
        y=nameContent; 
        alert(y);
    }
    second();
</script>

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

CSS file not refreshing in browser

I always use Ctrl+Shift+F5 out of habit, it should force a full-refresh including by-passing any http proxies you may be going through.

How can I check for existence of element in std::vector, in one line?

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

How can I split a text into sentences?

Here is a middle of the road approach that doesn't rely on any external libraries. I use list comprehension to exclude overlaps between abbreviations and terminators as well as to exclude overlaps between variations on terminations, for example: '.' vs. '."'

abbreviations = {'dr.': 'doctor', 'mr.': 'mister', 'bro.': 'brother', 'bro': 'brother', 'mrs.': 'mistress', 'ms.': 'miss', 'jr.': 'junior', 'sr.': 'senior',
                 'i.e.': 'for example', 'e.g.': 'for example', 'vs.': 'versus'}
terminators = ['.', '!', '?']
wrappers = ['"', "'", ')', ']', '}']


def find_sentences(paragraph):
   end = True
   sentences = []
   while end > -1:
       end = find_sentence_end(paragraph)
       if end > -1:
           sentences.append(paragraph[end:].strip())
           paragraph = paragraph[:end]
   sentences.append(paragraph)
   sentences.reverse()
   return sentences


def find_sentence_end(paragraph):
    [possible_endings, contraction_locations] = [[], []]
    contractions = abbreviations.keys()
    sentence_terminators = terminators + [terminator + wrapper for wrapper in wrappers for terminator in terminators]
    for sentence_terminator in sentence_terminators:
        t_indices = list(find_all(paragraph, sentence_terminator))
        possible_endings.extend(([] if not len(t_indices) else [[i, len(sentence_terminator)] for i in t_indices]))
    for contraction in contractions:
        c_indices = list(find_all(paragraph, contraction))
        contraction_locations.extend(([] if not len(c_indices) else [i + len(contraction) for i in c_indices]))
    possible_endings = [pe for pe in possible_endings if pe[0] + pe[1] not in contraction_locations]
    if len(paragraph) in [pe[0] + pe[1] for pe in possible_endings]:
        max_end_start = max([pe[0] for pe in possible_endings])
        possible_endings = [pe for pe in possible_endings if pe[0] != max_end_start]
    possible_endings = [pe[0] + pe[1] for pe in possible_endings if sum(pe) > len(paragraph) or (sum(pe) < len(paragraph) and paragraph[sum(pe)] == ' ')]
    end = (-1 if not len(possible_endings) else max(possible_endings))
    return end


def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1:
            return
        yield start
        start += len(sub)

I used Karl's find_all function from this entry: Find all occurrences of a substring in Python

Login credentials not working with Gmail SMTP

I had the same issue. The Authentication Error can be because of your security settings, the 2-step verification for instance. It wont allow third party apps to override the authentication.

Log in to your Google account, and use these links:

Step 1 [Link of Disabling 2-step verification]:

https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin

Step 2: [Link for Allowing less secure apps]

https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none

It should be all good now.

Connection Java-MySql : Public Key Retrieval is not allowed

First of all, please make sure your Database server is up and running. I was getting the same error, after trying all the answers listed here I found out that my Database server was not running.

You can check the same from MySQL Workbench, or Command line using

mysql -u USERNAME -p

This sounds obvious, but many times we assume that Database server is up and running all the time, especially when we are working on our local machine, when we restart/shutdown the machine, Database server will be shutdown automatically.

Sending HTML email using Python

Here's a working example to send plain text and HTML emails from Python using smtplib along with the CC and BCC options.

https://varunver.wordpress.com/2017/01/26/python-smtplib-send-plaintext-and-html-emails/

#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_mail(params, type_):
      email_subject = params['email_subject']
      email_from = "[email protected]"
      email_to = params['email_to']
      email_cc = params.get('email_cc')
      email_bcc = params.get('email_bcc')
      email_body = params['email_body']

      msg = MIMEMultipart('alternative')
      msg['To'] = email_to
      msg['CC'] = email_cc
      msg['Subject'] = email_subject
      mt_html = MIMEText(email_body, type_)
      msg.attach(mt_html)

      server = smtplib.SMTP('YOUR_MAIL_SERVER.DOMAIN.COM')
      server.set_debuglevel(1)
      toaddrs = [email_to] + [email_cc] + [email_bcc]
      server.sendmail(email_from, toaddrs, msg.as_string())
      server.quit()

# Calling the mailer functions
params = {
    'email_to': '[email protected]',
    'email_cc': '[email protected]',
    'email_bcc': '[email protected]',
    'email_subject': 'Test message from python library',
    'email_body': '<h1>Hello World</h1>'
}
for t in ['plain', 'html']:
    send_mail(params, t)

Git: which is the default configured remote for branch?

the command to get the effective push remote for the branch, e.g., master, is:

git config branch.master.pushRemote || git config remote.pushDefault || git config branch.master.remote

Here's why (from the "man git config" output):

branch.name.remote [...] tells git fetch and git push which remote to fetch from/push to [...] [for push] may be overridden with remote.pushDefault (for all branches) [and] for the current branch [..] further overridden by branch.name.pushRemote [...]

For some reason, "man git push" only tells about branch.name.remote (even though it has the least precedence of the three) + erroneously states that if it is not set, push defaults to origin - it does not, it's just that when you clone a repo, branch.name.remote is set to origin, but if you remove this setting, git push will fail, even though you still have the origin remote

Keep values selected after form submission

If you are using WordPress (as is the case with the OP), you can use the selected function.

<form method="get" action="">
  <select name="name">
    <option value="a" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'a' ); ?>>a</option>
    <option value="b" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'b' ); ?>>b</option>
  </select>
  <select name="location">
    <option value="x" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'x' ); ?>>x</option>
    <option value="y" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'y' ); ?>>y</option>
  </select>
  <input type="submit" value="Submit" class="submit" />
</form>

Create new user in MySQL and give it full access to one database

To create a user and grant all privileges on a database.

Log in to MySQL:

mysql -u root

Now create and grant

GRANT ALL PRIVILEGES ON dbTest.* To 'user'@'hostname' IDENTIFIED BY 'password';

Anonymous user (for local testing only)

Alternately, if you just want to grant full unrestricted access to a database (e.g. on your local machine for a test instance, you can grant access to the anonymous user, like so:

GRANT ALL PRIVILEGES ON dbTest.* To ''@'hostname'

Be aware

This is fine for junk data in development. Don't do this with anything you care about.

PHP max_input_vars

Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.

I can suggest not to extend the default value which is 1000 and extend the application functionality by serialising the request or send the request by blocks. Otherwise, you can extend this to configuration needed.

It definitely needs to set up in the php.ini