Programs & Examples On #Contract first

A Web Services development strategy where a WSDL is written first and code that provides the service is generated from the WSDL.

How do you get an iPhone's device name

For xamarin user, use this

UIKit.UIDevice.CurrentDevice.Name

Unit tests vs Functional tests

AFAIK, unit testing is NOT functional testing. Let me explain with a small example. You want to test if the login functionality of an email web app is working or not, just as a user would. For that, your functional tests should be like this.

1- existing email, wrong password -> login page should show error "wrong password"!
2- non-existing email, any password -> login page should show error "no such email".
3- existing email, right password -> user should be taken to his inbox page.
4- no @symbol in email, right password -> login page should say "errors in form, please fix them!" 

Should our functional tests check if we can login with invalid inputs ? Eg. Email has no @ symbol, username has more than one dot (only one dot is permitted), .com appears before @ etc. ? Generally, no ! That kind of testing goes into your unit tests.

You can check if invalid inputs are rejected inside unit tests as shown in the tests below.

class LoginInputsValidator
  method validate_inputs_values(email, password)
    1-If email is not like [email protected], then throw error.
    2-If email contains abusive words, then throw error.
    3-If password is less than 10 chars, throw error.

Notice that the functional test 4 is actually doing what unit test 1 is doing. Sometimes, functional tests can repeat some (not all) of the testing done by unit tests, for different reasons. In our example, we use functional test 4 to check if a particular error message appears on entering invalid input. We don't want to test if all bad inputs are rejected or not. That is the job of unit tests.

How to clear a chart from a canvas so that hover events cannot be triggered?

We can update the chart data in Chart.js V2.0 as follows:

var myChart = new Chart(ctx, data);
myChart.config.data = new_data;
myChart.update();

Where is the Microsoft.IdentityModel dll

Install Both of the below links

  1. Windows Identity Foundation

    Note: (For Vista and Windows Server 2008 >>> Windows6.0 and For Windows 7 and Windows Server 2008 R2, >>> Windows6.1. )

  2. Windows Identity Foundation SDK

    Note: Download the 3.5 version for Visual Studio 2008 and .NET 3.5, the 4.0 version for Visual Studio 2010 and .NET 4.0.

Then Only, You will able to get the assembly called Microsoft.IdentityModel

Reflection: How to Invoke Method with parameters

You have a bug right there

result = methodInfo.Invoke(methodInfo, parametersArray);

it should be

result = methodInfo.Invoke(classInstance, parametersArray);

How do I use vim registers?

A big source of confusion is the default register ". It is important to know the way it works. It is much better if the default register is avoided most of the times. The explanation from the Vim documentation:

Vim fills this register with text deleted with the "d", "c", "s", "x" commands
or copied with the yank "y" command, regardless of whether or not a specific
register was used (e.g.  "xdd).  This is like the unnamed register is pointing
to the last used register.

So the default register is actually a pointer to the last used register. When you delete, or yank something this register is going to point to other registers. You can test that by checking the registers. There is always another register that is exactly the same as the default register: the yank register ("0) , the first delete register("1) , small delete register("-) or any other register that was used to delete or yank.

The only exception is the black hole register. Vim doc says:

An exception is the '_' register: "_dd does not store the deleted text in any
register.

Usually you are much better off by using directly: "0, "- and "1-"9 default registers or named registers.

Function for 'does matrix contain value X?'

you can do:

A = randi(10, [3 4]);      %# a random matrix
any( A(:)==5 )             %# does A contain 5?

To do the above in a vectorized way, use:

any( bsxfun(@eq, A(:), [5 7 11] )

or as @woodchips suggests:

ismember([5 7 11], A)

What is the difference between i++ and ++i?

The way the operator works is that it gets incremented at the same time, but if it is before a variable, the expression will evaluate with the incremented/decremented variable:

int x = 0;   //x is 0
int y = ++x; //x is 1 and y is 1

If it is after the variable the current statement will get executed with the original variable, as if it had not yet been incremented/decremented:

int x = 0;   //x is 0
int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0

I agree with dcp in using pre-increment/decrement (++x) unless necessary. Really the only time I use the post-increment/decrement is in while loops or loops of that sort. These loops are the same:

while (x < 5)  //evaluates conditional statement
{
    //some code
    ++x;       //increments x
}

or

while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
{
    //some code
}

You can also do this while indexing arrays and such:

int i = 0;
int[] MyArray = new int[2];
MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
MyArray[i] = 5678;   //sets array at index 1 to '5678'
int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);

Etc, etc...

MISCONF Redis is configured to save RDB snapshots

# on redis 6.0.4 
# if show error 'MISCONF Redis is configured to save RDB snapshots'
# Because redis doesn't have permissions to create dump.rdb file
sudo redis/bin/redis-server 
sudo redis/bin/redis-cli

How do I log a Python error with debug information?

logger.exception will output a stack trace alongside the error message.

For example:

import logging
try:
    1/0
except ZeroDivisionError:
    logging.exception("message")

Output:

ERROR:root:message
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

@Paulo Cheque notes, "be aware that in Python 3 you must call the logging.exception method just inside the except part. If you call this method in an arbitrary place you may get a bizarre exception. The docs alert about that."

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Normally when an optimization algorithm does not converge, it is usually because the problem is not well-conditioned, perhaps due to a poor scaling of the decision variables. There are a few things you can try.

  1. Normalize your training data so that the problem hopefully becomes more well conditioned, which in turn can speed up convergence. One possibility is to scale your data to 0 mean, unit standard deviation using Scikit-Learn's StandardScaler for an example. Note that you have to apply the StandardScaler fitted on the training data to the test data.
  2. Related to 1), make sure the other arguments such as regularization weight, C, is set appropriately.
  3. Set max_iter to a larger value. The default is 1000.
  4. Set dual = True if number of features > number of examples and vice versa. This solves the SVM optimization problem using the dual formulation. Thanks @Nino van Hooff for pointing this out, and @JamesKo for spotting my mistake.
  5. Use a different solver, for e.g., the L-BFGS solver if you are using Logistic Regression. See @5ervant's answer.

Note: One should not ignore this warning.

This warning came about because

  1. Solving the linear SVM is just solving a quadratic optimization problem. The solver is typically an iterative algorithm that keeps a running estimate of the solution (i.e., the weight and bias for the SVM). It stops running when the solution corresponds to an objective value that is optimal for this convex optimization problem, or when it hits the maximum number of iterations set.

  2. If the algorithm does not converge, then the current estimate of the SVM's parameters are not guaranteed to be any good, hence the predictions can also be complete garbage.

Edit

In addition, consider the comment by @Nino van Hooff and @5ervant to use the dual formulation of the SVM. This is especially important if the number of features you have, D, is more than the number of training examples N. This is what the dual formulation of the SVM is particular designed for and helps with the conditioning of the optimization problem. Credit to @5ervant for noticing and pointing this out.

Furthermore, @5ervant also pointed out the possibility of changing the solver, in particular the use of the L-BFGS solver. Credit to him (i.e., upvote his answer, not mine).

I would like to provide a quick rough explanation for those who are interested (I am :)) why this matters in this case. Second-order methods, and in particular approximate second-order method like the L-BFGS solver, will help with ill-conditioned problems because it is approximating the Hessian at each iteration and using it to scale the gradient direction. This allows it to get better convergence rate but possibly at a higher compute cost per iteration. That is, it takes fewer iterations to finish but each iteration will be slower than a typical first-order method like gradient-descent or its variants.

For e.g., a typical first-order method might update the solution at each iteration like

x(k + 1) = x(k) - alpha(k) * gradient(f(x(k)))

where alpha(k), the step size at iteration k, depends on the particular choice of algorithm or learning rate schedule.

A second order method, for e.g., Newton, will have an update equation

x(k + 1) = x(k) - alpha(k) * Hessian(x(k))^(-1) * gradient(f(x(k)))

That is, it uses the information of the local curvature encoded in the Hessian to scale the gradient accordingly. If the problem is ill-conditioned, the gradient will be pointing in less than ideal directions and the inverse Hessian scaling will help correct this.

In particular, L-BFGS mentioned in @5ervant's answer is a way to approximate the inverse of the Hessian as computing it can be an expensive operation.

However, second-order methods might converge much faster (i.e., requires fewer iterations) than first-order methods like the usual gradient-descent based solvers, which as you guys know by now sometimes fail to even converge. This can compensate for the time spent at each iteration.

In summary, if you have a well-conditioned problem, or if you can make it well-conditioned through other means such as using regularization and/or feature scaling and/or making sure you have more examples than features, you probably don't have to use a second-order method. But these days with many models optimizing non-convex problems (e.g., those in DL models), second order methods such as L-BFGS methods plays a different role there and there are evidence to suggest they can sometimes find better solutions compared to first-order methods. But that is another story.

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

I believe that npm install should not run in a production environment. There are several things that can go wrong - npm outage, download of newer dependencies (shrinkwrap seems to have solved this) are two of them.

On the other hand, folder node_modules should not be committed to Git. Apart from their big size, commits including them can become distracting.

The best solutions would be this: npm install should run in a CI environment that is similar to the production environment. All tests will run and a zipped release file will be created that will include all dependencies.

Axios handling errors

if u wanna use async await try

export const post = async ( link,data ) => {
const option = {
    method: 'post',
    url: `${URL}${link}`,
    validateStatus: function (status) {
        return status >= 200 && status < 300; // default
      },
    data
};

try {
    const response = await axios(option);
} catch (error) {
    const { response } = error;
    const { request, ...errorObject } = response; // take everything but 'request'
    console.log(errorObject);
}

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

I used a proxy url to solve a similar problem when I want to post data to my apache solr hosted in another server. (This may not be the perfect answer but it solves my problem.)

Follow this URL: Using Mode-Rewrite for proxying, I add this line to my httpd.conf:

 RewriteRule ^solr/(.*)$ http://ip:8983/solr$1 [P]

Therefore, I can just post data to /solr instead of posting data to http://ip:8983/solr/*. Then it will be posting data in the same origin.

How to search JSON data in MySQL?

  1. Storing JSON in database violates the first normal form.

    The best thing you can do is to normalize and store features in another table. Then you will be able to use a much better looking and performing query with joins. Your JSON even resembles the table.

  2. Mysql 5.7 has builtin JSON functionality:
    http://mysqlserverteam.com/mysql-5-7-lab-release-json-functions-part-2-querying-json-data/

  3. Correct pattern is:

    WHERE  `attribs_json` REGEXP '"1":{"value":[^}]*"3"[^}]*}'
    

    [^}] will match any character except }

Replace Multiple String Elements in C#

Quicker - no. More effective - yes, if you will use the StringBuilder class. With your implementation each operation generates a copy of a string which under circumstances may impair performance. Strings are immutable objects so each operation just returns a modified copy.

If you expect this method to be actively called on multiple Strings of significant length, it might be better to "migrate" its implementation onto the StringBuilder class. With it any modification is performed directly on that instance, so you spare unnecessary copy operations.

public static class StringExtention
{
    public static string clean(this string s)
    {
        StringBuilder sb = new StringBuilder (s);

        sb.Replace("&", "and");
        sb.Replace(",", "");
        sb.Replace("  ", " ");
        sb.Replace(" ", "-");
        sb.Replace("'", "");
        sb.Replace(".", "");
        sb.Replace("eacute;", "é");

        return sb.ToString().ToLower();
    }
}

Android appcompat v7:23

Latest published version of the Support Library is 24.1.1, So you can use it like this,

compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'

Same as for other support components.

You can see the revisions here,
https://developer.android.com/topic/libraries/support-library/revisions.html

What is the best (idiomatic) way to check the type of a Python variable?

I've been using a different approach:

from inspect import getmro
if (type([]) in getmro(obj.__class__)):
    # This is a list, or a subclass of...
elif (type{}) in getmro(obj.__class__)):
    # This one is a dict, or ...

I can't remember why I used this instead of isinstance, though...

How to count the number of letters in a string without the spaces?

n=str(input("Enter word: ").replace(" ",""))

ans=0
for i in n:
    ans=ans+1
print(ans)    

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

Using Font Awesome icon for bullet points, with a single list item element

@Tama, you may want to check this answer: Using Font Awesome icons as bullets

Basically you can accomplish this by using only CSS without the need for the extra markup as suggested by FontAwesome and the other answers here.

In other words, you can accomplish what you need using the same basic markup you mentioned in your initial post:

<ul>
  <li>...</li>
  <li>...</li>
  <li>...</li>
</ul>

Thanks.

Zip lists in Python

In Python 2.7 this might have worked fine:

>>> a = b = c = range(20)
>>> zip(a, b, c)

But in Python 3.4 it should be (otherwise, the result will be something like <zip object at 0x00000256124E7DC8>):

>>> a = b = c = range(20)
>>> list(zip(a, b, c))

.htaccess redirect http to https

Add this code at the end of your .htaccess file

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });

Make copy of an array

You can try using System.arraycopy()

int[] src  = new int[]{1,2,3,4,5};
int[] dest = new int[5];

System.arraycopy( src, 0, dest, 0, src.length );

But, probably better to use clone() in most cases:

int[] src = ...
int[] dest = src.clone();

JavaScript URL Decode function

decodeURIComponent(mystring);

you can get passed parameters by using this bit of code:

//parse URL to get values: var i = getUrlVars()["i"];
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Or this one-liner to get the parameters:

location.search.split("your_parameter=")[1]

Comparing two byte arrays in .NET

The short answer is this:

    public bool Compare(byte[] b1, byte[] b2)
    {
        return Encoding.ASCII.GetString(b1) == Encoding.ASCII.GetString(b2);
    }

In such a way you can use the optimized .NET string compare to make a byte array compare without the need to write unsafe code. This is how it is done in the background:

private unsafe static bool EqualsHelper(String strA, String strB)
{
    Contract.Requires(strA != null);
    Contract.Requires(strB != null);
    Contract.Requires(strA.Length == strB.Length);

    int length = strA.Length;

    fixed (char* ap = &strA.m_firstChar) fixed (char* bp = &strB.m_firstChar)
    {
        char* a = ap;
        char* b = bp;

        // Unroll the loop

        #if AMD64
            // For the AMD64 bit platform we unroll by 12 and
            // check three qwords at a time. This is less code
            // than the 32 bit case and is shorter
            // pathlength.

            while (length >= 12)
            {
                if (*(long*)a     != *(long*)b)     return false;
                if (*(long*)(a+4) != *(long*)(b+4)) return false;
                if (*(long*)(a+8) != *(long*)(b+8)) return false;
                a += 12; b += 12; length -= 12;
            }
       #else
           while (length >= 10)
           {
               if (*(int*)a != *(int*)b) return false;
               if (*(int*)(a+2) != *(int*)(b+2)) return false;
               if (*(int*)(a+4) != *(int*)(b+4)) return false;
               if (*(int*)(a+6) != *(int*)(b+6)) return false;
               if (*(int*)(a+8) != *(int*)(b+8)) return false;
               a += 10; b += 10; length -= 10;
           }
       #endif

        // This depends on the fact that the String objects are
        // always zero terminated and that the terminating zero is not included
        // in the length. For odd string sizes, the last compare will include
        // the zero terminator.
        while (length > 0)
        {
            if (*(int*)a != *(int*)b) break;
            a += 2; b += 2; length -= 2;
        }

        return (length <= 0);
    }
}

Phone number formatting an EditText in Android

I've recently done a similar formatting like 1 (XXX) XXX-XXXX for Android EditText. Please find the code below. Just use the TextWatcher sub-class as the text changed listener : ....

UsPhoneNumberFormatter addLineNumberFormatter = new UsPhoneNumberFormatter(
            new WeakReference<EditText>(mYourEditText));
    mYourEditText.addTextChangedListener(addLineNumberFormatter);

...

private class UsPhoneNumberFormatter implements TextWatcher {
    //This TextWatcher sub-class formats entered numbers as 1 (123) 456-7890
    private boolean mFormatting; // this is a flag which prevents the
                                    // stack(onTextChanged)
    private boolean clearFlag;
    private int mLastStartLocation;
    private String mLastBeforeText;
    private WeakReference<EditText> mWeakEditText;

    public UsPhoneNumberFormatter(WeakReference<EditText> weakEditText) {
        this.mWeakEditText = weakEditText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        if (after == 0 && s.toString().equals("1 ")) {
            clearFlag = true;
        }
        mLastStartLocation = start;
        mLastBeforeText = s.toString();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO: Do nothing
    }

    @Override
    public void afterTextChanged(Editable s) {
        // Make sure to ignore calls to afterTextChanged caused by the work
        // done below
        if (!mFormatting) {
            mFormatting = true;
            int curPos = mLastStartLocation;
            String beforeValue = mLastBeforeText;
            String currentValue = s.toString();
            String formattedValue = formatUsNumber(s);
            if (currentValue.length() > beforeValue.length()) {
                int setCusorPos = formattedValue.length()
                        - (beforeValue.length() - curPos);
                mWeakEditText.get().setSelection(setCusorPos < 0 ? 0 : setCusorPos);
            } else {
                int setCusorPos = formattedValue.length()
                        - (currentValue.length() - curPos);
                if(setCusorPos > 0 && !Character.isDigit(formattedValue.charAt(setCusorPos -1))){
                    setCusorPos--;
                }
                mWeakEditText.get().setSelection(setCusorPos < 0 ? 0 : setCusorPos);
            }
            mFormatting = false;
        }
    }

    private String formatUsNumber(Editable text) {
        StringBuilder formattedString = new StringBuilder();
        // Remove everything except digits
        int p = 0;
        while (p < text.length()) {
            char ch = text.charAt(p);
            if (!Character.isDigit(ch)) {
                text.delete(p, p + 1);
            } else {
                p++;
            }
        }
        // Now only digits are remaining
        String allDigitString = text.toString();

        int totalDigitCount = allDigitString.length();

        if (totalDigitCount == 0
                || (totalDigitCount > 10 && !allDigitString.startsWith("1"))
                || totalDigitCount > 11) {
            // May be the total length of input length is greater than the
            // expected value so we'll remove all formatting
            text.clear();
            text.append(allDigitString);
            return allDigitString;
        }
        int alreadyPlacedDigitCount = 0;
        // Only '1' is remaining and user pressed backspace and so we clear
        // the edit text.
        if (allDigitString.equals("1") && clearFlag) {
            text.clear();
            clearFlag = false;
            return "";
        }
        if (allDigitString.startsWith("1")) {
            formattedString.append("1 ");
            alreadyPlacedDigitCount++;
        }
        // The first 3 numbers beyond '1' must be enclosed in brackets "()"
        if (totalDigitCount - alreadyPlacedDigitCount > 3) {
            formattedString.append("("
                    + allDigitString.substring(alreadyPlacedDigitCount,
                            alreadyPlacedDigitCount + 3) + ") ");
            alreadyPlacedDigitCount += 3;
        }
        // There must be a '-' inserted after the next 3 numbers
        if (totalDigitCount - alreadyPlacedDigitCount > 3) {
            formattedString.append(allDigitString.substring(
                    alreadyPlacedDigitCount, alreadyPlacedDigitCount + 3)
                    + "-");
            alreadyPlacedDigitCount += 3;
        }
        // All the required formatting is done so we'll just copy the
        // remaining digits.
        if (totalDigitCount > alreadyPlacedDigitCount) {
            formattedString.append(allDigitString
                    .substring(alreadyPlacedDigitCount));
        }

        text.clear();
        text.append(formattedString.toString());
        return formattedString.toString();
    }

}

Eloquent ORM laravel 5 Get Array of ids

read about the lists() method

$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()

How to install a certificate in Xcode (preparing for app store submission)

These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)

a) Part on the developers' website:

Sign in into: https://developer.apple.com/

Member Center

Certificates, Identifiers & Profiles

Certificates>All

Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.

b) XCode part:

After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.

How to open a new file in vim in a new window

Check out gVim. You can launch that in its own window.

gVim makes it really easy to manage multiple open buffers graphically.

You can also do the usual :e to open a new file, CTRL+^ to toggle between buffers, etc...

Another cool feature lets you open a popup window that lists all the buffers you've worked on.

This allows you to switch between open buffers with a single click.

To do this, click on the Buffers menu at the top and click the dotted line with the scissors.

enter image description here

Otherwise you can just open a new tab from your terminal session and launch vi from there.

You can usually open a new tab from terminal with CTRL+T or CTRL+ALT+T

Once vi is launched, it's easy to open new files and switch between them.

How do you create a REST client for Java?

As I mentioned in this thread I tend to use Jersey which implements JAX-RS and comes with a nice REST client. The nice thing is if you implement your RESTful resources using JAX-RS then the Jersey client can reuse the entity providers such as for JAXB/XML/JSON/Atom and so forth - so you can reuse the same objects on the server side as you use on the client side unit test.

For example here is a unit test case from the Apache Camel project which looks up XML payloads from a RESTful resource (using the JAXB object Endpoints). The resource(uri) method is defined in this base class which just uses the Jersey client API.

e.g.

    clientConfig = new DefaultClientConfig();
    client = Client.create(clientConfig);

    resource = client.resource("http://localhost:8080");
    // lets get the XML as a String
    String text = resource("foo").accept("application/xml").get(String.class);        

BTW I hope that future version of JAX-RS add a nice client side API along the lines of the one in Jersey

How to remove item from a python list in a loop?

This stems from the fact that on deletion, the iteration skips one element as it semms only to work on the index.

Workaround could be:

x = ["ok", "jj", "uy", "poooo", "fren"]
for item in x[:]: # make a copy of x
    if len(item) != 2:
        print "length of %s is: %s" %(item, len(item))
        x.remove(item)

Replace \n with actual new line in Sublime Text

On Windows, Sublime text,

You press Ctrl + H to replace \n by a new line created by Ctrl + Enter.

Replace : \n

By : (press Ctrl + Enter)

How to concatenate string and int in C?

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

matplotlib savefig in jpeg format

To clarify and update @neo useful answer and the original question. A clean solution consists of installing Pillow, which is an updated version of the Python Imaging Library (PIL). This is done using

pip install pillow

Once Pillow is installed, the standard Matplotlib commands

import matplotlib.pyplot as plt

plt.plot([1, 2])
plt.savefig('image.jpg')

will save the figure into a JPEG file and will not generate a ValueError any more.

Contrary to @amillerrhodes answer, as of Matplotlib 3.1, JPEG files are still not supported. If I remove the Pillow package I still receive a ValueError about an unsupported file type.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Try the following

  1. download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.

  2. Unzip the file and Run intelhaxm-android.exe.

  3. Run silent_install.bat.

In my computer Win10 x64 - VS2015 it worked

Attach Authorization header for all axios requests

The best solution to me is to create a client service that you'll instantiate with your token an use it to wrap axios.

import axios from 'axios';

const client = (token = null) => {
    const defaultOptions = {
        headers: {
            Authorization: token ? `Token ${token}` : '',
        },
    };

    return {
        get: (url, options = {}) => axios.get(url, { ...defaultOptions, ...options }),
        post: (url, data, options = {}) => axios.post(url, data, { ...defaultOptions, ...options }),
        put: (url, data, options = {}) => axios.put(url, data, { ...defaultOptions, ...options }),
        delete: (url, options = {}) => axios.delete(url, { ...defaultOptions, ...options }),
    };
};

const request = client('MY SECRET TOKEN');

request.get(PAGES_URL);

In this client, you can also retrieve the token from the localStorage / cookie, as you want.

Hide Show content-list with only CSS, no javascript used

This is going to blow your mind: Hidden radio buttons.

_x000D_
_x000D_
input#show, input#hide {_x000D_
    display:none;_x000D_
}_x000D_
_x000D_
span#content {_x000D_
    display:none;_x000D_
}_x000D_
input#show:checked ~ span#content {_x000D_
  display:block;_x000D_
}_x000D_
_x000D_
input#hide:checked ~ span#content {_x000D_
    display:none;_x000D_
}
_x000D_
<label for="show">_x000D_
    <span>[Show]</span>_x000D_
</label>_x000D_
<input type=radio id="show" name="group">_x000D_
<label for="hide">_x000D_
    <span>[Hide]</span> _x000D_
</label>    _x000D_
<input type=radio id="hide" name="group">_x000D_
<span id="content">Content</span>
_x000D_
_x000D_
_x000D_

MySQL skip first 10 results

select * from table where id not in (select id from table limit 10)

where id be the key in your table.

jQuery .attr("disabled", "disabled") not working in Chrome

Here:
http://jsbin.com/urize4/edit

Live Preview
http://jsbin.com/urize4/

You should use "readonly" instead like:

$("input[type='text']").attr("readonly", "true");

How to export a MySQL database to JSON?

Another possibility is using the MySQL Workbench.

There is a JSON export option at the object browser context menu and at the result grid menu.

More information on MySQL documentation: Data export and import.

Difference between setTimeout with and without quotes and parentheses

Using setInterval or setTimeout

You should pass a reference to a function as the first argument for setTimeout or setInterval. This reference may be in the form of:

  • An anonymous function

    setTimeout(function(){/* Look mah! No name! */},2000);
    
  • A name of an existing function

    function foo(){...}
    
    setTimeout(foo, 2000);
    
  • A variable that points to an existing function

    var foo = function(){...};
    
    setTimeout(foo, 2000);
    

    Do note that I set "variable in a function" separately from "function name". It's not apparent that variables and function names occupy the same namespace and can clobber each other.

Passing arguments

To call a function and pass parameters, you can call the function inside the callback assigned to the timer:

setTimeout(function(){
  foo(arg1, arg2, ...argN);
}, 1000);

There is another method to pass in arguments into the handler, however it's not cross-browser compatible.

setTimeout(foo, 2000, arg1, arg2, ...argN);

Callback context

By default, the context of the callback (the value of this inside the function called by the timer) when executed is the global object window. Should you want to change it, use bind.

setTimeout(function(){
  this === YOUR_CONTEXT; // true
}.bind(YOUR_CONTEXT), 2000);

Security

Although it's possible, you should not pass a string to setTimeout or setInterval. Passing a string makes setTimeout() or setInterval() use a functionality similar to eval() that executes strings as scripts, making arbitrary and potentially harmful script execution possible.

How do I show my global Git configuration?

One important thing about git config:

git config has --local, --global and --system levels and corresponding files.

So you may use git config --local, git config --global and git config --system.

By default, git config will write to a local level if no configuration option is passed. Local configuration values are stored in a file that can be found in the repository's .git directory: .git/config

Global level configuration is user-specific, meaning it is applied to an operating system user. Global configuration values are stored in a file that is located in a user's home directory. ~/.gitconfig on Unix systems and C:\Users\<username>\.gitconfig on Windows.

System-level configuration is applied across an entire machine. This covers all users on an operating system and all repositories. The system level configuration file lives in a gitconfig file off the system root path. $(prefix)/etc/gitconfig on Linux systems. On Windows this file can be found in C:\ProgramData\Git\config.

So your option is to find that global .gitconfig file and edit it.

Or you can use git config --global --list.

This is exactly the line what you need.

Enter image description here

Find number of decimal places in decimal value regardless of culture

I'd probably use the solution in @fixagon's answer.

However, while the Decimal struct doesn't have a method to get the number of decimals, you could call Decimal.GetBits to extract the binary representation, then use the integer value and scale to compute the number of decimals.

This would probably be faster than formatting as a string, though you'd have to be processing an awful lot of decimals to notice the difference.

I'll leave the implementation as an exercise.

jQuery - checkbox enable/disable

<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="chk9[120]" class="chkGroup">
<input type="checkbox" name="chk9[140]" class="chkGroup">
<input type="checkbox" name="chk9[150]" class="chkGroup">
</form>

$("#chkAll").click(function() {
   $(".chkGroup").attr("checked", this.checked);
});

With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:

$(".chkGroup").click(function() {
  $("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;
});

How do I get the time of day in javascript/Node.js?

If you only want the time string you can use this expression (with a simple RegEx):

new Date().toISOString().match(/(\d{2}:){2}\d{2}/)[0]
// "23:00:59"

Pytorch reshape tensor dimension

This question has been thoroughly answered already, but I want to add for the less experienced python developers that you might find the * operator helpful in conjunction with view().

For example if you have a particular tensor size that you want a different tensor of data to conform to, you might try:

img = Variable(tensor.randn(20,30,3)) # tensor with goal shape
flat_size = 20*30*3
X = Variable(tensor.randn(50, flat_size)) # data tensor

X = X.view(-1, *img.size()) # sweet maneuver
print(X.size()) # size is (50, 20, 30, 3)

This works with numpy shape too:

img = np.random.randn(20,30,3)
flat_size = 20*30*3
X = Variable(tensor.randn(50, flat_size))
X = X.view(-1, *img.shape)
print(X.size()) # size is (50, 20, 30, 3)

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something');
$('.toggle img').attr('src', 'something.jpg');

Use jQuery.data and jQuery.attr.

I'm showing them to you separately for the sake of understanding.

How to disable phone number linking in Mobile Safari?

You could try encoding them as HTML entities:

&#48; = 0
&#57; = 9

Go To Definition: "Cannot navigate to the symbol under the caret."

The following worked out for me like a charm:

  1. I checked the warnings that showed up when I built the Project
  2. Some of them mentioned something about assembly version conflict. Visual studio suggested that I clicked on the warning and hit Enter. A popup window offered to automatically fix the issue and so I did.
  3. Problem solved!

Difference between no-cache and must-revalidate

max-age=0, must-revalidate and no-cache aren't exactly identical. With must-revalidate, if the server doesn't respond to a revalidation request, the browser/proxy is supposed to return a 504 error. With no-cache, it would just show the cached content, which would be probably preferred by the user (better to have something stale than nothing at all). This is why must-revalidate is intended for critical transactions only.

C# Change A Button's Background Color

// WPF

// Defined Color
button1.Background = Brushes.Green;

// Color from RGB
button2.Background = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));

The name 'model' does not exist in current context in MVC3

If your views are in a class library assembly, which is useful for reuse of shared views among projects, then just doing what Adam suggests might not be enough. I still had issues even with that.

Try this in your web.config in the root of your project:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</configuration>

And this in the web.config in your views folder:

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

This worked for me. I now have intellisense and no compile errors on my views in a non-MVC project that I can then reference from multiple MVC websites.

Can a constructor in Java be private?

According to me we can declare constructor as a private and also we can get the instance of that class in the subclass by using static method in class in which we declare constructor and then return class object. we class this method from to the sub class by using classname.method name bcz it is static method and the we will get the instance of class in which we declare const.

How to set all elements of an array to zero or any same value?

If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.

// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};

// file scope
int arr[4];
// equivalent to
int arr[4] = {0};

Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.

// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};

Finding the average of a list

suppose that

x = [
    [-5.01,-5.43,1.08,0.86,-2.67,4.94,-2.51,-2.25,5.56,1.03],
    [-8.12,-3.48,-5.52,-3.78,0.63,3.29,2.09,-2.13,2.86,-3.33],
    [-3.68,-3.54,1.66,-4.11,7.39,2.08,-2.59,-6.94,-2.26,4.33]
]

you can notice that x has dimension 3*10 if you need to get the mean to each row you can type this

theMean = np.mean(x1,axis=1)

don't forget to import numpy as np

What's the best free C++ profiler for Windows?

I use AQTime, it is one of the best profiling tools I've ever used. It isn't free but you can get a 30 day trial, so if you plan on a optimizing and profiling only one project and 30 days are enough for you then I would recommend using this application. (http://www.automatedqa.com/downloads/aqtime/index.asp)

Detect iPad users using jQuery?

iPad Detection

You should be able to detect an iPad user by taking a look at the userAgent property:

var is_iPad = navigator.userAgent.match(/iPad/i) != null;

iPhone/iPod Detection

Similarly, the platform property to check for devices like iPhones or iPods:

function is_iPhone_or_iPod(){
     return navigator.platform.match(/i(Phone|Pod))/i)
}

Notes

While it works, you should generally avoid performing browser-specific detection as it can often be unreliable (and can be spoofed). It's preferred to use actual feature-detection in most cases, which can be done through a library like Modernizr.

As pointed out in Brennen's answer, issues can arise when performing this detection within the Facebook app. Please see his answer for handling this scenario.

Related Resources

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

You can do it in this way

// xyz.h
#ifndef _XYZ_
#define _XYZ_

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

#include "xyz.cpp"
#endif

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

#endif

This has been discussed in Daniweb

Also in FAQ but using C++ export keyword.

Angular2 disable button

 <button [disabled]="this.model.IsConnected() == false"
              [ngClass]="setStyles()"
              class="action-button action-button-selected button-send"
              (click)= "this.Send()">
          SEND
        </button>

.ts code

setStyles() 
{
    let styles = {

    'action-button-disabled': this.model.IsConnected() == false  
  };
  return styles;
}

SyntaxError: non-default argument follows default argument

Let me clarify two points here :

  • Firstly non-default argument should not follow the default argument, it means you can't define (a = 'b',c) in function. The correct order of defining parameter in function are :
  • positional parameter or non-default parameter i.e (a,b,c)
  • keyword parameter or default parameter i.e (a = 'b',r= 'j')
  • keyword-only parameter i.e (*args)
  • var-keyword parameter i.e (**kwargs)

def example(a, b, c=None, r="w" , d=[], *ae, **ab):

(a,b) are positional parameter

(c=none) is optional parameter

(r="w") is keyword parameter

(d=[]) is list parameter

(*ae) is keyword-only

(*ab) is var-keyword parameter

so first re-arrange your parameters

  • now the second thing is you have to define len1 when you are doing hgt=len1 the len1 argument is not defined when default values are saved, Python computes and saves default values when you define the function len1 is not defined, does not exist when this happens (it exists only when the function is executed)

so second remove this "len1 = hgt" it's not allowed in python.

keep in mind the difference between argument and parameters.

Convert array to string in NodeJS

toString is a method, so you should add parenthesis () to make the function call.

> a = [1,2,3]
[ 1, 2, 3 ]
> a.toString()
'1,2,3'

Besides, if you want to use strings as keys, then you should consider using a Object instead of Array, and use JSON.stringify to return a string.

> var aa = {}
> aa['a'] = 'aaa'
> JSON.stringify(aa)
'{"a":"aaa","b":"bbb"}'

Google drive limit number of download

Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:

The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB
POP and IMAP bandwidth limits

Limit                Per day
Download via IMAP    2500 MB
Download via POP     1250 MB
Upload via IMAP      500 MB

check out this link

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

For me it was a browser issue, since my requests were working fine in Postman.

Turns out that for some reason, Firefox and Chrome blocked requests going to port 6000, once I changed the ASP.NET API port to 4000, the error changed to a known CORS error which I could fix.

Chrome at least showed me ERR_UNSAFE_PORT which gave me a clue about what could be wrong.

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

I solved the Access-Control-Allow-Origin error modifying the dataType parameter to dataType:'jsonp' and adding a crossDomain:true

$.ajax({

    url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
    data: myData,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader
});

How disable / remove android activity label and label bar?

IF you are using Android Studio 3+ This will work: android:theme="@style/Theme.AppCompat.NoActionBar"

@android:style/Theme.NoTitleBar will not support in new API and force you app close.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

SQL Server - copy stored procedures from one db to another

Another option is to transfer stored procedures using SQL Server Integration Services (SSIS). There is a task called Transfer SQL Server Objects Task. You can use the task to transfer the following items:

  • Tables
  • Views
  • Stored Procedures
  • User-Defined Functions
  • Defaults
  • User-Defined Data Types
  • Partition Functions
  • Partition Schemes
  • Schemas
  • Assemblies
  • User-Defined Aggregates
  • User-Defined Types
  • XML Schema Collection

It's a graphical tutorial for Transfer SQL Server Objects Task.

How to convert a 3D point into 2D perspective projection?

I think this will probably answer your question. Here's what I wrote there:

Here's a very general answer. Say the camera's at (Xc, Yc, Zc) and the point you want to project is P = (X, Y, Z). The distance from the camera to the 2D plane onto which you are projecting is F (so the equation of the plane is Z-Zc=F). The 2D coordinates of P projected onto the plane are (X', Y').

Then, very simply:

X' = ((X - Xc) * (F/Z)) + Xc

Y' = ((Y - Yc) * (F/Z)) + Yc

If your camera is the origin, then this simplifies to:

X' = X * (F/Z)

Y' = Y * (F/Z)

Transfer files to/from session I'm logged in with PuTTY

  • Click on start menu.
  • Click run
  • In the open box, type cmd then click ok
  • At the command prompt, enter:

    c:>pscp source_file_name userid@server_name:/path/destination_file_name.

For example:

c:>pscp november2012 [email protected]:/mydata/november2012.

  • When promted, enter your password for server.

Enjoy

UITableView, Separator color where to set?

If you just want to set the same color to every separator and it is opaque you can use:

 self.tableView.separatorColor = UIColor.redColor()

If you want to use different colors for the separators or clear the separator color or use a color with alpha.

BE CAREFUL: You have to know that there is a backgroundView in the separator that has a default color.

To change it you can use this functions:

    func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if(view.isKindOfClass(UITableViewHeaderFooterView)){
            var headerView = view as! UITableViewHeaderFooterView;
            headerView.backgroundView?.backgroundColor = myColor

           //Other colors you can change here
           // headerView.backgroundColor = myColor
           // headerView.contentView.backgroundColor = myColor
        }
    }

    func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
        if(view.isKindOfClass(UITableViewHeaderFooterView)){
            var footerView = view as! UITableViewHeaderFooterView;
            footerView.backgroundView?.backgroundColor = myColor
           //Other colors you can change here
           //footerView.backgroundColor = myColor
           //footerView.contentView.backgroundColor = myColor
        }
    }

Hope it helps!

Angular ForEach in Angular4/Typescript?

you can try typescript's For :

selectChildren(data , $event){
   let parentChecked : boolean = data.checked;
   for(let o of this.hierarchicalData){
      for(let child of o){
         child.checked = parentChecked;
      }
   }
}

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

Open Git Bash and run the command if you want to completely disable SSL verification.

git config --global http.sslVerify false

Note: This solution may open you to attacks like man-in-the-middle attacks. Therefore turn on verification again as soon as possible:

git config --global http.sslVerify true

Replace input type=file by an image

This works really well for me:

_x000D_
_x000D_
.image-upload>input {_x000D_
  display: none;_x000D_
}
_x000D_
<div class="image-upload">_x000D_
  <label for="file-input">_x000D_
    <img src="https://icon-library.net/images/upload-photo-icon/upload-photo-icon-21.jpg"/>_x000D_
  </label>_x000D_
_x000D_
  <input id="file-input" type="file" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Basically the for attribute of the label makes it so that clicking the label is the same as clicking the specified input.

Also, the display property set to none makes it so that the file input isn't rendered at all, hiding it nice and clean.

Tested in Chrome but according to the web should work on all major browsers. :)

EDIT: Added JSFiddle here: https://jsfiddle.net/c5s42vdz/

Deny access to one specific folder in .htaccess

You can create a .htaccess file for the folder, wich should have denied access with

Deny from  all

or you can redirect to a custom 404 page

Redirect /includes/ 404.html

Android Failed to install HelloWorld.apk on device (null) Error

go setting- security verify apps if checked, change to unchecked status, then change to checked status

How to uninstall jupyter

When you $ pip install jupyter several dependencies are installed. The best way to uninstall it completely is by running:

  1. $ pip install pip-autoremove
  2. $ pip-autoremove jupyter -y

Kindly refer to this related question.

pip-autoremove removes a package and its unused dependencies. Here are the docs.

How to prevent http file caching in Apache httpd (MAMP)

Based on the example here: http://drupal.org/node/550488

The following will probably work in .htaccess

 <IfModule mod_expires.c>
   # Enable expirations.
   ExpiresActive On

   # Cache all files for 2 weeks after access (A).
   ExpiresDefault A1209600

  <FilesMatch (\.js|\.html)$>
     ExpiresActive Off
  </FilesMatch>
 </IfModule>

What does "./" (dot slash) refer to in terms of an HTML file path location?

For example css files are in folder named CSS and html files are in folder HTML, and both these are in folder named XYZ means we refer css files in html as

<link rel="stylesheet" type="text/css" href="./../CSS/style.css" />

Here .. moves up to HTML
and . refers to the current directory XYZ

---by this logic you would just reference as:

<link rel="stylesheet" type="text/css" href="CSS/style.css" />

Rails Active Record find(:all, :order => ) issue

The problem is that date is a reserved sqlite3 keyword. I had a similar problem with time, also a reserved keyword, which worked fine in PostgreSQL, but not in sqlite3. The solution is renaming the column.

See this: Sqlite3 activerecord :order => "time DESC" doesn't sort

correct way to use super (argument passing)

If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

class First(object):
    def __init__(self, *args, **kwargs):
        self.first_arg = kwargs.pop('first_arg')
        super(First, self).__init__(*args, **kwargs)

class Second(First):
    def __init__(self, *args, **kwargs):
        self.second_arg = kwargs.pop('second_arg')
        super(Second, self).__init__(*args, **kwargs)

class Third(Second):
    def __init__(self, *args, **kwargs):
        self.third_arg = kwargs.pop('third_arg')
        super(Third, self).__init__(*args, **kwargs)

This is the simplest way to solve those kind of problems.

third = Third(first_arg=1, second_arg=2, third_arg=3)

How to enable SOAP on CentOS

After hours of searching I think my problem was that command yum install php-soap installs the latest version of soap for the latest php version.

My php version was 7.027, but latest php version is 7.2 so I had to search for the right soap version and finaly found it HERE!

yum install rh-php70-php-soap

Now php -m | grep -i soap works, Output: soap

Do not forget to restart httpd service.

Java ElasticSearch None of the configured nodes are available

I had the same problem. my problem was that the version of the dependency had conflict with the elasticsearch version. check the version in ip:9200 and use the dependency version that match it

Asp.net Validation of viewstate MAC failed

I had this same issue and it was due to a Gridview (generated from a vb code) on the page which had sorting enabled. Disabling Sort fixed my issue. I do not have this problem with the gridviews created using a SQLdatasource.

How to resize a VirtualBox vmdk file

Throw it away and start again. Ignore all these answers - don't waste your time.

Unix shell script find out which directory the script file resides?

INTRODUCTION

This answer corrects the very broken but shockingly top voted answer of this thread (written by TheMarko):

#!/usr/bin/env bash

BASEDIR=$(dirname "$0")
echo "$BASEDIR"

WHY DOES USING dirname "$0" ON IT'S OWN NOT WORK?

dirname $0 will only work if user launches script in a very specific way. I was able to find several situations where this answer fails and crashes the script.

First of all, let's understand how this answer works. He's getting the script directory by doing

dirname "$0"

$0 represents the first part of the command calling the script (it's basically the inputted command without the arguments:

/some/path/./script argument1 argument2

$0="/some/path/./script"

dirname basically finds the last / in a string and truncates it there. So if you do:

  dirname /usr/bin/sha256sum

you'll get: /usr/bin

This example works well because /usr/bin/sha256sum is a properly formatted path but

  dirname "/some/path/./script"

wouldn't work well and would give you:

  BASENAME="/some/path/." #which would crash your script if you try to use it as a path

Say you're in the same dir as your script and you launch it with this command

./script   

$0 in this situation will be ./script and dirname $0 will give:

. #or BASEDIR=".", again this will crash your script

Using:

sh script

Without inputting the full path will also give a BASEDIR="."

Using relative directories:

 ../some/path/./script

Gives a dirname $0 of:

 ../some/path/.

If you're in the /some directory and you call the script in this manner (note the absence of / in the beginning, again a relative path):

 path/./script.sh

You'll get this value for dirname $0:

 path/. 

and ./path/./script (another form of the relative path) gives:

 ./path/.

The only two situations where basedir $0 will work is if the user use sh or touch to launch a script because both will result in $0:

 $0=/some/path/script

which will give you a path you can use with dirname.

THE SOLUTION

You'd have account for and detect every one of the above mentioned situations and apply a fix for it if it arises:

#!/bin/bash
#this script will only work in bash, make sure it's installed on your system.

#set to false to not see all the echos
debug=true

if [ "$debug" = true ]; then echo "\$0=$0";fi


#The line below detect script's parent directory. $0 is the part of the launch command that doesn't contain the arguments
BASEDIR=$(dirname "$0") #3 situations will cause dirname $0 to fail: #situation1: user launches script while in script dir ( $0=./script)
                                                                     #situation2: different dir but ./ is used to launch script (ex. $0=/path_to/./script)
                                                                     #situation3: different dir but relative path used to launch script
if [ "$debug" = true ]; then echo 'BASEDIR=$(dirname "$0") gives: '"$BASEDIR";fi                                 

if [ "$BASEDIR" = "." ]; then BASEDIR="$(pwd)";fi # fix for situation1

_B2=${BASEDIR:$((${#BASEDIR}-2))}; B_=${BASEDIR::1}; B_2=${BASEDIR::2}; B_3=${BASEDIR::3} # <- bash only
if [ "$_B2" = "/." ]; then BASEDIR=${BASEDIR::$((${#BASEDIR}-1))};fi #fix for situation2 # <- bash only
if [ "$B_" != "/" ]; then  #fix for situation3 #<- bash only
        if [ "$B_2" = "./" ]; then
                #covers ./relative_path/(./)script
                if [ "$(pwd)" != "/" ]; then BASEDIR="$(pwd)/${BASEDIR:2}"; else BASEDIR="/${BASEDIR:2}";fi
        else
                #covers relative_path/(./)script and ../relative_path/(./)script, using ../relative_path fails if current path is a symbolic link
                if [ "$(pwd)" != "/" ]; then BASEDIR="$(pwd)/$BASEDIR"; else BASEDIR="/$BASEDIR";fi
        fi
fi

if [ "$debug" = true ]; then echo "fixed BASEDIR=$BASEDIR";fi

How to suspend/resume a process in Windows?

PsSuspend, as mentioned by Vadzim, even suspends/resumes a process by its name, not only by pid.

I use both PsSuspend and PsList (another tool from the PsTools suite) in a simple toggle script for the OneDrive process: if I need more bandwidth, I suspend the OneDrive sync, afterwards I resume the process by issuing the same mini script:

PsList -d onedrive|find/i "suspend" && PsSuspend -r onedrive || PsSuspend onedrive

PsSuspend command line utility from SysInternals suite. It suspends / resumes a process by its id.

How to select a value in dropdown javascript?

Yes. As mentioned in the posts, value property is nonstandard and does not work with IE. You will need to use the selectedIndex property to achieve this. You can refer to the w3schools DOM reference to see the properties of HTML elements. The following link will give you the list of properties you can work with on the select element.

http://www.w3schools.com/jsref/dom_obj_select.asp

Update

This was not supported during 2011 on IE. As commented by finnTheHuman, it is supported at present.

What is and how to fix System.TypeInitializationException error?

Had a simular issue getting the same exception. Took some time locating. In my case I had a static utility class with a constructor that threw the exception (wrapping it). So my issue was in the static constructor.

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

Your most elegant solution must be:

var left: Node? = null

fun show() {
    left?.also {
        queue.add( it )
    }
}

Then you don't have to define a new and unnecessary local variable, and you don't have any new assertions or casts (which are not DRY). Other scope functions could also work so choose your favourite.

How do I access (read, write) Google Sheets spreadsheets with Python?

This thread seems to be quite old. If anyone's still looking, the steps mentioned here : https://github.com/burnash/gspread work very well.

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os

os.chdir(r'your_path')

scope = ['https://spreadsheets.google.com/feeds',
     'https://www.googleapis.com/auth/drive']

creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
gc = gspread.authorize(creds)
wks = gc.open("Trial_Sheet").sheet1
wks.update_acell('H3', "I'm here!")

Make sure to drop your credentials json file in your current directory. Rename it as client_secret.json.

You might run into errors if you don't enable Google Sheet API with your current credentials.

Calculating a directory's size using Python?

The accepted answer doesn't take into account hard or soft links, and would count those files twice. You'd want to keep track of which inodes you've seen, and not add the size for those files.

import os
def get_size(start_path='.'):
    total_size = 0
    seen = {}
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            try:
                stat = os.stat(fp)
            except OSError:
                continue

            try:
                seen[stat.st_ino]
            except KeyError:
                seen[stat.st_ino] = True
            else:
                continue

            total_size += stat.st_size

    return total_size

print get_size()

What is unexpected T_VARIABLE in PHP?

There might be a semicolon or bracket missing a line before your pasted line.

It seems fine to me; every string is allowed as an array index.

Image, saved to sdcard, doesn't appear in Android's Gallery app

Use this after saving the image

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

import .css file into .less file

If you want to import a css file that should be treaded as less use this line:

.ie {
  @import (less) 'ie.css';
}

Https to http redirect using htaccess

RewriteCond %{HTTP:X-Forwarded-Proto} =https

Reloading/refreshing Kendo Grid

You may try:

    $('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();

How to run Spring Boot web application in Eclipse itself?

May be useful for someone.. In Run as if you are getting only java application (No spring bootapp).. then probably you need to install "Spring Tools (aka Spring IDE and Spring Tool Suite)" through Eclipse market place. After successful installation and restart of Eclipse.. now you can see in Run as "Spring Boot app".

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

I had this problem. Reinstalling the latest version of Adobe Reader did nothing. Adobe Reader worked in Chrome but not in IE. This worked for me ...

1) Go to IE's Tools-->Compatibility View menu.
2) Enter a website that has the PDF you wish to see. Click OK.
3) Restart IE 4) Go to the website you entered and select the PDF. It should come up.
5) Go back to Compatibility View and delete the entry you made.
6) Adobe Reader works OK now in IE on all websites.

It's a strange fix, but it worked for me. I needed to go through an Adobe acceptance screen after reinstall that only appeared after I did the Compatibility View trick. Once accepted, it seemed to work everywhere. Pretty flaky stuff. Hope this helps someone.

How do I get and set Environment variables in C#?

I ran into this while working on a .NET console app to read the PATH environment variable, and found that using System.Environment.GetEnvironmentVariable will expand the environment variables automatically.

I didn't want that to happen...that means folders in the path such as '%SystemRoot%\system32' were being re-written as 'C:\Windows\system32'. To get the un-expanded path, I had to use this:

string keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\";
string existingPathFolderVariable = (string)Registry.LocalMachine.OpenSubKey(keyName).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);

Worked like a charm for me.

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);

Using GregorianCalendar with SimpleDateFormat

tl;dr

LocalDate.parse(
    "23-Mar-2017" ,
    DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) 
)

Avoid legacy date-time classes

The Question and other Answers are now outdated, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Using java.time

You seem to be dealing with date-only values. So do not use a date-time class. Instead use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Parse a string.

String input = "23-Mar-2017" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f );

Generate a string.

String output = ld.format( f );

If you were given numbers rather than text for the year, month, and day-of-month, use LocalDate.of.

LocalDate ld = LocalDate.of( 2017 , 3 , 23 );  // ( year , month 1-12 , day-of-month )

See this code run live at IdeOne.com.

input: 23-Mar-2017

ld.toString(): 2017-03-23

output: 23-Mar-2017


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Python: PIP install path, what is the correct location for this and other addons?

Since pip is an executable and which returns path of executables or filenames in environment. It is correct. Pip module is installed in site-packages but the executable is installed in bin.

Going to a specific line number using Less in Unix

To open at a specific line straight from the command line, use:

less +320123 filename

If you want to see the line numbers too:

less +320123 -N filename

You can also choose to display a specific line of the file at a specific line of the terminal, for when you need a few lines of context. For example, this will open the file with line 320123 on the 10th line of the terminal:

less +320123 -j 10 filename

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

How to log cron jobs?

If you'd still like to check your cron jobs you should provide a valid email account when setting the Cron jobs in cPanel.

When you specify a valid email you will receive the output of the cron job that is executed. Thus you will be able to check it and make sure everything has been executed correctly. Note that you will not receive an email if there is no output from the cron job command.

Please bear in mind that you will receive an email for each of the executed cron jobs. This may flood your inbox in case your crons run too often

How to read file with space separated values in pandas

you can use regex as the delimiter:

pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")

How to use a TRIM function in SQL Server

You are missing two closing parentheses...and I am not sure an ampersand works as a string concatenation operator. Try '+'

SELECT dbo.COL_V_Cost_GEMS_Detail.TNG_SYS_NR AS [EHP Code], 
dbo.COL_TBL_VCOURSE.TNG_NA AS [Course Title], 
LTRIM(RTRIM(FCT_TYP_CD)) + ') AND (' + LTRIM(RTRIM(DEP_TYP_ID)) + ')' AS [Course Owner]

How to print variables without spaces between values

Don't use print ..., if you don't want spaces. Use string concatenation or formatting.

Concatenation:

print 'Value is "' + str(value) + '"'

Formatting:

print 'Value is "{}"'.format(value)

The latter is far more flexible, see the str.format() method documentation and the Formatting String Syntax section.

You'll also come across the older % formatting style:

print 'Value is "%d"' % value
print 'Value is "%d", but math.pi is %.2f' % (value, math.pi)

but this isn't as flexible as the newer str.format() method.

Cannot add or update a child row: a foreign key constraint fails

Just a little bit fix: Make the JoinColumn 'nullable = true' in Table1 and 'UserID' field 'insertable=false' and 'nullable=true' in Table2.

In Table1 Entity:

@OneToMany(targetEntity=Table2.class, cascade = CascadeType.ALL)
@JoinColumn(name = "UserID", referencedColumnName = "UserID", nullable = true)
private List<Table2> table2List;

In Table2 Entity:

@Column(insertable = false, nullable = true)
private int UserID;

Extract time from date String

I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.

Catch KeyError in Python

You can also try to use get(), for example:

connection = manager.connect.get("I2Cx")

which won't raise a KeyError in case the key doesn't exist.

You may also use second argument to specify the default value, if the key is not present.

How do you execute SQL from within a bash script?

If you do not want to install sqlplus on your server/machine then the following command-line tool can be your friend. It is a simple Java application, only Java 8 that you need in order to you can execute this tool.

The tool can be used to run any SQL from the Linux bash or Windows command line.

Example:

java -jar sql-runner-0.2.0-with-dependencies.jar \
     -j jdbc:oracle:thin:@//oracle-db:1521/ORCLPDB1.localdomain \
     -U "SYS as SYSDBA" \
     -P Oradoc_db1 \
      "select 1 from dual"

Documentation is here.

You can download the binary file from here.

Give all permissions to a user on a PostgreSQL database

In PostgreSQL 9.0+ you would do the following:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA MY_SCHEMA TO MY_GROUP;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA MY_SCHEMA TO MY_GROUP;

If you want to enable this for newly created relations too, then set the default permissions:

ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
  GRANT ALL PRIVILEGES ON TABLES TO MY_GROUP;
ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
  GRANT ALL PRIVILEGES ON SEQUENCES TO MY_GROUP;

However, seeing that you use 8.1 you have to code it yourself:

CREATE FUNCTION grant_all_in_schema (schname name, grant_to name) RETURNS integer AS $$
DECLARE
  rel RECORD;
BEGIN
  FOR rel IN
    SELECT c.relname
    FROM pg_class c
    JOIN pg_namespace s ON c.namespace = s.oid
    WHERE s.nspname = schname
  LOOP
    EXECUTE 'GRANT ALL PRIVILEGES ON ' || quote_ident(schname) || '.' || rel.relname || ' TO ' || quote_ident(grant_to);
  END LOOP;
  RETURN 1;
END; $$ LANGUAGE plpgsql STRICT;
REVOKE ALL ON FUNCTION grant_all_in_schema(name, name) FROM PUBLIC;

This will set the privileges on all relations: tables, views, indexes, sequences, etc. If you want to restrict that, filter on pg_class.relkind. See the pg_class docs for details.

You should run this function as superuser and as regular as your application requires. An option would be to package this in a cron job that executes every day or every hour.

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

As an addendum to akf's answer you could use instanceof checks instead of String equals() calls:

String cname="com.some.vendor.Impl";
try {
  Class c=this.getClass().getClassLoader().loadClass(cname);
  Object o= c.newInstance();
  if(o instanceof Spam) {
    Spam spam=(Spam) o;
    process(spam);
  }
  else if(o instanceof Ham) {
    Ham ham = (Ham) o;
    process(ham);
  }
  /* etcetera */
}
catch(SecurityException se) {
  System.err.printf("Someone trying to game the system?%nOr a rename is in order because this JVM doesn't feel comfortable with: “%s”", cname);
  se.printStackTrace();
}
catch(LinkageError le) {
  System.err.printf("Seems like a bad class to this JVM: “%s”.", cname);
  le.printStackTrace();
}
catch(RuntimeException re) { 
  // runtime exceptions I might have forgotten. Classloaders are wont to produce those.
  re.printStackTrace();
}
catch(Exception e) { 
  e.printStackTrace();
}

Note the liberal hardcoding of some values. Anyways the main points are:

  1. Use instanceof rather than equals(). If anything, it will co-operate better when refactoring.
  2. Be sure to catch these runtime errors and security ones too.

Class not registered Error

I was getting the below error in my 32 bit application.

Error: Retrieving the COM class factory for component with CLSID {4911BB26-11EE-4182-B66C-64DF2FA6502D} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

And on setting the "Enable32bitApplications" to true in defaultapplicationpool in IIS worked for me.

Difference between webdriver.Dispose(), .Close() and .Quit()

Close() - It is used to close the browser or page currently which is having the focus.

Quit() - It is used to shut down the web driver instance or destroy the web driver instance(Close all the windows).

Dispose() - I am not aware of this method.

add created_at and updated_at fields to mongoose schemas

we may can achieve this by using schema plugin also.

In helpers/schemaPlugin.js file

module.exports = function(schema) {

  var updateDate = function(next){
    var self = this;
    self.updated_at = new Date();
    if ( !self.created_at ) {
      self.created_at = now;
    }
    next()
  };
  // update date for bellow 4 methods
  schema.pre('save', updateDate)
    .pre('update', updateDate)
    .pre('findOneAndUpdate', updateDate)
    .pre('findByIdAndUpdate', updateDate);
};

and in models/ItemSchema.js file:

var mongoose = require('mongoose'),
  Schema   = mongoose.Schema,
  SchemaPlugin = require('../helpers/schemaPlugin');

var ItemSchema = new Schema({
  name    : { type: String, required: true, trim: true },
  created_at    : { type: Date },
  updated_at    : { type: Date }
});
ItemSchema.plugin(SchemaPlugin);
module.exports = mongoose.model('Item', ItemSchema);

What's the difference between primitive and reference types?

these are primitive data types

  • boolean
  • character
  • byte
  • short
  • integer
  • long
  • float
  • double

saved in stack in the memory which is managed memory on the other hand object data type or reference data type stored in head in the memory managed by GC

this is the most important difference

Typescript sleep

You have to wait for TypeScript 2.0 with async/await for ES5 support as it now supported only for TS to ES6 compilation.

You would be able to create delay function with async:

function delay(ms: number) {
    return new Promise( resolve => setTimeout(resolve, ms) );
}

And call it

await delay(300);

Please note, that you can use await only inside async function.

If you can't (let's say you are building nodejs application), just place your code in the anonymous async function. Here is an example:

    (async () => { 
        // Do something before delay
        console.log('before delay')

        await delay(1000);

        // Do something after
        console.log('after delay')
    })();

Example TS Application: https://github.com/v-andrew/ts-template

In OLD JS you have to use

setTimeout(YourFunctionName, Milliseconds);

or

setTimeout( () => { /*Your Code*/ }, Milliseconds );

However with every major browser supporting async/await it less useful.

Update: TypeScript 2.1 is here with async/await.

Just do not forget that you need Promise implementation when you compile to ES5, where Promise is not natively available.

PS

You have to export the function if you want to use it outside of the original file.

Lightweight XML Viewer that can handle large files

http://www.firstobject.com/dn_editor.htm is so far the best and lightest editor available with handful of utilities. I recommend using it - tried with up to 400 MB of files and more than a million records :)

How to match "any character" in regular expression?

.* and .+ are for any chars except for new lines.

Double Escaping

Just in case, you would wanted to include new lines, the following expressions might also work for those languages that double escaping is required such as Java or C++:

[\\s\\S]*
[\\d\\D]*
[\\w\\W]*

for zero or more times, or

[\\s\\S]+
[\\d\\D]+
[\\w\\W]+

for one or more times.

Single Escaping:

Double escaping is not required for some languages such as, C#, PHP, Ruby, PERL, Python, JavaScript:

[\s\S]*
[\d\D]*
[\w\W]*
[\s\S]+
[\d\D]+
[\w\W]+

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){

        final String regex_1 = "[\\s\\S]*";
        final String regex_2 = "[\\d\\D]*";
        final String regex_3 = "[\\w\\W]*";
        final String string = "AAA123\n\t"
             + "ABCDEFGH123\n\t"
             + "XXXX123\n\t";

        final Pattern pattern_1 = Pattern.compile(regex_1);
        final Pattern pattern_2 = Pattern.compile(regex_2);
        final Pattern pattern_3 = Pattern.compile(regex_3);

        final Matcher matcher_1 = pattern_1.matcher(string);
        final Matcher matcher_2 = pattern_2.matcher(string);
        final Matcher matcher_3 = pattern_3.matcher(string);

        if (matcher_1.find()) {
            System.out.println("Full Match for Expression 1: " + matcher_1.group(0));
        }

        if (matcher_2.find()) {
            System.out.println("Full Match for Expression 2: " + matcher_2.group(0));
        }
        if (matcher_3.find()) {
            System.out.println("Full Match for Expression 3: " + matcher_3.group(0));
        }
    }
}

Output

Full Match for Expression 1: AAA123
    ABCDEFGH123
    XXXX123

Full Match for Expression 2: AAA123
    ABCDEFGH123
    XXXX123

Full Match for Expression 3: AAA123
    ABCDEFGH123
    XXXX123

If you wish to explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

Try to remove armv7s from project's "Valid architecture" to release from this issue for iOS 5.1 phone

Center a DIV horizontally and vertically

I do not believe there is a way to do this strictly with CSS. The reason is your "important" qualifier to the question: forcing the parent element to expand with the contents of its child.

My guess is that you will have to use some bits of JavaScript to find the height of the child, and make adjustments.

So, with this HTML:

<div class="parentElement">  
  <div class="childElement">  
    ...Some Contents...  
  </div>  
</div>  

This CSS:

.parentElement {  
  position:relative;
  width:960px;
}
.childElement {
  position:absolute;
  top:50%;
  left:50%;
}

This jQuery might be useful:

$('.childElement').each(function(){
  // determine the real dimensions of the element: http://api.jquery.com/outerWidth/
  var x = $(this).outerWidth();
  var y = $(this).outerHeight();
  // adjust parent dimensions to fit child
  if($(this).parent().height() < y) {
    $(this).parent().css({height: y + 'px'});
  }
  // offset the child element using negative margins to "center" in both axes
  $(this).css({marginTop: 0-(y/2)+'px', marginLeft: 0-(x/2)+'px'});
});

Remember to load the jQ properly, either in the body below the affected elements, or in the head inside of $(document).ready(...).

getResources().getColor() is deprecated

well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor function. You can get current theme with getTheme().

This will do the trick in fragment, you can replace getActivity() with getBaseContext(), yourContext, etc which hold your current context

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}

*p.s : color is deprecated in M, but drawable is deprecated in L

JQuery: Change value of hidden input field

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

How do I reference tables in Excel using VBA?

Adding a third option. The "shorthand" version of @AndrewD's second option.

  1. SheetObject.ListObjects("TableName")
  2. Application.Range("TableName").ListObject
  3. [TableName].ListObject

Yes, there are no quotes in the bracket reference.

How to set the text color of TextView in code?

You can use textView.setTextColor(Color.BLACK) to use any of the in-built colors of the Color class.

You can also use textView.setTextColor(Color.parseColor(hexRGBvalue)) to define custom colors.

Copying files from one directory to another in Java

Not even that complicated and no imports required in Java 7:

The renameTo( ) method changes the name of a file:

public boolean renameTo( File destination)

For example, to change the name of the file src.txt in the current working directory to dst.txt, you would write:

File src = new File(" src.txt"); File dst = new File(" dst.txt"); src.renameTo( dst); 

That's it.

Reference:

Harold, Elliotte Rusty (2006-05-16). Java I/O (p. 393). O'Reilly Media. Kindle Edition.

Jquery function BEFORE form submission

Aghhh... i was missing some code when i first tried the .submit function.....

This works:

$('#create-card-process.design').submit(function() {
    var textStyleCSS = $("#cover-text").attr('style');
    var textbackgroundCSS = $("#cover-text-wrapper").attr('style');
    $("#cover_text_css").val(textStyleCSS);
    $("#cover_text_background_css").val(textbackgroundCSS);
});

Thanks for all the comments.

Return Boolean Value on SQL Select Statement

DECLARE @isAvailable      BIT = 0;

IF EXISTS(SELECT 1  FROM [User] WHERE (UserID = 20070022))
BEGIN
 SET @isAvailable = 1
END

initially isAvailable boolean value is set to 0

How to get selenium to wait for ajax response?

A more general solution than waiting for an element would be to wait for all the connections to the server to close. This will allow you to wait for all ajax calls to finish, even if they don't have any callback and thus don't affect the page. More details can be found here.

Using C# and jQuery, I have created the following method to wait for all AJax calls to complete (if anyone have more direct ways of accessing JS variables from C#, please comment):

internal void WaitForAjax(int timeOut = 15)
{
    var value = "";
    RepeatUntil(
        () => value = GetJavascriptValue("jQuery.active"), 
        () => value == "0", 
        "Ajax calls did not complete before timeout"
    );
}

internal void RepeatUntil(Action repeat, Func<bool> until, string errorMessage, int timeout = 15)
{
    var end = DateTime.Now + TimeSpan.FromSeconds(timeout);
    var complete = false;

    while (DateTime.Now < end)
    {
        repeat();
        try
        {
            if (until())
            {
                complete = true;
                break;
            }
        }
        catch (Exception)
        { }
        Thread.Sleep(500);
    }
    if (!complete)
        throw new TimeoutException(errorMessage);
}

internal string GetJavascriptValue(string variableName)
{
    var id = Guid.NewGuid().ToString();
    _selenium.RunScript(String.Format(@"window.$('body').append(""<input type='text' value='""+{0}+""' id='{1}'/>"");", variableName, id));
    return _selenium.GetValue(id);
}

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

IN vs OR in the SQL WHERE Clause

I assume you want to know the performance difference between the following:

WHERE foo IN ('a', 'b', 'c')
WHERE foo = 'a' OR foo = 'b' OR foo = 'c'

According to the manual for MySQL if the values are constant IN sorts the list and then uses a binary search. I would imagine that OR evaluates them one by one in no particular order. So IN is faster in some circumstances.

The best way to know is to profile both on your database with your specific data to see which is faster.

I tried both on a MySQL with 1000000 rows. When the column is indexed there is no discernable difference in performance - both are nearly instant. When the column is not indexed I got these results:

SELECT COUNT(*) FROM t_inner WHERE val IN (1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000);
1 row fetched in 0.0032 (1.2679 seconds)

SELECT COUNT(*) FROM t_inner WHERE val = 1000 OR val = 2000 OR val = 3000 OR val = 4000 OR val = 5000 OR val = 6000 OR val = 7000 OR val = 8000 OR val = 9000;
1 row fetched in 0.0026 (1.7385 seconds)

So in this case the method using OR is about 30% slower. Adding more terms makes the difference larger. Results may vary on other databases and on other data.

When to use IList and when to use List

IEnumerable
You should try and use the least specific type that suits your purpose.
IEnumerable is less specific than IList.
You use IEnumerable when you want to loop through the items in a collection.

IList
IList implements IEnumerable.
You should use IList when you need access by index to your collection, add and delete elements, etc...

List
List implements IList.

Colors in JavaScript console

I actually just found this by accident being curious with what would happen but you can actually use bash colouring flags to set the colour of an output in Chrome:

console.log('\x1b[36m Hello \x1b[34m Colored \x1b[35m World!');
console.log('\x1B[31mHello\x1B[34m World');
console.log('\x1b[43mHighlighted');

Output:

Hello World red and blue

enter image description here

See this link for how colour flags work: https://misc.flogisoft.com/bash/tip_colors_and_formatting

Basically use the \x1b or \x1B in place of \e. eg. \x1b[31m and all text after that will be switched to the new colour.

I haven't tried this in any other browser though, but thought it worth mentioning.

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

} catch ( ActivityNotFoundException e ) {
     e.printStackTrace();

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

Multiprocessing vs Threading Python

As I learnd in university most of the answers above are right. In PRACTISE on different platforms (always using python) spawning multiple threads ends up like spawning one process. The difference is the multiple cores share the load instead of only 1 core processing everything at 100%. So if you spawn for example 10 threads on a 4 core pc, you will end up getting only the 25% of the cpus power!! And if u spawn 10 processes u will end up with the cpu processing at 100% (if u dont have other limitations). Im not a expert in all the new technologies. Im answering with own real experience background

How to append a newline to StringBuilder

I create original class that similar to StringBuidler and can append line by calling method appendLine(String str).

public class StringBuilderPlus {

    private StringBuilder sb;

    public StringBuilderPlus(){
         sb = new StringBuilder();
    }

    public void append(String str)
    {
        sb.append(str != null ? str : "");
    }

    public void appendLine(String str)
    {
        sb.append(str != null ? str : "").append(System.getProperty("line.separator"));
    }

    public String toString()
    {
        return sb.toString();
    }
}

Usage:

StringBuilderPlus sb = new StringBuilderPlus();
sb.appendLine("aaaaa");
sb.appendLine("bbbbb");
System.out.println(sb.toString());

Console:

aaaaa
bbbbb

What does it mean by select 1 from table?

If you don't know there exist any data in your table or not, you can use following query:

SELECT cons_value FROM table_name;

For an Example:

SELECT 1 FROM employee;
  1. It will return a column which contains the total number of rows & all rows have the same constant value 1 (for this time it returns 1 for all rows);
  2. If there is no row in your table it will return nothing.

So, we use this SQL query to know if there is any data in the table & the number of rows indicates how many rows exist in this table.

What is the easiest way to get the current day of the week in Android?

Using both method you find easy if you wont last seven days you use (currentdaynumber+7-1)%7,(currentdaynumber+7-2)%7.....upto 6

public static String getDayName(int day){
    switch(day){
        case 0:
            return "Sunday";
        case 1:
            return "Monday";
        case 2:
            return "Tuesday";
        case 3:
            return "Wednesday";
        case 4:
            return "Thursday";
        case 5:
            return  "Friday";
        case 6:
            return "Saturday";
    }

    return "Worng Day";
}
public static String getCurrentDay(){
    SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", Locale.US);
    Calendar calendar = Calendar.getInstance();
    return dayFormat.format(calendar.getTime());

}

Is it possible to change the content HTML5 alert messages?

Yes:

<input required title="Enter something OR ELSE." /> 

The title attribute will be used to notify the user of a problem.

Does my application "contain encryption"?

It's not hard to get approval for your app the proper way. SSL (HTTPS/TLS) is still encryption and unless you are using it just for authentication, then you should get the proper approval. I just received approval, and my app is in the store now for something that uses SSL to encrypt data traffic (not just authentication).

Here is a blog entry I made so that others can do this the proper way.

apple itunes export restrictions

convert from Color to brush

you can use this:

new SolidBrush(color)

where color is something like this:

Color.Red

or

Color.FromArgb(36,97,121))

or ...

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

You will also get this if git doesn't have permissions to read the config files. It will just go up in the hierarchy tree until it needs to cross file systems.

Detect all Firefox versions in JS

here it it

var ffversion = '18';
var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox/'+ffversion) > -1;
alert(is_firefox);

how to change text in Android TextView

per your advice, i am using handle and runnables to switch/change the content of the TextView using a "timer". for some reason, when running, the app always skips the second step ("Step Two: fry egg"), and only show the last (third) step ("Step three: serve egg").

TextView t; 
private String sText;

private Handler mHandler = new Handler();

private Runnable mWaitRunnable = new Runnable() {
    public void run() {
        t.setText(sText);
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    mMonster = BitmapFactory.decodeResource(getResources(),
            R.drawable.monster1);

    t=new TextView(this); 
    t=(TextView)findViewById(R.id.TextView01); 

    sText = "Step One: unpack egg";
    t.setText(sText);

    sText = "Step Two: fry egg";        
    mHandler.postDelayed(mWaitRunnable, 3000);

    sText = "Step three: serve egg";
    mHandler.postDelayed(mWaitRunnable, 4000);      
    ...
}

Update Rows in SSIS OLEDB Destination

Well, found a solution to my problem; Updating all rows using a SQL query and a SQL Task in SSIS Like Below. May help others if they face same challenge in future.

update Original 
set Original.Vaal= t.vaal 
from Original join (select * from staging1  union   select * from staging2) t 
on Original.id=t.id

How to automatically indent source code?

I have tried both ways, and from the Edit|Advanced menu, and they are not doing anything to my source code. Other options like line indent are working. What could be wrong? – Chucky Jul 12 '13 at 11:06

Sometimes if it doesnt work, try to select a couple lines above and below or the whole block of code (whole function, whole cycle, whole switch, etc.), so that it knows how to indent.

Like for example if you copy/paste something into a case statement of a switch and it has wrong indentation, you need to select the text + the line with the case statement above to get it to work.

Autoplay an audio with HTML5 embed tag while the player is invisible

For future reference to people who find this page later you can use:

<audio controls autoplay loop hidden>
<source src="kooche.mp3" type="audio/mpeg">
<p>If you can read this, your browser does not support the audio element.</p>
</audio>

Set the selected index of a Dropdown using jQuery

First of all - that selector is pretty slow. It will scan every DOM element looking for the ids. It will be less of a performance hit if you can assign a class to the element.

$(".myselect")

To answer your question though, there are a few ways to change the select elements value in jQuery

// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0'); 

// sets selected index of a select box to the option with the value ""
$("select#elem").val(''); 

// sets selected index to first item using the DOM
$("select#elem")[0].selectedIndex = 0;

// sets selected index to first item using jQuery (can work on multiple elements)
$("select#elem").prop('selectedIndex', 0);

How to use MapView in android using google map V2?

yes you can use MapView in v2... for further details you can get help from this

https://gist.github.com/joshdholtz/4522551


SomeFragment.java

public class SomeFragment extends Fragment implements OnMapReadyCallback{
 
    MapView mapView;
    GoogleMap map;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.some_layout, container, false);
 
        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
 
    
        mapView.getMapAsync(this);
        
 
        return v;
    }
 
   @Override
   public void onMapReady(GoogleMap googleMap) {
       map = googleMap;
       map.getUiSettings().setMyLocationButtonEnabled(false);
       map.setMyLocationEnabled(true);
       /*
       //in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
        try {
            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        } 
       */
        
        // Updates the location and zoom of the MapView
        /*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        map.animateCamera(cameraUpdate);*/
        map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));

    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
 
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
 
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    
    <permission
        android:name="com.example.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_key"/>
        
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
    </application>
 
</manifest>

some_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
    <com.google.android.gms.maps.MapView android:id="@+id/mapview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" />
 
</LinearLayout>

How Can I Override Style Info from a CSS Class in the Body of a Page?

you can test a color by writing the CSS inline like <div style="color:red";>...</div>

How can I expose more than 1 port with Docker?

Use this as an example:

docker create --name new_ubuntu -it -p 8080:8080 -p  15672:15672 -p 5432:5432   ubuntu:latest bash

look what you've created(and copy its CONTAINER ID xxxxx):

docker ps -a 

now write the miracle maker word(start):

docker start xxxxx

good luck

Exception is never thrown in body of corresponding try statement

A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}-block can throw (or a super class of that).

try {
    //do something that throws ExceptionA, e.g.
    throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
    //do something to handle the exception, e.g.
    System.out.println("Message: " + e.getMessage());
}

What you are trying to do is this:

try {
    throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
    System.out.println("Message: " + e.getMessage());
}

This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement.

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Parse an URL in JavaScript

One liner:

location.search.replace('?','').split('&').reduce(function(s,c){var t=c.split('=');s[t[0]]=t[1];return s;},{})

START_STICKY and START_NOT_STICKY

  • START_STICKY: It will restart the service in case if it terminated and the Intent data which is passed to the onStartCommand() method is NULL. This is suitable for the service which are not executing commands but running independently and waiting for the job.
  • START_NOT_STICKY: It will not restart the service and it is useful for the services which will run periodically. The service will restart only when there are a pending startService() calls. It’s the best option to avoid running a service in case if it is not necessary.
  • START_REDELIVER_INTENT: It’s same as STAR_STICKY and it recreates the service, call onStartCommand() with last intent that was delivered to the service.

Pandas - Plotting a stacked Bar Chart

If you want to change the size of plot the use arg figsize

df.groupby(['NFF', 'ABUSE']).size().unstack()
      .plot(kind='bar', stacked=True, figsize=(15, 5))

How to use adb command to push a file on device without sd card

I've got a Nexus 4, that is without external storage. However Android thinks to have one because it mount a separated partition called "storage", mounted in "/storage/emulated/legacy", so try pushing there: adb push anand.jpg /storage/emulated/legacy

CSS: How to remove pseudo elements (after, before,...)?

p:after {
   content: none;
}

none is the official value to set the content, if specified, to nothing.

http://www.w3schools.com/cssref/pr_gen_content.asp

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

Writing file to web server - ASP.NET

Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.

Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.

Hashset vs Treeset

Even after 11 years, nobody thought of mentioning a very important difference.

Do you think that if HashSet equals TreeSet then the opposite is true as well? Take a look at this code:

TreeSet<String> treeSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
HashSet<String> hashSet = new HashSet<>();
treeSet.add("a");
hashSet.add("A");
System.out.println(hashSet.equals(treeSet));
System.out.println(treeSet.equals(hashSet));

Try to guess the output and then hover below snippet for seeing what the real output is. Ready? Here you go:

false
true

That's right, they don't hold equivalence relation for a comparator that is inconsistent with equals. The reason for this is that a TreeSet uses a comparator to determine the equivalence while HashSet uses equals. Internally they use HashMap and TreeMap so you should expect this behavior with the mentioned Maps as well.

Originally answered

Is < faster than <=?

When I wrote the first version of this answer, I was only looking at the title question about < vs. <= in general, not the specific example of a constant a < 901 vs. a <= 900. Many compilers always shrink the magnitude of constants by converting between < and <=, e.g. because x86 immediate operand have a shorter 1-byte encoding for -128..127.

For ARM, being able to encode as an immediate depends on being able to rotate a narrow field into any position in a word. So cmp r0, #0x00f000 would be encodeable, while cmp r0, #0x00efff would not be. So the make-it-smaller rule for comparison vs. a compile-time constant doesn't always apply for ARM. AArch64 is either shift-by-12 or not, instead of an arbitrary rotation, for instructions like cmp and cmn, unlike 32-bit ARM and Thumb modes.


< vs. <= in general, including for runtime-variable conditions

In assembly language on most machines, a comparison for <= has the same cost as a comparison for <. This applies whether you're branching on it, booleanizing it to create a 0/1 integer, or using it as a predicate for a branchless select operation (like x86 CMOV). The other answers have only addressed this part of the question.

But this question is about the C++ operators, the input to the optimizer. Normally they're both equally efficient; the advice from the book sounds totally bogus because compilers can always transform the comparison that they implement in asm. But there is at least one exception where using <= can accidentally create something the compiler can't optimize.

As a loop condition, there are cases where <= is qualitatively different from <, when it stops the compiler from proving that a loop is not infinite. This can make a big difference, disabling auto-vectorization.

Unsigned overflow is well-defined as base-2 wrap around, unlike signed overflow (UB). Signed loop counters are generally safe from this with compilers that optimize based on signed-overflow UB not happening: ++i <= size will always eventually become false. (What Every C Programmer Should Know About Undefined Behavior)

void foo(unsigned size) {
    unsigned upper_bound = size - 1;  // or any calculation that could produce UINT_MAX
    for(unsigned i=0 ; i <= upper_bound ; i++)
        ...

Compilers can only optimize in ways that preserve the (defined and legally observable) behaviour of the C++ source for all possible input values, except ones that lead to undefined behaviour.

(A simple i <= size would create the problem too, but I thought calculating an upper bound was a more realistic example of accidentally introducing the possibility of an infinite loop for an input you don't care about but which the compiler must consider.)

In this case, size=0 leads to upper_bound=UINT_MAX, and i <= UINT_MAX is always true. So this loop is infinite for size=0, and the compiler has to respect that even though you as the programmer probably never intend to pass size=0. If the compiler can inline this function into a caller where it can prove that size=0 is impossible, then great, it can optimize like it could for i < size.

Asm like if(!size) skip the loop; do{...}while(--size); is one normally-efficient way to optimize a for( i<size ) loop, if the actual value of i isn't needed inside the loop (Why are loops always compiled into "do...while" style (tail jump)?).

But that do{}while can't be infinite: if entered with size==0, we get 2^n iterations. (Iterating over all unsigned integers in a for loop C makes it possible to express a loop over all unsigned integers including zero, but it's not easy without a carry flag the way it is in asm.)

With wraparound of the loop counter being a possibility, modern compilers often just "give up", and don't optimize nearly as aggressively.

Example: sum of integers from 1 to n

Using unsigned i <= n defeats clang's idiom-recognition that optimizes sum(1 .. n) loops with a closed form based on Gauss's n * (n+1) / 2 formula.

unsigned sum_1_to_n_finite(unsigned n) {
    unsigned total = 0;
    for (unsigned i = 0 ; i < n+1 ; ++i)
        total += i;
    return total;
}

x86-64 asm from clang7.0 and gcc8.2 on the Godbolt compiler explorer

 # clang7.0 -O3 closed-form
    cmp     edi, -1       # n passed in EDI: x86-64 System V calling convention
    je      .LBB1_1       # if (n == UINT_MAX) return 0;  // C++ loop runs 0 times
          # else fall through into the closed-form calc
    mov     ecx, edi         # zero-extend n into RCX
    lea     eax, [rdi - 1]   # n-1
    imul    rax, rcx         # n * (n-1)             # 64-bit
    shr     rax              # n * (n-1) / 2
    add     eax, edi         # n + (stuff / 2) = n * (n+1) / 2   # truncated to 32-bit
    ret          # computed without possible overflow of the product before right shifting
.LBB1_1:
    xor     eax, eax
    ret

But for the naive version, we just get a dumb loop from clang.

unsigned sum_1_to_n_naive(unsigned n) {
    unsigned total = 0;
    for (unsigned i = 0 ; i<=n ; ++i)
        total += i;
    return total;
}
# clang7.0 -O3
sum_1_to_n(unsigned int):
    xor     ecx, ecx           # i = 0
    xor     eax, eax           # retval = 0
.LBB0_1:                       # do {
    add     eax, ecx             # retval += i
    add     ecx, 1               # ++1
    cmp     ecx, edi
    jbe     .LBB0_1            # } while( i<n );
    ret

GCC doesn't use a closed-form either way, so the choice of loop condition doesn't really hurt it; it auto-vectorizes with SIMD integer addition, running 4 i values in parallel in the elements of an XMM register.

# "naive" inner loop
.L3:
    add     eax, 1       # do {
    paddd   xmm0, xmm1    # vect_total_4.6, vect_vec_iv_.5
    paddd   xmm1, xmm2    # vect_vec_iv_.5, tmp114
    cmp     edx, eax      # bnd.1, ivtmp.14     # bound and induction-variable tmp, I think.
    ja      .L3 #,       # }while( n > i )

 "finite" inner loop
  # before the loop:
  # xmm0 = 0 = totals
  # xmm1 = {0,1,2,3} = i
  # xmm2 = set1_epi32(4)
 .L13:                # do {
    add     eax, 1       # i++
    paddd   xmm0, xmm1    # total[0..3] += i[0..3]
    paddd   xmm1, xmm2    # i[0..3] += 4
    cmp     eax, edx
    jne     .L13      # }while( i != upper_limit );

     then horizontal sum xmm0
     and peeled cleanup for the last n%3 iterations, or something.
     

It also has a plain scalar loop which I think it uses for very small n, and/or for the infinite loop case.

BTW, both of these loops waste an instruction (and a uop on Sandybridge-family CPUs) on loop overhead. sub eax,1/jnz instead of add eax,1/cmp/jcc would be more efficient. 1 uop instead of 2 (after macro-fusion of sub/jcc or cmp/jcc). The code after both loops writes EAX unconditionally, so it's not using the final value of the loop counter.

How do you create a toggle button?

JQuery UI makes light work out of creating toggle buttons. Just put this

<label for="myToggleButton">my toggle button caption</label>
<input type="checkbox" id="myToggleButton" />

on your page and then in your body onLoad or your $.ready() (or some object literals init() function if your building an ajax site..) drop some JQuery like so:

$("#myToggleButton").button()

thats it. (don't forget the < label for=...> because JQueryUI uses that for the body of the toggle button..)

From there you just work with it like any other input="checkbox" because that is what the underlying control still is but JQuery UI just skins it to look like a pretty toggle button on screen.

What is Node.js?

Two good examples are regarding how you manage templates and use progressive enhancements with it. You just need a few lightweight pieces of JavaScript code to make it work perfectly.

I strongly recommend that you watch and read these articles:

Pick up any language and try to remember how you would manage your HTML file templates and what you had to do to update a single CSS class name in your DOM structure (for instance, a user clicked on a menu item and you want that marked as "selected" and update the content of the page).

With Node.js it is as simple as doing it in client-side JavaScript code. Get your DOM node and apply your CSS class to that. Get your DOM node and innerHTML your content (you will need some additional JavaScript code to do this. Read the article to know more).

Another good example, is that you can make your web page compatible both with JavaScript turned on or off with the same piece of code. Imagine you have a date selection made in JavaScript that would allow your users to pick up any date using a calendar. You can write (or use) the same piece of JavaScript code to make it work with your JavaScript turned ON or OFF.

C error: undefined reference to function, but it IS defined

I had this issue recently. In my case, I had my IDE set to choose which compiler (C or C++) to use on each file according to its extension, and I was trying to call a C function (i.e. from a .c file) from C++ code.

The .h file for the C function wasn't wrapped in this sort of guard:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

I could've added that, but I didn't want to modify it, so I just included it in my C++ file like so:

extern "C" {
#include "legacy_C_header.h"
}

(Hat tip to UncaAlby for his clear explanation of the effect of extern "C".)

Find all elements on a page whose element ID contains a certain text using jQuery

Thanks to both of you. This worked perfectly for me.

$("input[type='text'][id*=" + strID + "]:visible").each(function() {
    this.value=strVal;
});

Check folder size in Bash

To check the size of all of the directories within a directory, you can use:

du -h --max-depth=1

Android WebView progress bar

here is the easiest way to add progress bar in android Web View.

Add a boolean field in your activity/fragment

private boolean isRedirected;

This boolean will prevent redirection of web pages cause of dead links.Now you can just pass your WebView object and web Url into this method.

private void startWebView(WebView webView,String url) {

    webView.setWebViewClient(new WebViewClient() {
        ProgressDialog progressDialog;

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            isRedirected = true;
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            isRedirected = false;
        }

        public void onLoadResource (WebView view, String url) {
            if (!isRedirected) {
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
                    progressDialog.setMessage("Loading...");
                    progressDialog.show();
                }
            }

        }
        public void onPageFinished(WebView view, String url) {
            try{
                isRedirected=true;

                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }



            }catch(Exception exception){
                exception.printStackTrace();
            }
        }

    });

    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);
}

Here when start loading it will call onPageStarted. Here i setting Boolean field is false. But when page load finish it will come to onPageFinished method and here Boolean field is set to true. Sometimes if url is dead it will redirected and it will come to onLoadResource() before onPageFinished method. For this reason it will not hiding the progress bar. To prevent this i am checking if (!isRedirected) in onLoadResource()

in onPageFinished() method before dismissing the Progress Dialog you can write your 10 second time delay code

That's it. Happy coding :)

Position absolute and overflow hidden

An absolutely positioned element is actually positioned regarding a relative parent, or the nearest found relative parent. So the element with overflow: hidden should be between relative and absolute positioned elements:

<div class="relative-parent">
  <div class="hiding-parent">
    <div class="child"></div>
  </div>
</div>

.relative-parent {
  position:relative;
}
.hiding-parent {
  overflow:hidden;
}
.child {
  position:absolute; 
}

Why does NULL = NULL evaluate to false in SQL server

To quote the Christmas analogy again:

In SQL, NULL basically means "closed box" (unknown). So, the result of comparing two closed boxes will also be unknown (null).

I understand, for a developer, this is counter-intuitive, because in programming languages, often NULL rather means "empty box" (known). And comparing two empty boxes will naturally yield true / equal.

This is why JavaScript for example distinguishes between null and undefined.

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

mysqli_error() needs you to pass the connection to the database as a parameter. Documentation here has some helpful examples:

http://php.net/manual/en/mysqli.error.php

Try altering your problem line like so and you should be in good shape:

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error($myConnection)); 

"import datetime" v.s. "from datetime import datetime"

datetime is a module which contains a type that is also called datetime. You appear to want to use both, but you're trying to use the same name to refer to both. The type and the module are two different things and you can't refer to both of them with the name datetime in your program.

If you need to use anything from the module besides the datetime type (as you apparently do), then you need to import the module with import datetime. You can then refer to the "date" type as datetime.date and the datetime type as datetime.datetime.

You could also do this:

from datetime import datetime, date
today_date = date.today()
date_time = datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

Here you import only the names you need (the datetime and date types) and import them directly so you don't need to refer to the module itself at all.

Ultimately you have to decide what names from the module you need to use, and how best to use them. If you are only using one or two things from the module (e.g., just the date and datetime types), it may be okay to import those names directly. If you're using many things, it's probably better to import the module and access the things inside it using dot syntax, to avoid cluttering your global namespace with date-specific names.

Note also that, if you do import the module name itself, you can shorten the name to ease typing:

import datetime as dt
today_date = dt.date.today()
date_time = dt.datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

Number of days between two dates in Joda-Time

tl;dr

java.time.temporal.ChronoUnit.DAYS.between( 
    earlier.toLocalDate(), 
    later.toLocalDate() 
)

…or…

java.time.temporal.ChronoUnit.HOURS.between( 
    earlier.truncatedTo( ChronoUnit.HOURS )  , 
    later.truncatedTo( ChronoUnit.HOURS ) 
)

java.time

FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

The equivalent of Joda-Time DateTime is ZonedDateTime.

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;

Apparently you want to count the days by dates, meaning you want to ignore the time of day. For example, starting a minute before midnight and ending a minute after midnight should result in a single day. For this behavior, extract a LocalDate from your ZonedDateTime. The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate localDateStart = zdtStart.toLocalDate() ;
LocalDate localDateStop = zdtStop.toLocalDate() ;

Use the ChronoUnit enum to calculate elapsed days or other units.

long days = ChronoUnit.DAYS.between( localDateStart , localDateStop ) ;

Truncate

As for you asking about a more general way to do this counting where you are interested the delta of hours as hour-of-the-clock rather than complete hours as spans-of-time of sixty minutes, use the truncatedTo method.

Here is your example of 14:45 to 15:12 on same day.

ZoneId z = ZoneId.of( "America/Montreal" ); 
ZonedDateTime start = ZonedDateTime.of( 2017 , 1 , 17 , 14 , 45 , 0 , 0 , z );
ZonedDateTime stop = ZonedDateTime.of( 2017 , 1 , 17 , 15 , 12 , 0 , 0 , z );

long hours = ChronoUnit.HOURS.between( start.truncatedTo( ChronoUnit.HOURS ) , stop.truncatedTo( ChronoUnit.HOURS ) );

1

This does not work for days. Use toLocalDate() in this case.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Test if something is not undefined in JavaScript

Actually you must surround it with an Try/Catch block so your code won't stop from working. Like this:

try{
    if(typeof response[0].title !== 'undefined') {
        doSomething();
    }
  }catch(e){
    console.log('responde[0].title is undefined'); 
  }

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

I even run the command prompt as Administrator but it didn't work for me with the below error.

'keytool' is not recognized as an internal or external command,
 operable program or batch file.

If the path to the keytool is not in your System paths then you will need to use the full path to use the keytool, which is

C:\Program Files\Java\jre<version>\bin

So, the command should be like

"C:\Program Files\Java\jre<version>\bin\keytool.exe" -importcert -alias certificateFileAlias -file CertificateFileName.cer -keystore cacerts

that worked for me.

Using column alias in WHERE clause of MySQL query produces an error

You can use SUBSTRING(locations.raw,-6,4) for where conditon

SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE SUBSTRING(`locations`.`raw`,-6,4) NOT IN #this is where the fake col is being used
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
 'australia'
)
)

Default optional parameter in Swift function

Optionals and default parameters are two different things.

An Optional is a variable that can be nil, that's it.

Default parameters use a default value when you omit that parameter, this default value is specified like this: func test(param: Int = 0)

If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil. If your function looks like this func test(param: Int?), you can't call it like this test(). Even though the parameter is optional, it doesn't have a default value.

You can also combine the two and have a parameter that takes an optional where nil is the default value, like this: func test(param: Int? = nil).

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

I solved this by stopping mysql several times.

$ mysql.server stop
Shutting down MySQL
.. ERROR! The server quit without updating PID file (/usr/local/var/mysql/xxx.local.pid).
$ mysql.server stop
Shutting down MySQL
.. SUCCESS! 
$ mysql.server stop
ERROR! MySQL server PID file could not be found! (note: this is good)
$ mysql.server start

All good from here. I suspect mysql had been started more than once.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Read file line by line in PowerShell

Get-Content has bad performance; it tries to read the file into memory all at once.

C# (.NET) file reader reads each line one by one

Best Performace

foreach($line in [System.IO.File]::ReadLines("C:\path\to\file.txt"))
{
       $line
}

Or slightly less performant

[System.IO.File]::ReadLines("C:\path\to\file.txt") | ForEach-Object {
       $_
}

The foreach statement will likely be slightly faster than ForEach-Object (see comments below for more information).

How do I clone a github project to run locally?

To clone a repository and place it in a specified directory use "git clone [url] [directory]". For example

git clone https://github.com/ryanb/railscasts-episodes.git Rails

will create a directory named "Rails" and place it in the new directory. Click here for more information.

Shell script to check if file exists

Wildcards aren't expanded inside quoted strings. And when wildcard is expanded, it's returned unchanged if there are no matches, it doesn't expand into an empty string. Try:

output="$(ls home/edward/bank1/fiche/Test* 2>/dev/null)"
if [ -n "$output" ]
then echo "Found one"
else echo "Found none"
fi

If the wildcard expanded to filenames, ls will list them on stdout; otherwise it will print an error on stderr, and nothing on stdout. The contents of stdout are assigned to output.

if [ -n "$output" ] tests whether $output contains anything.

Another way to write this would be:

if [ $(ls home/edward/bank1/fiche/Test* 2>/dev/null | wc -l) -gt 0 ]

Formatting "yesterday's" date in python

To expand on the answer given by Chris

if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know

>>> from datetime import date, timedelta                   
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'

If you want it as an integer (which can be useful)

>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

What is the &#xA; character?

It is the equivalent to \n -> LF (Line Feed).

Sometimes it is used in HTML and JavaScript. Otherwise in .NET environments, use Environment.NewLine.

"The operation is not valid for the state of the transaction" error and transaction scope

For me, this error came up when I was trying to rollback a transaction block after encountering an exception, inside another transaction block.

All I had to do to fix it was to remove my inner transaction block.

Things can get quite messy when using nested transactions, best to avoid this and just restructure your code.

Update value of a nested dictionary of varying depth

a new Q how to By a keys chain

dictionary1={'level1':{'level2':{'levelA':0,'levelB':1}},'anotherLevel1':{'anotherLevel2':{'anotherLevelA':0,'anotherLevelB':1}}}
update={'anotherLevel1':{'anotherLevel2':1014}}
dictionary1.update(update)
print dictionary1
{'level1':{'level2':{'levelA':0,'levelB':1}},'anotherLevel1':{'anotherLevel2':1014}}

Backup/Restore a dockerized PostgreSQL database

The below command can be used to take dump from docker postgress container

docker exec -t <postgres-container-name> pg_dump --no-owner -U <db-username> <db-name> > file-name-to-backup-to.sql

How to change text color of simple list item

Create an xml file in res/values and copy the below code

<style name="BlackText">
<item name="android:textColor">#000000</item>
</style>

and the specify the style in activity in Manifest like below

 android:theme="@style/BlackText"

Return different type of data from a method in java?

I create various return types using enum. It doesn't defined automatically. That implementation look like factory pattern.

public  enum  SmartReturn {

    IntegerType, DoubleType;

    @SuppressWarnings("unchecked")
    public <T> T comeback(String value) {
        switch (this) {
            case IntegerType:
                return (T) Integer.valueOf(value);
            case DoubleType:
                return (T) Double.valueOf(value);
            default:
                return null;
        }
    }
}

Unit Test:

public class MultipleReturnTypeTest {

  @Test
  public void returnIntegerOrString() {
     Assert.assertTrue(SmartReturn.IntegerType.comeback("1") instanceof Integer);
     Assert.assertTrue(SmartReturn.DoubleType.comeback("1") instanceof Double);
  }

}

Add a default value to a column through a migration

This is what you can do:

class Profile < ActiveRecord::Base
  before_save :set_default_val

  def set_default_val
    self.send_updates = 'val' unless self.send_updates
  end
end

EDIT: ...but apparently this is a Rookie mistake!

Can I have multiple Xcode versions installed?

Install Multiple Versions Of Xcode using the Xcode-Install Ruby Gem

You can do this whole process a lot easier if you use the xcode-install RubyGem.

If you already have a working installation of the Xcode CommandLineTools and Ruby (I'd suggest using Homebrew for installing Ruby) but I think it works with the Ruby supplied by macOS as well if you install the Gem either using sudo or as a user install. (Details on the GitHub page) Basically:

    $ gem install xcode-install
    $ xcversion list
    6.0.1
    6.1
    6.1.1
    6.2 (installed)
    6.3
    $ xcversion install 8
    ######################################################################## 100.0%
    Please authenticate for Xcode installation...

    Xcode 8
    Build version 6D570

To select a version as active, you'll run:
$ xcversion select 8

To select a version as active and change the symlink at /Applications/Xcode, you'll run:
$ xcversion select 8 --symlink

xcode-install can also manage your local simulators using the simulators command.

Read the instructions on the GitHub Project page for more info.

How do I split a string, breaking at a particular character?

Something like:

var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];

Is probably going to be easiest