Programs & Examples On #Svnlook

How to check queue length in Python

Use queue.rear+1 to get the length of the queue

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

Here is the result. enter image description here

MySQL error 2006: mysql server has gone away

There is an easier way if you are using XAMPP. Open the XAMPP control panel, and click on the config button in mysql section.
enter image description here

Now click on the my.ini and it will open in the editor. Update the max_allowed_packet to your required size.

enter image description here

Then restart the mysql service. Click on stop on the Mysql service click start again. Wait for a few minutes. enter image description here enter image description here

Then try to run your Mysql query again. Hope it will work.

Bootstrap Datepicker - Months and Years Only

You should have to add only minViewMode: "months" in your datepicker function.

How can I read a text file in Android?

Shortest form for small text files (in Kotlin):

val reader = FileReader(path)
val txt = reader.readText()
reader.close()

Android Studio: Default project directory

I found an easy way:

  1. Open a new project;
  2. Change the project location name by typing and not the Browse... button;
  3. The Next button will appear now.

Get Windows version in a batch file

Just starting a new cmd-level from the command line gives you directly the version!

C:> cmd

Microsoft Windows [Version 10.0.17130.1233]

(c) 2018 Microsoft Corporation. All rights reserved.

How to truncate a foreign key constrained table?

While this question was asked I didn't know about it, but now if you use phpMyAdmin you can simply open the database and select the table(s) you want to truncate.

  • At the bottom there is a drop down with many options. Open it and select Empty option under the heading Delete data or table.
  • It takes you to the next page automatically where there is an option in checkbox called Enable foreign key checks. Just unselect it and press the Yes button and the selected table(s) will be truncated.

Maybe it internally runs the query suggested in user447951's answer, but it is very convenient to use from phpMyAdmin interface.

Difference between os.getenv and os.environ.get

In addition to the answers above:

$ python3 -m timeit -s 'import os' 'os.environ.get("TERM_PROGRAM")'
200000 loops, best of 5: 1.65 usec per loop

$ python3 -m timeit -s 'import os' 'os.getenv("TERM_PROGRAM")'
200000 loops, best of 5: 1.83 usec per loop

How do I drag and drop files into an application?

Some sample code:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      this.AllowDrop = true;
      this.DragEnter += new DragEventHandler(Form1_DragEnter);
      this.DragDrop += new DragEventHandler(Form1_DragDrop);
    }

    void Form1_DragEnter(object sender, DragEventArgs e) {
      if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
    }

    void Form1_DragDrop(object sender, DragEventArgs e) {
      string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
      foreach (string file in files) Console.WriteLine(file);
    }
  }

C/C++ include header file order

To add my own brick to the wall.

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

So I usually go like this:

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

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

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

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

#include "detail/impl.h"

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

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

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

How to get different colored lines for different plots in a single figure?

Matplot colors your plot with different colors , but incase you wanna put specific colors

    import matplotlib.pyplot as plt
    import numpy as np
            
    x = np.arange(10)
            
    plt.plot(x, x)
    plt.plot(x, 2 * x,color='blue')
    plt.plot(x, 3 * x,color='red')
    plt.plot(x, 4 * x,color='green')
    plt.show()

Indexes of all occurrences of character in a string

This should print the list of positions without the -1 at the end that Peter Lawrey's solution has had.

int index = word.indexOf(guess);
while (index >= 0) {
    System.out.println(index);
    index = word.indexOf(guess, index + 1);
}

It can also be done as a for loop:

for (int index = word.indexOf(guess);
     index >= 0;
     index = word.indexOf(guess, index + 1))
{
    System.out.println(index);
}

[Note: if guess can be longer than a single character, then it is possible, by analyzing the guess string, to loop through word faster than the above loops do. The benchmark for such an approach is the Boyer-Moore algorithm. However, the conditions that would favor using such an approach do not seem to be present.]

Is it possible to import modules from all files in a directory, using a wildcard?

You can use async import():

import fs = require('fs');

and then:

fs.readdir('./someDir', (err, files) => {
 files.forEach(file => {
  const module = import('./' + file).then(m =>
    m.callSomeMethod();
  );
  // or const module = await import('file')
  });
});

Logging best practices

We use log4net on our web applications.

It's ability to customize logging at run-time by changing the XML configuration file is very handy when an application is malfunctioning at run-time and you need to see more information.

It also allows you to target specific classes or attributes to log under. This is very handy when you have an idea where the error is occurring. A classic example is NHibernate where you want to see just the SQL going to the database.

Edit:

We write all events to a database and the Trace system. The event log we use for errors or exceptions. We log most events to a database so that we can create custom reports and let the users view the log if they want to right from the application.

How to detect installed version of MS-Office?

Why not check HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\[office.exe], where [office.exe] stands for particular office product exe-filename, e.g. winword.exe, excel.exe etc. There you get path to executable and check version of that file.

How to check version of the file: in C++ / in C#

Any criticism towards such approach?

No generated R.java file in my project

Do you have installed the android plugin ?

Your project must be of the android type.

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

You may also find the following approach cleaner than including every method:

class Thing
  delegate :url_helpers, to: 'Rails.application.routes' 

  def url
    url_helpers.thing_path(self)
  end
end

Transition color fade on hover?

For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:

_x000D_
_x000D_
.field-error {_x000D_
    color: #f44336;_x000D_
    padding: 2px 5px;_x000D_
    position: absolute;_x000D_
    font-size: small;_x000D_
    background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
    animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
    -moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
    -webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
    -o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
    from { background-color: lightgreen; } /** from color **/_x000D_
    to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
_x000D_
_x000D_

creating Hashmap from a JSON String

Best way to parse Json to HashMap

public static HashMap<String, String> jsonToMap(JSONObject json) throws JSONException {
            HashMap<String, String> map = new HashMap<>();
            try {
                Iterator<String> iterator = json.keys();

                while (iterator.hasNext()) {
                    String key = iterator.next();
                    String value = json.getString(key);
                    map.put(key, value);
                }

                return map;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

How can I remove an SSH key?

Note that there are at least two bug reports for ssh-add -d/-D not removing keys:

The exact issue is:

ssh-add -d/-D deletes only manually added keys from gnome-keyring.
There is no way to delete automatically added keys.
This is the original bug, and it's still definitely present.

So, for example, if you have two different automatically-loaded ssh identities associated with two different GitHub accounts -- say for work and for home -- there's no way to switch between them. GitHubtakes the first one which matches, so you always appear as your 'home' user to GitHub, with no way to upload things to work projects.

Allowing ssh-add -d to apply to automatically-loaded keys (and ssh-add -t X to change the lifetime of automatically-loaded keys), would restore the behavior most users expect.


More precisely, about the issue:

The culprit is gpg-keyring-daemon:

  • It subverts the normal operation of ssh-agent, mostly just so that it can pop up a pretty box into which you can type the passphrase for an encrypted ssh key.
  • And it paws through your .ssh directory, and automatically adds any keys it finds to your agent.
  • And it won't let you delete those keys.

How do we hate this? Let's not count the ways -- life's too short.

The failure is compounded because newer ssh clients automatically try all the keys in your ssh-agent when connecting to a host.
If there are too many, the server will reject the connection.
And since gnome-keyring-daemon has decided for itself how many keys you want your ssh-agent to have, and has autoloaded them, AND WON'T LET YOU DELETE THEM, you're toast.

This bug is still confirmed in Ubuntu 14.04.4, as recently as two days ago (August 21st, 2014)


A possible workaround:

  • Do ssh-add -D to delete all your manually added keys. This also locks the automatically added keys, but is not much use since gnome-keyring will ask you to unlock them anyways when you try doing a git push.
  • Navigate to your ~/.ssh folder and move all your key files except the one you want to identify with into a separate folder called backup. If necessary you can also open seahorse and delete the keys from there.
  • Now you should be able to do git push without a problem.

Another workaround:

What you really want to do is to turn off gpg-keyring-daemon altogether.
Go to System --> Preferences --> Startup Applications, and unselect the "SSH Key Agent (Gnome Keyring SSH Agent)" box -- you'll need to scroll down to find it.

You'll still get an ssh-agent, only now it will behave sanely: no keys autoloaded, you run ssh-add to add them, and if you want to delete keys, you can. Imagine that.

This comments actually suggests:

The solution is to keep gnome-keyring-manager from ever starting up, which was strangely difficult by finally achieved by removing the program file's execute permission.


Ryan Lue adds another interesting corner case in the comments:

In case this helps anyone: I even tried deleting the id_rsa and id_rsa.pub files altogether, and the key was still showing up.

Turns out gpg-agent was caching them in a ~/.gnupg/sshcontrol file; I had to manually delete them from there.

That is the case when the keygrip has been added as in here.

Laravel stylesheets and javascript don't load for non-base routes

Laravel 4

The better and correct way to do this

Adding CSS

HTML::style will link to your project/public/ folder

{{ HTML::style('css/bootstrap.css') }}

Adding JS

HTML::script will link to your project/public/ folder

{{ HTML::script('js/script.js') }}

How to "log in" to a website using Python's Requests module?

Let me try to make it simple, suppose URL of the site is http://example.com/ and let's suppose you need to sign up by filling username and password, so we go to the login page say http://example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like

 <form name="loginform" method="post" action="userinfo.php">

now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script

import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
          'password': 'pass'}

r = requests.post(url, data=values)
print r.content

I Hope that this helps someone somewhere someday.

Group by in LINQ

First, set your key field. Then include your other fields:

var results = 
    persons
    .GroupBy(n => n.PersonId)
    .Select(r => new Result {PersonID = r.Key, Cars = r.ToList() })
    .ToList()

What is the runtime performance cost of a Docker container?

An excellent 2014 IBM research paper “An Updated Performance Comparison of Virtual Machines and Linux Containers” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: Docker is nearly identical to native performance and faster than KVM in every category.

The exception to this is Docker’s NAT — if you use port mapping (e.g., docker run -p 8080:8080), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., docker run --net=host) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down).

Docker NAT overhead

They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native.

Docker Redis Latency Overhead

Just because it’s a really useful paper, here are some other figures. Please download it for full access.

Taking a look at Disk I/O:

Docker vs. KVM vs. Native I/O Performance

Now looking at CPU overhead:

Docker CPU Overhead

Now some examples of memory (read the paper for details, memory can be extra tricky):

Docker Memory Comparison

Javascript/jQuery: Set Values (Selection) in a multiple Select

in jQuery:

$("#strings").val(["Test", "Prof", "Off"]);

or in pure JavaScript:

var element = document.getElementById('strings');
var values = ["Test", "Prof", "Off"];
for (var i = 0; i < element.options.length; i++) {
    element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}

jQuery does significant abstraction here.

Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:

Suddenly, without any major change in my project, I too got this error.

All the above did not work for me, since I needed both the support libs V4 and V7.

At the end, because 2 hours ago the project compiled with no problems, I simply told Android Studio to REBUILD the project, and the error was gone.

how to get all child list from Firebase android

In my case only given solution worked fine.

Screenshot of Firebase ArrayList structure:

enter image description here

How to fetch whole list from Firebase from DataSnapshot.

GenericTypeIndicator<Map<String, List<Education>>> genericTypeIndicator = new GenericTypeIndicator<Map<String, List<Education>>>() {};
Map<String, List<Education>> hashMap = dataSnapshot.getValue(genericTypeIndicator);

for (Map.Entry<String,List<Education>> entry : hashMap.entrySet()) {
      List<Education> educations = entry.getValue();
        for (Education education: educations){
             Log.i(TAG, education.Degree);
         }
}

Education.java: (Model class).

public class Education implements Serializable{

    public String Degree;
    public String Result;
}

Hope this would works fine.

JQUERY: Uncaught Error: Syntax error, unrecognized expression

Try using:

console.log($("#"+d));

This will remove the extra quotes you were using.

How to run a specific Android app using Terminal?

Use the cmd activity start-activity (or the alternative am start) command, which is a command-line interface to the ActivityManager. Use am to start activities as shown in this help:

$ adb shell am
usage: am [start|instrument]
       am start [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
                [-c <CATEGORY> [-c <CATEGORY>] ...]
                [-e <EXTRA_KEY> <EXTRA_VALUE> [-e <EXTRA_KEY> <EXTRA_VALUE> ...]
                [-n <COMPONENT>] [-D] [<URI>]
       ...

For example, to start the Contacts application, and supposing you know only the package name but not the Activity, you can use

$ pkg=com.google.android.contacts
$ comp=$(adb shell cmd package resolve-activity --brief -c android.intent.category.LAUNCHER $pkg | tail -1)
$ adb shell cmd activity start-activity $comp

or the alternative

$ adb shell am start -n $comp

See also http://www.kandroid.org/online-pdk/guide/instrumentation_testing.html (may be a copy of obsolete url : http://source.android.com/porting/instrumentation_testing.html ) for other details.

To terminate the application you can use

$ adb shell am kill com.google.android.contacts

or the more drastic

$ adb shell am force-stop com.google.android.contacts

Python 3.1.1 string to hex

base64.b16encode and base64.b16decode convert bytes to and from hex and work across all Python versions. The codecs approach also works, but is less straightforward in Python 3.

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

Writing a new line to file in PHP (line feed)

You can also use file_put_contents():

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Gradle failed to resolve library in Android Studio

repositories {
    mavenCentral()
}

I added this in build.gradle, and it worked.

VNC viewer with multiple monitors

tightVNC 2.5.X and even pre 2.5 supports multi monitor. When you connect, you get a huge virtual monitor. However, this is also has disadvantages. UltaVNC (Tho when I tried it, was buggy in this area) allows you to connect to one huge virtual monitor or just to 1 screen at a time. (With a button to cycle through them) TightVNC also plan to support such a feature.. (When , no idea) This feature is important as if you have large multi monitors and connecting over a reasonably slow link.. The screen updates are just to slow.. Cutting down to one monitor to focus on is desirable.

I like tightVNC, but UltraVNC seems to have a few more features right now..

I have found tightVNC more solid. And that is why I have stuck with it.

I would try both. They both work well, but I imagine one would suite slightly more then the other.

Unzip All Files In A Directory

Use

sudo apt-get install unzip 

unzip file.zip -d path_to_destination_folder

to unzip a folder in linux

How to change facet labels?

Have you tried changing the specific levels of your Hospital vector?

levels(survey$hospital)[levels(survey$hospital) == "Hospital #1"] <- "Hosp 1"
levels(survey$hospital)[levels(survey$hospital) == "Hospital #2"] <- "Hosp 2"
levels(survey$hospital)[levels(survey$hospital) == "Hospital #3"] <- "Hosp 3"

Get hostname of current request in node.js Express

Here's an alternate

req.hostname

Read about it in the Express Docs.

Oracle Add 1 hour in SQL

select sysdate + 1/24 from dual;

sysdate is a function without arguments which returns DATE type
+ 1/24 adds 1 hour to a date

select to_char(to_date('2014-10-15 03:30:00 pm', 'YYYY-MM-DD HH:MI:SS pm') + 1/24, 'YYYY-MM-DD HH:MI:SS pm') from dual;

How to close a web page on a button click, a hyperlink or a link button click?

To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.

What does random.sample() method in python do?

According to documentation:

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Basically, it picks k unique random elements, a sample, from a sequence:

>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]

random.sample works also directly from a range:

>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]

In addition to sequences, random.sample works with sets too:

>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]

However, random.sample doesn't work with arbitrary iterators:

>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set.  For dicts, use list(d).

System.currentTimeMillis vs System.nanoTime

one thing here is the inconsistency of the nanoTime method.it does not give very consistent values for the same input.currentTimeMillis does much better in terms of performance and consistency,and also ,though not as precise as nanoTime,has a lower margin of error,and therefore more accuracy in its value. i would therefore suggest that you use currentTimeMillis

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

Possible to iterate backwards through a foreach?

As 280Z28 says, for an IList<T> you can just use the index. You could hide this in an extension method:

public static IEnumerable<T> FastReverse<T>(this IList<T> items)
{
    for (int i = items.Count-1; i >= 0; i--)
    {
        yield return items[i];
    }
}

This will be faster than Enumerable.Reverse() which buffers all the data first. (I don't believe Reverse has any optimisations applied in the way that Count() does.) Note that this buffering means that the data is read completely when you first start iterating, whereas FastReverse will "see" any changes made to the list while you iterate. (It will also break if you remove multiple items between iterations.)

For general sequences, there's no way of iterating in reverse - the sequence could be infinite, for example:

public static IEnumerable<T> GetStringsOfIncreasingSize()
{
    string ret = "";
    while (true)
    {
        yield return ret;
        ret = ret + "x";
    }
}

What would you expect to happen if you tried to iterate over that in reverse?

How to enter newline character in Oracle?

Chr(Number) should work for you.

select 'Hello' || chr(10) ||' world' from dual

Remember different platforms expect different new line characters:

  • CHR(10) => LF, line feed (unix)
  • CHR(13) => CR, carriage return (windows, together with LF)

Difference between "module.exports" and "exports" in the CommonJs Module System

Also, one things that may help to understand:

math.js

this.add = function (a, b) {
    return a + b;
};

client.js

var math = require('./math');
console.log(math.add(2,2); // 4;

Great, in this case:

console.log(this === module.exports); // true
console.log(this === exports); // true
console.log(module.exports === exports); // true

Thus, by default, "this" is actually equals to module.exports.

However, if you change your implementation to:

math.js

var add = function (a, b) {
    return a + b;
};

module.exports = {
    add: add
};

In this case, it will work fine, however, "this" is not equal to module.exports anymore, because a new object was created.

console.log(this === module.exports); // false
console.log(this === exports); // true
console.log(module.exports === exports); // false

And now, what will be returned by the require is what was defined inside the module.exports, not this or exports, anymore.

Another way to do it would be:

math.js

module.exports.add = function (a, b) {
    return a + b;
};

Or:

math.js

exports.add = function (a, b) {
    return a + b;
};

App.settings - the Angular way?

If you are using , there is yet another option:

Angular CLI provides environment files in src/environments (default ones are environment.ts (dev) and environment.prod.ts (production)).

Note that you need to provide the config parameters in all environment.* files, e.g.,

environment.ts:

export const environment = {
  production: false,
  apiEndpoint: 'http://localhost:8000/api/v1'
};

environment.prod.ts:

export const environment = {
  production: true,
  apiEndpoint: '__your_production_server__'
};

and use them in your service (the correct environment file is chosen automatically):

api.service.ts

// ... other imports
import { environment } from '../../environments/environment';

@Injectable()
export class ApiService {     

  public apiRequest(): Observable<MyObject[]> {
    const path = environment.apiEndpoint + `/objects`;
    // ...
  }

// ...
}

Read more on application environments on Github (Angular CLI version 6) or in the official Angular guide (version 7).

Dynamically creating keys in a JavaScript associative array

The original code (I added the line numbers so can refer to them):

1  var text = ' name = oscar '
2  var dict = new Array();
3  var keyValuePair = text.split(' = ');
4  dict[ keyValuePair[0] ] = 'whatever';
5  alert( dict ); // Prints nothing.

Almost there...

  • line 1: you should do a trim on text so it is name = oscar.

  • line 3: okay as long as you always have spaces around your equal. It might be better to not trim in line 1. Use = and trim each keyValuePair

  • add a line after 3 and before 4:

      key = keyValuePair[0];`
    
  • line 4: Now becomes:

      dict[key] = keyValuePair[1];
    
  • line 5: Change to:

      alert( dict['name'] );  // It will print out 'oscar'
    

I'm trying to say that the dict[keyValuePair[0]] does not work. You need to set a string to keyValuePair[0] and use that as the associative key. That is the only way I got mine to work. After you have set it up, you can either refer to it with numeric index or key in quotes.

Script to get the HTTP status code of a list of urls?

wget --spider -S "http://url/to/be/checked" 2>&1 | grep "HTTP/" | awk '{print $2}'

prints only the status code for you

Blur effect on a div element

I got blur working with SVG blur filter:

CSS

-webkit-filter: url(#svg-blur);
        filter: url(#svg-blur);

SVG

<svg id="svg-filter">
    <filter id="svg-blur">
        <feGaussianBlur in="SourceGraphic" stdDeviation="4"></feGaussianBlur>
    </filter>
</svg>

Working example:

https://jsfiddle.net/1k5x6dgm/

Please note - this will not work in IE versions

how to convert .java file to a .class file

From the command line, run

javac ClassName.java

How To Make Circle Custom Progress Bar in Android

I have solved this cool custom progress bar by creating the custom view. I have overriden the onDraw() method to draw the circles, filled arc and text on the canvas.

following is the custom progress bar

import android.annotation.TargetApi;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.graphics.Path;

import android.graphics.Rect;

import android.graphics.RectF;

import android.os.Build;

import android.util.AttributeSet;

import android.view.View;

import com.investorfinder.utils.UiUtils;


public class CustomProgressBar extends View {


private int max = 100;

private int progress;

private Path path = new Path();

int color = 0xff44C8E5;

private Paint paint;

private Paint mPaintProgress;

private RectF mRectF;

private Paint textPaint;

private String text = "0%";

private final Rect textBounds = new Rect();

private int centerY;

private int centerX;

private int swipeAndgle = 0;


public CustomProgressBar(Context context) {
    super(context);
    initUI();
}

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

public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initUI();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    initUI();
}

private void initUI() {
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStrokeWidth(UiUtils.dpToPx(getContext(), 1));
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(color);


    mPaintProgress = new Paint();
    mPaintProgress.setAntiAlias(true);
    mPaintProgress.setStyle(Paint.Style.STROKE);
    mPaintProgress.setStrokeWidth(UiUtils.dpToPx(getContext(), 9));
    mPaintProgress.setColor(color);

    textPaint = new Paint();
    textPaint.setAntiAlias(true);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(color);
    textPaint.setStrokeWidth(2);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
    int viewHeight = MeasureSpec.getSize(heightMeasureSpec);

    int radius = (Math.min(viewWidth, viewHeight) - UiUtils.dpToPx(getContext(), 2)) / 2;

    path.reset();

    centerX = viewWidth / 2;
    centerY = viewHeight / 2;
    path.addCircle(centerX, centerY, radius, Path.Direction.CW);

    int smallCirclRadius = radius - UiUtils.dpToPx(getContext(), 7);
    path.addCircle(centerX, centerY, smallCirclRadius, Path.Direction.CW);
    smallCirclRadius += UiUtils.dpToPx(getContext(), 4);

    mRectF = new RectF(centerX - smallCirclRadius, centerY - smallCirclRadius, centerX + smallCirclRadius, centerY + smallCirclRadius);

    textPaint.setTextSize(radius * 0.5f);
}


@Override
protected void onDraw(Canvas canvas) {


    super.onDraw(canvas);

    canvas.drawPath(path, paint);

    canvas.drawArc(mRectF, 270, swipeAndgle, false, mPaintProgress);

    drawTextCentred(canvas);

}

public void drawTextCentred(Canvas canvas) {

    textPaint.getTextBounds(text, 0, text.length(), textBounds);

    canvas.drawText(text, centerX - textBounds.exactCenterX(), centerY - textBounds.exactCenterY(), textPaint);
}

public void setMax(int max) {
    this.max = max;
}

public void setProgress(int progress) {
    this.progress = progress;

    int percentage = progress * 100 / max;

    swipeAndgle = percentage * 360 / 100;

    text = percentage + "%";

    invalidate();
}

public void setColor(int color) {
    this.color = color;
}
}

In layout XML

<com.your.package.name.CustomProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/txt_title"
            android:layout_marginRight="15dp" />

in activity

CustomProgressBar progressBar = (CustomProgressBar)findViewById(R.id.progress_bar);

    progressBar.setMax(9);

    progressBar.setProgress(5);

IBOutlet and IBAction

Ran into the diagram while looking at key-value coding, thought it might help someone. It helps with understanding of what IBOutlet is.

By looking at the flow, one could see that IBOutlets are only there to match the property name with a control name in the Nib file.

How nib file is loaded, screenshot of Matt's online book for iOS6

Reading Excel file using node.js

Useful link

https://ciphertrick.com/read-excel-files-convert-json-node-js/

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

How to utilize date add function in Google spreadsheet?

As with @kidbrax's answer, you can use the + to add days. To get this to work I had to explicitly declare my cell data as being a date:

A1: =DATE(2014, 03, 28)

A2: =A1+1

Value of A2 is now 29th March 2014

jQuery set radio button

You can try the following code:

$("input[name=cols][value=" + value + "]").attr('checked', 'checked');

This will set the attribute checked for the radio columns and value as specified.

How do I revert an SVN commit?

svn merge -r 1944:1943 . should revert the changes of r1944 in your working copy. You can then review the changes in your working copy (with diff), but you'd need to commit in order to apply the revert into the repository.

how to re-format datetime string in php?

why not use date() just like below,try this

$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);

and will be output

09/04/13 16:37:05

List of all index & index columns in SQL Server DB

I came up with this one, which is giving me the exact overview I need. What is helps is that you get one row per index into which the index columns are aggregated.

select 
    o.name as ObjectName, 
    i.name as IndexName, 
    i.is_primary_key as [PrimaryKey],
    SUBSTRING(i.[type_desc],0,6) as IndexType,
    i.is_unique as [Unique],
    Columns.[Normal] as IndexColumns,
    Columns.[Included] as IncludedColumns
from sys.indexes i 
join sys.objects o on i.object_id = o.object_id
cross apply
(
    select
        substring
        (
            (
                select ', ' + co.[name]
                from sys.index_columns ic
                join sys.columns co on co.object_id = i.object_id and co.column_id = ic.column_id
                where ic.object_id = i.object_id and ic.index_id = i.index_id and ic.is_included_column = 0
                order by ic.key_ordinal
                for xml path('')
            )
            , 3
            , 10000
        )    as [Normal]    
        , substring
        (
            (
                select ', ' + co.[name]
                from sys.index_columns ic
                join sys.columns co on co.object_id = i.object_id and co.column_id = ic.column_id
                where ic.object_id = i.object_id and ic.index_id = i.index_id and ic.is_included_column = 1
                order by ic.key_ordinal
                for xml path('')
            )
            , 3
            , 10000
        )    as [Included]    

) Columns
where o.[type] = 'U' --USER_TABLE
order by o.[name], i.[name], i.is_primary_key desc

In Typescript, How to check if a string is Numeric

function isNumber(value: string | number): boolean
{
   return ((value != null) &&
           (value !== '') &&
           !isNaN(Number(value.toString())));
}

Laravel 5 – Remove Public from URL

Create A .htaccess file in your root DIR and paste the below code. That's it :P

_x000D_
_x000D_
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1 

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
_x000D_
_x000D_
_x000D_

A regular expression to exclude a word/string

As you want to exclude both words, you need a conjuction:

^/(?!ignoreme$)(?!ignoreme2$)[a-z0-9]+$

Now both conditions must be true (neither ignoreme nor ignoreme2 is allowed) to have a match.

Install pip in docker

An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine. They offer pip out of the box (and have a smaller footprint which leads to faster builds etc).

Align DIV to bottom of the page

Try position:fixed; bottom:0;. This will make your div to stay fixed at the bottom.

WORKING DEMO

The HTML:

<div id="bottom-stuff">
  <div id="search"> MY DIV </div>
</div>
<div id="bottom"> MY DIV </div>

The CSS:

#bottom-stuff {

    position: relative;
}

#bottom{

    position: fixed; 
    background:gray; 
    width:100%;
    bottom:0;
}

#search{height:5000px; overflow-y:scroll;}

Hope this helps.

How to check for null in Twig?

You can also use one line to do that:

{{ yourVariable is not defined ? "Not Assigned" : "Assigned" }}

failed to find target with hash string android-23

Download the specific Android release from the link specified in the build console.

Use PHP to create, edit and delete crontab jobs?

Its simple You can you curl to do so, make sure curl installed on server :

for triggering every minute : * * * * * curl --request POST 'https://glassdoor.com/admin/sendBdayNotification'

        • *

    minute hour day month week

Let say you want to send this notification 2:15 PM everyday You may change POST/GET based on your API:

15 14 * * * curl --request POST 'url of ur API'

How do I get the path of the assembly the code is in?

Same as John's answer, but a slightly less verbose extension method.

public static string GetDirectoryPath(this Assembly assembly)
{
    string filePath = new Uri(assembly.CodeBase).LocalPath;
    return Path.GetDirectoryName(filePath);            
}

Now you can do:

var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();

or if you prefer:

var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();

When to use Hadoop, HBase, Hive and Pig?

First of all we should get clear that Hadoop was created as a faster alternative to RDBMS. To process large amount of data at a very fast rate which earlier took a lot of time in RDBMS.

Now one should know the two terms :

  1. Structured Data : This is the data that we used in traditional RDBMS and is divided into well defined structures.

  2. Unstructured Data : This is important to understand, about 80% of the world data is unstructured or semi structured. These are the data which are on its raw form and cannot be processed using RDMS. Example : facebook, twitter data. (http://www.dummies.com/how-to/content/unstructured-data-in-a-big-data-environment.html).

So, large amount of data was being generated in the last few years and the data was mostly unstructured, that gave birth to HADOOP. It was mainly used for very large amount of data that takes unfeasible amount of time using RDBMS. It had many drawbacks, that it could not be used for comparatively small data in real time but they have managed to remove its drawbacks in the newer version.

Before going further I would like to tell that a new Big Data tool is created when they see a fault on the previous tools. So, whichever tool you will see that is created has been done to overcome the problem of the previous tools.

Hadoop can be simply said as two things : Mapreduce and HDFS. Mapreduce is where the processing takes place and HDFS is the DataBase where data is stored. This structure followed WORM principal i.e. write once read multiple times. So, once we have stored data in HDFS, we cannot make changes. This led to the creation of HBASE, a NOSQL product where we can make changes in the data also after writing it once.

But with time we saw that Hadoop had many faults and for that we created different environment over the Hadoop structure. PIG and HIVE are two popular examples.

HIVE was created for people with SQL background. The queries written is similar to SQL named as HIVEQL. HIVE was developed to process completely structured data. It is not used for ustructured data.

PIG on the other hand has its own query language i.e. PIG LATIN. It can be used for both structured as well as unstructured data.

Moving to the difference as when to use HIVE and when to use PIG, I don't think anyone other than the architect of PIG could say. Follow the link : https://developer.yahoo.com/blogs/hadoop/comparing-pig-latin-sql-constructing-data-processing-pipelines-444.html

PHP - remove <img> tag from string

Sean it works fine i've just used this code

$content = preg_replace("/<img[^>]+\>/i", " ", $content); 
echo $content;

//the result it's only the plain text. It works!!!

\n or \n in php echo not print

Escape sequences (and variables too) work inside double quoted and heredoc strings. So change your code to:

echo '<p>' . $unit1 . "</p>\n";

PS: One clarification, single quotes strings do accept two escape sequences:

  • \' when you want to use single quote inside single quoted strings
  • \\ when you want to use backslash literally

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

How do you decompile a swf file

Get the Sothink SWF decompiler. Not free, but worth it. Recently used it to decompile an SWF that I had lost the fla for, and I could completely round-trip swf-fla and back!
link text

Why is Tkinter Entry's get function returning nothing?

*

master = Tk()
entryb1 = StringVar

Label(master, text="Input: ").grid(row=0, sticky=W)

Entry(master, textvariable=entryb1).grid(row=1, column=1)

b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)

def print_content():
    global entryb1
    content = entryb1.get()
    print(content)

master.mainloop()

What you did wrong was not put it inside a Define function then you hadn't used the .get function with the textvariable you had set.

How eliminate the tab space in the column in SQL Server 2008

Try this code

SELECT REPLACE([Column], char(9), '') From [dbo.Table] 

char(9) is the TAB character

Getting mouse position in c#

Cursor.Position will get the current screen poisition of the mouse (if you are in a Control, the MousePosition property will also get the same value).

To set the mouse position, you will have to use Cursor.Position and give it a new Point:

Cursor.Position = new Point(x, y);

You can do this in your Main method before creating your form.

How can I break up this long line in Python?

For anyone who is also trying to call .format() on a long string, and is unable to use some of the most popular string wrapping techniques without breaking the subsequent .format( call, you can do str.format("", 1, 2) instead of "".format(1, 2). This lets you break the string with whatever technique you like. For example:

logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title))

can be

logger.info(str.format(("Skipping {0} because its thumbnail was already"
+ "in our system as {1}"), line[indexes['url']], video.title))

Otherwise, the only possibility is using line ending continuations, which I personally am not a fan of.

How Connect to remote host from Aptana Studio 3

From the Project Explorer, expand the project you want to hook up to a remote site (or just right click and create a new Web project that's empty if you just want to explore a remote site from there). There's a "Connections" node, right click it and select "Add New connection...". A dialog will appear, at bottom you can select the destination as Remote and then click the "New..." button. There you can set up an FTP/FTPS/SFTP connection.

That's how you set up a connection that's tied to a project, typically for upload/download/sync between it and a project.

You can also do Window > Show View > Remote. From that view, you can click the globe icon in the upper right to add connections and in this view you can just browse your remote connections.

PowerShell script to return members of multiple security groups

This will give you a list of a single group, and the members of each group.

param
(   
    [Parameter(Mandatory=$true,position=0)]
    [String]$GroupName
)

import-module activedirectory

# optional, add a wild card..
# $groups = $groups + "*"

$Groups = Get-ADGroup -filter {Name -like $GroupName} | Select-Object Name

ForEach ($Group in $Groups)
   {write-host " "
    write-host "$($group.name)"
    write-host "----------------------------"

    Get-ADGroupMember -identity $($groupname) -recursive | Select-Object samaccountname

 }
write-host "Export Complete"

If you want the friendly name, or other details, add them to the end of the select-object query.

"No rule to make target 'install'"... But Makefile exists

I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install. When I changed to the directory that had my makefile it worked.

So possibly you aren't in the right directory.

Imported a csv-dataset to R but the values becomes factors

None of these answers mention the colClasses argument which is another way to specify the variable classes in read.csv.

 stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "numeric") # all variables to numeric

or you can specify which columns to convert:

stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = c("PTS" = "numeric", "MP" = "numeric") # specific columns to numeric

Note that if a variable can't be converted to numeric then it will be converted to factor as default which makes it more difficult to convert to number. Therefore, it can be advisable just to read all variables in as 'character' colClasses = "character" and then convert the specific columns to numeric once the csv is read in:

stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "character")
point <- as.numeric(stuckey$PTS)
time <- as.numeric(stuckey$MP)

How to get response body using HttpURLConnection, when code other than 2xx is returned?

If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream().

Linear Layout and weight in Android

3 things to remember:

  • set the android:layout_width of the children to "0dp"
  • set the android:weightSum of the parent (edit: as Jason Moore noticed, this attribute is optional, because by default it is set to the children's layout_weight sum)
  • set the android:layout_weight of each child proportionally (e.g. weightSum="5", three children: layout_weight="1", layout_weight="3", layout_weight="1")

Example:

    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="5">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="2" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

    </LinearLayout>

And the result:

Layout weight example

Wait until a process ends

Try this:

string command = "...";
var process = Process.Start(command);
process.WaitForExit();

Conditional step/stage in Jenkins pipeline

Doing the same in declarative pipeline syntax, below are few examples:

stage('master-branch-stuff') {
    when {
        branch 'master'
    }
    steps {
        echo 'run this stage - ony if the branch = master branch'
    }
}

stage('feature-branch-stuff') {
    when {
        branch 'feature/*'
    }
    steps {
        echo 'run this stage - only if the branch name started with feature/'
    }
}

stage('expression-branch') {
    when {
        expression {
            return env.BRANCH_NAME != 'master';
        }
    }
    steps {
        echo 'run this stage - when branch is not equal to master'
    }
}

stage('env-specific-stuff') {
    when { 
        environment name: 'NAME', value: 'this' 
    }
    steps {
        echo 'run this stage - only if the env name and value matches'
    }
}

More effective ways coming up - https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at - https://jenkins.io/doc/book/pipeline/syntax/#when


The directive beforeAgent true can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:

when { beforeAgent true; expression { return isStageConfigured(config) } }

Release post and docs


UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative

equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.

changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.

buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.

tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.

File opens instead of downloading in internet explorer in a href link

This must be a matter of http headers.

see here: HTTP Headers for File Downloads

The server should tell your browser to download the file by sending

Content-Type: application/octet-stream; 
Content-Disposition: attachment;

in the headers

Return HTTP status code 201 in flask

Dependent on how the API is created, normally with a 201 (created) you would return the resource which was created. For example if it was creating a user account you would do something like:

return {"data": {"username": "test","id":"fdsf345"}}, 201

Note the postfixed number is the status code returned.

Alternatively, you may want to send a message to the client such as:

return {"msg": "Created Successfully"}, 201

Check/Uncheck all the checkboxes in a table

All CheckBox Checked

$("input[type=checkbox]").prop('checked', true);

Empty an array in Java / processing

You can simply assign null to the reference. (This will work for any type of array, not just ints)

int[] arr = new int[]{1, 2, 3, 4};
arr = null;

This will 'clear out' the array. You can also assign a new array to that reference if you like:

int[] arr = new int[]{1, 2, 3, 4};
arr = new int[]{6, 7, 8, 9};

If you are worried about memory leaks, don't be. The garbage collector will clean up any references left by the array.

Another example:

float[] arr = ;// some array that you want to clear
arr = new float[arr.length];

This will create a new float[] initialized to the default value for float.

Get the client IP address using PHP

It also works fine for internal IP addresses:

 function get_client_ip()
 {
      $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
          $ipaddress = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $ipaddress = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
          $ipaddress = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $ipaddress = getenv('REMOTE_ADDR');
      else
          $ipaddress = 'UNKNOWN';

      return $ipaddress;
 }

How to select a column name with a space in MySQL

Generally the first step is to not do that in the first place, but if this is already done, then you need to resort to properly quoting your column names:

SELECT `Business Name` FROM annoying_table

Usually these sorts of things are created by people who have used something like Microsoft Access and always use a GUI to do their thing.

Textarea onchange detection

I know this isn't exactly your question but I thought this might be useful. For certain applications it is nice to have the change function fire not every single time a key is pressed. This can be achieved with something like this:

var text = document.createElement('textarea');
text.rows = 10;
text.cols = 40;
document.body.appendChild(text);

text.onkeyup = function(){
var callcount = 0;
    var action = function(){
        alert('changed');
    }
    var delayAction = function(action, time){
        var expectcallcount = callcount;
        var delay = function(){
            if(callcount == expectcallcount){
                action();
            }
        }
        setTimeout(delay, time);
    }
    return function(eventtrigger){
        ++callcount;
        delayAction(action, 1200);
    }
}();

This works by testing if a more recent event has fired within a certain delay period. Good luck!

How to get directory size in PHP

There are several things you could do to optimise the script - but maximum success would make it IO-bound rather than CPU-bound:

  1. Calculate rtrim($path, '/') outside the loop.
  2. make if ($t<>"." && $t<>"..") the outer test - it doesn't need to stat the path
  3. Calculate rtrim($path, '/') . '/' . $t once per loop - inside 2) and taking 1) into account.
  4. Calculate explode(' ','B KB MB GB TB PB'); once rather than each call?

DynamoDB vs MongoDB NoSQL

Bear in mind, I've only experimented with MongoDB...

From what I've read, DynamoDB has come a long way in terms of features. It used to be a super-basic key-value store with extremely limited storage and querying capabilities. It has since grown, now supporting bigger document sizes + JSON support and global secondary indices. The gap between what DynamoDB and MongoDB offers in terms of features grows smaller with every month. The new features of DynamoDB are expanded on here.

Much of the MongoDB vs. DynamoDB comparisons are out of date due to the recent addition of DynamoDB features. However, this post offers some other convincing points to choose DynamoDB, namely that it's simple, low maintenance, and often low cost. Another discussion here of database choices was interesting to read, though slightly old.

My takeaway: if you're doing serious database queries or working in languages not supported by DynamoDB, use MongoDB. Otherwise, stick with DynamoDB.

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.

Where's the DateTime 'Z' format specifier?

When you use DateTime you are able to store a date and a time inside a variable.

The date can be a local time or a UTC time, it depend on you.

For example, I'm in Italy (+2 UTC)

var dt1 = new DateTime(2011, 6, 27, 12, 0, 0); // store 2011-06-27 12:00:00
var dt2 = dt1.ToUniversalTime()  // store 2011-06-27 10:00:00

So, what happen when I print dt1 and dt2 including the timezone?

dt1.ToString("MM/dd/yyyy hh:mm:ss z") 
// Compiler alert...
// Output: 06/27/2011 12:00:00 +2

dt2.ToString("MM/dd/yyyy hh:mm:ss z") 
// Compiler alert...
// Output: 06/27/2011 10:00:00 +2

dt1 and dt2 contain only a date and a time information. dt1 and dt2 don't contain the timezone offset.

So where the "+2" come from if it's not contained in the dt1 and dt2 variable?

It come from your machine clock setting.

The compiler is telling you that when you use the 'zzz' format you are writing a string that combine "DATE + TIME" (that are store in dt1 and dt2) + "TIMEZONE OFFSET" (that is not contained in dt1 and dt2 because they are DateTyme type) and it will use the offset of the server machine that it's executing the code.

The compiler tell you "Warning: the output of your code is dependent on the machine clock offset"

If i run this code on a server that is positioned in London (+1 UTC) the result will be completly different: instead of "+2" it will write "+1"

...
dt1.ToString("MM/dd/yyyy hh:mm:ss z") 
// Output: 06/27/2011 12:00:00 +1

dt2.ToString("MM/dd/yyyy hh:mm:ss z") 
// Output: 06/27/2011 10:00:00 +1

The right solution is to use DateTimeOffset data type in place of DateTime. It's available in sql Server starting from the 2008 version and in the .Net framework starting from the 3.5 version

Why does Java's hashCode() in String use 31 as a multiplier?

According to Joshua Bloch's Effective Java (a book that can't be recommended enough, and which I bought thanks to continual mentions on stackoverflow):

The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.

(from Chapter 3, Item 9: Always override hashcode when you override equals, page 48)

AngularJS sorting by property

It's pretty easy, just do it like this

$scope.props = [{order:"1"},{order:"5"},{order:"2"}]

ng-repeat="prop in props | orderBy:'order'"

How to update parent's state in React?

<Footer 
  action={()=>this.setState({showChart: true})}
/>

<footer className="row">
    <button type="button" onClick={this.props.action}>Edit</button>
  {console.log(this.props)}
</footer>

Try this example to write inline setState, it avoids creating another function.

Commenting in a Bash script inside a multiline command

This will have some overhead, but technically it does answer your question:

echo abc `#Put your comment here` \
     def `#Another chance for a comment` \
     xyz, etc.

And for pipelines specifically, there is a clean solution with no overhead:

echo abc |        # Normal comment OK here
     tr a-z A-Z | # Another normal comment OK here
     sort |       # The pipelines are automatically continued
     uniq         # Final comment

See Stack Overflow question How to Put Line Comment for a Multi-line Command.

Replace Div Content onclick

A simple addClass and removeClass will do the trick on what you need..

$('#change').on('click', function() { 
  $('div').each(function() { 
    if($(this).hasClass('active')) { 
        $(this).removeClass('active');
    } else { 
        $(this).addClass('active');
    }
});

});

Seee fiddle

I recommend you to learn jquery first before using.

Is it possible to output a SELECT statement from a PL/SQL block?

use execute immediate statement

like:

declare
 var1    integer;
var2 varchar2(200)
begin
 execute immediate 'select emp_id,emp_name from emp'
   into var1,var2;
 dbms_output.put_line(var1 || var2);
end;

Running a command in a new Mac OS X Terminal window

I call this script trun. I suggest putting it in a directory in your executable path. Make sure it is executable like this:

chmod +x ~/bin/trun

Then you can run commands in a new window by just adding trun before them, like this:

trun tail -f /var/log/system.log

Here's the script. It does some fancy things like pass your arguments, change the title bar, clear the screen to remove shell startup clutter, remove its file when its done. By using a unique file for each new window it can be used to create many windows at the same time.

#!/bin/bash
# make this file executable with chmod +x trun
# create a unique file in /tmp
trun_cmd=`mktemp`
# make it cd back to where we are now
echo "cd `pwd`" >$trun_cmd
# make the title bar contain the command being run
echo 'echo -n -e "\033]0;'$*'\007"' >>$trun_cmd
# clear window
echo clear >>$trun_cmd
# the shell command to execute
echo $* >>$trun_cmd
# make the command remove itself
echo rm $trun_cmd >>$trun_cmd
# make the file executable
chmod +x $trun_cmd

# open it in Terminal to run it in a new Terminal window
open -b com.apple.terminal $trun_cmd

PHP Unset Array value effect on other indexes

They are as they were. That one key is JUST DELETED

In PHP, how do you change the key of an array element?

$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);

How can INSERT INTO a table 300 times within a loop in SQL?

Found some different answers that I combined to solve simulair problem:

CREATE TABLE nummer (ID INTEGER PRIMARY KEY, num, text, text2);
WITH RECURSIVE
  for(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM for WHERE i < 1000000)
INSERT INTO nummer SELECT i, i+1, "text" || i, "otherText" || i FROM for;

Adds 1 miljon rows with

  • id increased by one every itteration
  • num one greater then id
  • text concatenated with id-number like: text1, text2 ... text1000000
  • text2 concatenated with id-number like: otherText1, otherText2 ... otherText1000000

How can I read user input from the console?

Sometime in the future .NET4.6

//for Double
double inputValues = double.Parse(Console.ReadLine());

//for Int
int inputValues = int.Parse(Console.ReadLine());

How to find first element of array matching a boolean condition in JavaScript?

A less elegant way that will throw all the right error messages (based on Array.prototype.filter) but will stop iterating on the first result is

function findFirst(arr, test, context) {
    var Result = function (v, i) {this.value = v; this.index = i;};
    try {
        Array.prototype.filter.call(arr, function (v, i, a) {
            if (test(v, i, a)) throw new Result(v, i);
        }, context);
    } catch (e) {
        if (e instanceof Result) return e;
        throw e;
    }
}

Then examples are

findFirst([-2, -1, 0, 1, 2, 3], function (e) {return e > 1 && e % 2;});
// Result {value: 3, index: 5}
findFirst([0, 1, 2, 3], 0);               // bad function param
// TypeError: number is not a function
findFirst(0, function () {return true;}); // bad arr param
// undefined
findFirst([1], function (e) {return 0;}); // no match
// undefined

It works by ending filter by using throw.

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

Check if you also installed the "Google Repository". If not, you also have to install the "Google Repository" in your SDK Manager.

Also be aware that there might be 2 SDK installations - one coming from AndroidStudio and one you might have installed. Better consolidate this to one installation - this is a common pitfall - that you have it installed in one installation but it fails when you build with the other installation.

Example of how to access SDK Manager for Google Repository

How to enter in a Docker container already running with a new TTY

First step get container id:

docker ps

This will show you something like

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

1170fe9e9460 localhost:5000/python:env-7e847468c4d73a0f35e9c5164046ad88 "./run_notebook.sh" 26 seconds ago Up 25 seconds 0.0.0.0:8989->9999/tcp SLURM_TASK-303337_0

1170fe9e9460 is the container id in this case.

Second, enter the docker :

docker exec -it [container_id] bash

so in the above case: docker exec -it 1170fe9e9460 bash

HTML5 Video Stop onClose

Try this:

if ($.browser.msie)
{
   // Some other solution as applies to whatever IE compatible video player used.
}
else
{
   $('video')[0].pause();
}

But, consider that $.browser is deprecated, but I haven't found a comparable solution.

Quick unix command to display specific lines in the middle of a file?

sed will need to read the data too to count the lines. The only way a shortcut would be possible would there to be context/order in the file to operate on. For example if there were log lines prepended with a fixed width time/date etc. you could use the look unix utility to binary search through the files for particular dates/times

vertical-align image in div

If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.

Here's an example: http://jsfiddle.net/Cthulhu/QHEnL/1/

EDIT

Your code should look like this:

.img_thumb {
    float: left;
    height: 120px;
    margin-bottom: 5px;
    margin-left: 9px;
    position: relative;
    width: 147px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 3px;
    line-height:120px;
    text-align:center;
}

.img_thumb img {
    vertical-align: middle;
}

The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:

http://jsfiddle.net/Cthulhu/QHEnL/6/

http://jsfiddle.net/Cthulhu/QHEnL/7/

UPDATE

It's now 2016 (the future!) and looks like a few things are changing (finally!!).

Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).

Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.

With that being said, here's an updated way of aligning elements, both horizontally and vertically:

.container {
    position: relative;
}

.container .element {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

Using this transform: translate(); method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.

If you only need to center in one dimension, you can use translateY or translateX. Just try it for a while and you'll see how it works. Also, try to change the values of the translate, you will find it useful for a bunch of different situations.

Here, have a new fiddle: https://jsfiddle.net/Cthulhu/1xjbhsr4/

For more information on transform, here's a good resource.

Happy coding.

Is it possible to style a select box?

Update: As of 2013 the two I've seen that are worth checking are:

  • Chosen - loads of cool stuff, 7k+ watchers on github. (mentioned by 'a paid nerd' in the comments)
  • Select2 - inspired by Chosen, part of Angular-UI with a couple useful tweaks on Chosen.

Yeah!


As of 2012 one of the most lightweight, flexible solutions I've found is ddSlick. Relevant (edited) info from the site:

  • Adds images and text to select options
  • Can use JSON to populate options
  • Supports callback functions on selection

And here's a preview of the various modes:

enter image description here

When is JavaScript synchronous?

JavaScript is single-threaded, and all the time you work on a normal synchronous code-flow execution.

Good examples of the asynchronous behavior that JavaScript can have are events (user interaction, Ajax request results, etc) and timers, basically actions that might happen at any time.

I would recommend you to give a look to the following article:

That article will help you to understand the single-threaded nature of JavaScript and how timers work internally and how asynchronous JavaScript execution works.

async

Creating a UITableView Programmatically

- (void)viewDidLoad
{
    [super viewDidLoad];
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;

    tableView.backgroundColor = [UIColor grayColor];

    // add to superview
    [self.view addSubview:tableView];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:    (NSInteger)section
{
    return 1;
}

// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    // Similar to UITableViewCell, but 
    UITableViewCell *cell = (UITableViewCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.descriptionLabel.text = @"Testing";
    return cell;
}

Push Notifications in Android Platform

Google's official answer is the Android Cloud to Device Messaging Framework (deprecated) Google Cloud Messaging(deprecated) Firebase Cloud Messaging

It will work on Android >= 2.2 (on phones that have the Play Store).

How to download a branch with git?

We can download a specified branch by using following magical command:

git clone -b < branch name > <remote_repo url> 

How to rename HTML "browse" button of an input type=file?

<script language="JavaScript" type="text/javascript">
function HandleBrowseClick()
{
    var fileinput = document.getElementById("browse");
    fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("browse");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>

<input type="file" id="browse" name="fileupload" style="display: none" onChange="Handlechange();"/>
<input type="text" id="filename" readonly="true"/>
<input type="button" value="Click to select file" id="fakeBrowse" onclick="HandleBrowseClick();"/>

http://jsfiddle.net/J8ekg/

Reference excel worksheet by name?

There are several options, including using the method you demonstrate, With, and using a variable.

My preference is option 4 below: Dim a variable of type Worksheet and store the worksheet and call the methods on the variable or pass it to functions, however any of the options work.

Sub Test()
  Dim SheetName As String
  Dim SearchText As String
  Dim FoundRange As Range

  SheetName = "test"      
  SearchText = "abc"

  ' 0. If you know the sheet is the ActiveSheet, you can use if directly.
  Set FoundRange = ActiveSheet.UsedRange.Find(What:=SearchText)
  ' Since I usually have a lot of Subs/Functions, I don't use this method often.
  ' If I do, I store it in a variable to make it easy to change in the future or
  ' to pass to functions, e.g.: Set MySheet = ActiveSheet
  ' If your methods need to work with multiple worksheets at the same time, using
  ' ActiveSheet probably isn't a good idea and you should just specify the sheets.

  ' 1. Using Sheets or Worksheets (Least efficient if repeating or calling multiple times)
  Set FoundRange = Sheets(SheetName).UsedRange.Find(What:=SearchText)
  Set FoundRange = Worksheets(SheetName).UsedRange.Find(What:=SearchText)

  ' 2. Using Named Sheet, i.e. Sheet1 (if Worksheet is named "Sheet1"). The
  ' sheet names use the title/name of the worksheet, however the name must
  ' be a valid VBA identifier (no spaces or special characters. Use the Object
  ' Browser to find the sheet names if it isn't obvious. (More efficient than #1)
  Set FoundRange = Sheet1.UsedRange.Find(What:=SearchText)

  ' 3. Using "With" (more efficient than #1)
  With Sheets(SheetName)
    Set FoundRange = .UsedRange.Find(What:=SearchText)
  End With
  ' or possibly...
  With Sheets(SheetName).UsedRange
    Set FoundRange = .Find(What:=SearchText)
  End With

  ' 4. Using Worksheet variable (more efficient than 1)
  Dim MySheet As Worksheet
  Set MySheet = Worksheets(SheetName)
  Set FoundRange = MySheet.UsedRange.Find(What:=SearchText)

  ' Calling a Function/Sub
  Test2 Sheets(SheetName) ' Option 1
  Test2 Sheet1 ' Option 2
  Test2 MySheet ' Option 4

End Sub

Sub Test2(TestSheet As Worksheet)
    Dim RowIndex As Long
    For RowIndex = 1 To TestSheet.UsedRange.Rows.Count
        If TestSheet.Cells(RowIndex, 1).Value = "SomeValue" Then
            ' Do something
        End If
    Next RowIndex
End Sub

echo that outputs to stderr

No, that's the standard way to do it. It shouldn't cause errors.

get data from mysql database to use in javascript

Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?

  1. Send AJAX request to php script
  2. PHP script processes request and builds table
  3. PHP script sends response back to JS in form of encoded HTML
  4. JS takes response and inserts it into the DOM

Docker compose port mapping

If you want to bind to the redis port from your nodejs container you will have to expose that port in the redis container:

version: '2'
services:
  nodejs:
    build:
      context: .
      dockerfile: DockerFile
    ports:
      - "4000:4000"
    links:
      - redis

  redis:
    build:
      context: .
      dockerfile: Dockerfile-redis
    expose:
      - "6379"

The expose tag will let you expose ports without publishing them to the host machine, but they will be exposed to the containers networks.

https://docs.docker.com/compose/compose-file/#expose

The ports tag will be mapping the host port with the container port HOST:CONTAINER

https://docs.docker.com/compose/compose-file/#ports

How can I import a database with MySQL from terminal?

mysql -u username -ppassword dbname < /path/file-name.sql

example

mysql -u root -proot product < /home/myPC/Downloads/tbl_product.sql

Use this from terminal

Oracle query execution time

I'd recommend looking at consistent gets/logical reads as a better proxy for 'work' than run time. The run time can be skewed by what else is happening on the database server, how much stuff is in the cache etc.

But if you REALLY want SQL executing time, the V$SQL view has both CPU_TIME and ELAPSED_TIME.

How do I delete from multiple tables using INNER JOIN in SQL server

To build upon John Gibb's answer, for deleting a set of data in two tables with a FK relationship:

--*** To delete from tblMain which JOINs to (has a FK of) tblReferredTo's PK  
--       i.e.  ON tblMain.Refer_FK = tblReferredTo.ID
--*** !!! If you're CERTAIN that no other rows anywhere also refer to the 
--      specific rows in tblReferredTo !!!
BEGIN TRAN;

    --*** Keep the ID's from tblReferredTo when we DELETE from tblMain
    DECLARE @tblDeletedRefs TABLE ( ID INT );
    --*** DELETE from the referring table first
    DELETE FROM tblMain 
    OUTPUT DELETED.Refer_FK INTO @tblDeletedRefs  -- doesn't matter that this isn't DISTINCT, the following DELETE still works.
    WHERE ..... -- be careful if filtering, what if other rows 
                --   in tblMain (or elsewhere) also point to the tblReferredTo rows?

    --*** Now we can remove the referred to rows, even though tblMain no longer refers to them.
    DELETE tblReferredTo
    FROM   tblReferredTo INNER JOIN @tblDeletedRefs Removed  
            ON tblReferredTo.ID = Removed.ID;

COMMIT TRAN;

Returning JSON response from Servlet to Javascript/JSP page

Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe the following:

JSONObject json      = new JSONObject();
JSONArray  addresses = new JSONArray();
JSONObject address;
try
{
   int count = 15;

   for (int i=0 ; i<count ; i++)
   {
       address = new JSONObject();
       address.put("CustomerName"     , "Decepticons" + i);
       address.put("AccountId"        , "1999" + i);
       address.put("SiteId"           , "1888" + i);
       address.put("Number"            , "7" + i);
       address.put("Building"          , "StarScream Skyscraper" + i);
       address.put("Street"            , "Devestator Avenue" + i);
       address.put("City"              , "Megatron City" + i);
       address.put("ZipCode"          , "ZZ00 XX1" + i);
       address.put("Country"           , "CyberTron" + i);
       addresses.add(address);
   }
   json.put("Addresses", addresses);
}
catch (JSONException jse)
{ 

}
response.setContentType("application/json");
response.getWriter().write(json.toString());

This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel

moment.js 24h format

You can use

 moment("15", "hh").format('LT') 

to convert the time to 12 hours format like this 3:00 PM

Laravel Pagination links not including other GET parameters

Not append() but appends() So, right answer is:

{!! $records->appends(Input::except('page'))->links() !!}

How to make a owl carousel with arrows instead of next previous

This is how you do it in your $(document).ready() function with FontAwesome Icons:

 $( ".owl-prev").html('<i class="fa fa-chevron-left"></i>');
 $( ".owl-next").html('<i class="fa fa-chevron-right"></i>');

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

How to bind list to dataGridView?

I know this is old, but this hung me up for awhile. The properties of the object in your list must be actual "properties", not just public members.

public class FileName
{        
     public string ThisFieldWorks {get;set;}
     public string ThisFieldDoesNot;
}

How should I import data from CSV into a Postgres table using pgAdmin 3?

You may have a table called 'test'

COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER

Java function for arrays like PHP's join()?

In Java 8 you can use

1) Stream API :

String[] a = new String[] {"a", "b", "c"};
String result = Arrays.stream(a).collect(Collectors.joining(", "));

2) new String.join method: https://stackoverflow.com/a/21756398/466677

3) java.util.StringJoiner class: http://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html

How to run multiple DOS commands in parallel?

I suggest you to see "How do I run a bat file in the background from another bat file?"

Also, good answer (of using start command) was given in "Parallel execution of shell processes" question page here;

But my recommendation is to use PowerShell. I believe it will perfectly suit your needs.

Int division: Why is the result of 1/3 == 0?

Try this out:

public static void main(String[] args) {
    double a = 1.0;
    double b = 3.0;
    double g = a / b;
    System.out.printf(""+ g);
}

How to get substring of NSString?

Use this also

NSString *ChkStr = [MyString substringWithRange:NSMakeRange(5, 26)];

Note - Your NSMakeRange(start, end) should be NSMakeRange(start, end- start);

Interpreting "condition has length > 1" warning from `if` function

The way I cam across this question was when I tried doing something similar where I was defining a function and it was being called with the array like others pointed out

You could do something like this however for this scenarios its less elegant compared to Sven's method.

sapply(a, function(x) afunc(x))

afunc<-function(a){
  if (a>0){
    a/sum(a)
  }
  else 1
}

How do I get textual contents from BLOB in Oracle SQL

You can use below SQL to read the BLOB Fields from table.

SELECT DBMS_LOB.SUBSTR(BLOB_FIELD_NAME) FROM TABLE_NAME;

How can I change the color of pagination dots of UIPageControl?

It's easy with Swift 1.2:

UIPageControl.appearance().pageIndicatorTintColor           = UIColor.lightGrayColor()
UIPageControl.appearance().currentPageIndicatorTintColor    = UIColor.redColor()

Checking if a field contains a string

Here's what you have to do if you are connecting MongoDB through Python

db.users.find({"username": {'$regex' : '.*' + 'Son' + '.*'}})

you may also use a variable name instead of 'Son' and therefore the string concatenation.

Animate visibility modes, GONE and VISIBLE

There is no easy way to animate hiding/showing views. You can try method described in following answer: How do I animate View.setVisibility(GONE)

How to place two forms on the same page?

Hope this will help you. Assumed that login form has: username and password inputs.

if(isset($_POST['username']) && trim($_POST['username']) != "" && isset($_POST['password']) && trim($_POST['password']) != ""){
//login
} else {
//register
}

Check if multiple strings exist in another string

I would use this kind of function for speed:

def check_string(string, substring_list):
    for substring in substring_list:
        if substring in string:
            return True
    return False

How to enable LogCat/Console in Eclipse for Android?

Write "LogCat" in Quick Access edit box in your eclipse window (top right corner, just before Open Prospective button). And just select LogCat it will open-up the LogCat window in your current prospect

enter image description here

How to change the font size on a matplotlib plot

Here is a totally different approach that works surprisingly well to change the font sizes:

Change the figure size!

I usually use code like this:

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
x = np.linspace(0,6.28,21)
ax.plot(x, np.sin(x), '-^', label="1 Hz")
ax.set_title("Oscillator Output")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Output (V)")
ax.grid(True)
ax.legend(loc=1)
fig.savefig('Basic.png', dpi=300)

The smaller you make the figure size, the larger the font is relative to the plot. This also upscales the markers. Note I also set the dpi or dot per inch. I learned this from a posting the AMTA (American Modeling Teacher of America) forum. Example from above code: enter image description here

Sorting a vector in descending order

bool comp(int i, int j) { return i > j; }
sort(numbers.begin(), numbers.end(), comp);

How do I set path while saving a cookie value in JavaScript?

See https://developer.mozilla.org/en/DOM/document.cookie for more documentation:

 setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {  
     if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }  
     var sExpires = "";  
     if (vEnd) {  
       switch (typeof vEnd) {  
         case "number": sExpires = "; max-age=" + vEnd; break;  
         case "string": sExpires = "; expires=" + vEnd; break;  
         case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;  
       }  
     }  
     document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");  
   }

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

better way to drop nan rows in pandas

Just in case commands in previous answers doesn't work, Try this: dat.dropna(subset=['x'], inplace = True)

Convert python long/int to fixed size byte array

Little-endian, reverse the result or the range if you want Big-endian:

def int_to_bytes(val, num_bytes):
    return [(val & (0xff << pos*8)) >> pos*8 for pos in range(num_bytes)]

Big-endian:

def int_to_bytes(val, num_bytes):
    return [(val & (0xff << pos*8)) >> pos*8 for pos in reversed(range(num_bytes))]

What do raw.githubusercontent.com URLs represent?

The raw.githubusercontent.com domain is used to serve unprocessed versions of files stored in GitHub repositories. If you browse to a file on GitHub and then click the Raw link, that's where you'll go.

The URL in your question references the install file in the master branch of the Homebrew/install repository. The rest of that command just retrieves the file and runs ruby on its contents.

Mysql select distinct

Are you looking for "SELECT * FROM temp_tickets GROUP BY ticket_id ORDER BY ticket_id ?

UPDATE

SELECT t.* 
FROM 
(SELECT ticket_id, MAX(id) as id FROM temp_tickets GROUP BY ticket_id) a  
INNER JOIN temp_tickets t ON (t.id = a.id)

Appending to an existing string

Can I ask why this is important?

I know that this is not a direct answer to your question, but the fact that you are trying to preserve the object ID of a string might indicate that you should look again at what you are trying to do.

You might find, for instance, that relying on the object ID of a string will lead to bugs that are quite hard to track down.

pop/remove items out of a python tuple

There is a simple but practical solution.

As DSM said, tuples are immutable, but we know Lists are mutable. So if you change a tuple to a list, it will be mutable. Then you can delete the items by the condition, then after changing the type to a tuple again. That’s it.

Please look at the codes below:

tuplex = list(tuplex)
for x in tuplex:
  if (condition):
     tuplex.pop(tuplex.index(x))
tuplex = tuple(tuplex)
print(tuplex)

For example, the following procedure will delete all even numbers from a given tuple.

tuplex = (1, 2, 3, 4, 5, 6, 7, 8, 9)
tuplex = list(tuplex)
for x in tuplex:
  if (x % 2 == 0):
     tuplex.pop(tuplex.index(x))
tuplex = tuple(tuplex)
print(tuplex)

if you test the type of the last tuplex, you will find it is a tuple.

Finally, if you want to define an index counter as you did (i.e., n), you should initialize it before the loop, not in the loop.

JavaScript: SyntaxError: missing ) after argument list

just posting in case anyone else has the same error...

I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.

The solution was to make the function asynchronous

function functionName(args) {}

becomes

async function functionName(args) {}

Copy every nth line from one sheet to another

In A1 of your new sheet, put this:

=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)

... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.

If you want to copy the nth line but multiple columns, use the formula:

=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)

This can be copied right too.

What's the best mock framework for Java?

I've had good success using Mockito.

When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me).

I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp.

Here's an (abridged) example from the Mockito homepage:

import static org.mockito.Mockito.*;

List mockedList = mock(List.class);
mockedList.clear();
verify(mockedList).clear();

It doesn't get much simpler than that.

The only major downside I can think of is that it won't mock static methods.

Oracle: SQL select date with timestamp

You can specify the whole day by doing a range, like so:

WHERE bk_date >= TO_DATE('2012-03-18', 'YYYY-MM-DD')
AND bk_date <  TO_DATE('2012-03-19', 'YYYY-MM-DD')

More simply you can use TRUNC:

WHERE TRUNC(bk_date) = TO_DATE('2012-03-18', 'YYYY-MM-DD')

TRUNC without parameter removes hours, minutes and seconds from a DATE.

Ajax request returns 200 OK, but an error event is fired instead of success

I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'text json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

PHPmailer sending HTML CODE

Calling the isHTML() method after the instance Body property (I mean $mail->Body) has been set solved the problem for me:

$mail->Subject = $Subject;
$mail->Body    = $Body;
$mail->IsHTML(true);       // <=== call IsHTML() after $mail->Body has been set.

Search a whole table in mySQL for a string

Try something like this:

SELECT * FROM clients WHERE CONCAT(field1, '', field2, '', fieldn) LIKE "%Mary%"

You may want to see SQL docs for additional information on string operators and regular expressions.

Edit: There may be some issues with NULL fields, so just in case you may want to use IFNULL(field_i, '') instead of just field_i

Case sensitivity: You can use case insensitive collation or something like this:

... WHERE LOWER(CONCAT(...)) LIKE LOWER("%Mary%")

Just search all field: I believe there is no way to make an SQL-query that will search through all field without explicitly declaring field to search in. The reason is there is a theory of relational databases and strict rules for manipulating relational data (something like relational algebra or codd algebra; these are what SQL is from), and theory doesn't allow things such as "just search all fields". Of course actual behaviour depends on vendor's concrete realisation. But in common case it is not possible. To make sure, check SELECT operator syntax (WHERE section, to be precise).

Adding a caption to an equation in LaTeX

As in this forum post by Gonzalo Medina, a third way may be:

\documentclass{article}
\usepackage{caption}

\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}

\begin{document}

Some text

\begin{equ}[!ht]
  \begin{equation}
    a=b+c
  \end{equation}
\caption{Caption of the equation}
\end{equ}

Some other text
 
\end{document}

More details of the commands used from package caption: here.

A screenshot of the output of the above code:

screenshot of output

How can I convert an HTML element to a canvas element?

No such thing, sorry.

Though the spec states:

A future version of the 2D context API may provide a way to render fragments of documents, rendered using CSS, straight to the canvas.

Which may be as close as you'll get.

A lot of people want a ctx.drawArbitraryHTML/Element kind of deal but there's nothing built in like that.

The only exception is Mozilla's exclusive drawWindow, which draws a snapshot of the contents of a DOM window into the canvas. This feature is only available for code running with Chrome ("local only") privileges. It is not allowed in normal HTML pages. So you can use it for writing FireFox extensions like this one does but that's it.

Bind a function to Twitter Bootstrap Modal Close

I've seen many answers regarding the bootstrap events such as hide.bs.modal which triggers when the modal closes.

There's a problem with those events: any popups in the modal (popovers, tooltips, etc) will trigger that event.

There is another way to catch the event when a modal closes.

$(document).on('hidden','#modal:not(.in)', function(){} );

Bootstrap uses the in class when the modal is open. It is very important to use the hidden event since the class in is still defined when the event hideis triggered.

This solution will not work in IE8 since IE8 does not support the Jquery :not() selector.

How to use linux command line ftp with a @ sign in my username?

As an alternative, if you don't want to create config files, do the unattended upload with curl instead of ftp:

curl -u user:password -T file ftp://server/dir/file

How to clear exisiting dropdownlist items when its content changes?

You should clear out your listbbox prior to binding:

 Me.ddl2.Items.Clear()
  ' now set datasource and bind

Returning null in a method whose signature says return int?

Change your return type to java.lang.Integer . This way you can safely return null

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

This kind of problem really make us anxious because of that no more useful information will be provided.

I don't know we are really the same,but I can provide two ways to help us try to solve the problem.

1.Firstly you can try to clean or restart your Android Studio & your computer.In China,we have a saying between developers.

Little problems,just restart.Big problems,should reinstall.

The above saying will help you to solve this kind of problem many times.

2.Secondly we need to use some gradle command to help you to find more useful details.

I have met the similar situation as below:

org.gradle.initialization.ReportedException: org.gradle.internal.exceptions.LocationAwareException: Execution failed for task ':app:compileDebugJavaWithJavac'.
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:139)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:109)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:53)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:47)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:69)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:30)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.internal.exceptions.LocationAwareException: Execution failed for task ':app:compileDebugJavaWithJavac'.
    at org.gradle.initialization.DefaultExceptionAnalyser.transform(DefaultExceptionAnalyser.java:74)
    at org.gradle.initialization.MultipleBuildFailuresExceptionAnalyser.transform(MultipleBuildFailuresExceptionAnalyser.java:47)
    at org.gradle.initialization.StackTraceSanitizingExceptionAnalyser.transform(StackTraceSanitizingExceptionAnalyser.java:30)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:137)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:109)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:53)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:47)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:69)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:30)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugJavaWithJavac'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    ... 3 more
Caused by: org.gradle.api.internal.tasks.compile.CompilationFailedException: Compilation failed; see the compiler error output for details.
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:50)
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:35)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:98)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:51)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:37)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:35)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:25)
    at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilationFinalizer.execute(IncrementalCompilationFinalizer.java:39)
    at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilationFinalizer.execute(IncrementalCompilationFinalizer.java:24)
    at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:207)
    at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:133)
    at com.android.build.gradle.tasks.factory.AndroidJavaCompile.compile(AndroidJavaCompile.java:125)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    ... 29 more

You know that the above log is not useful for us to solve this kind of problem.We need to do some gradle command to find more useful information.

Note:I use macOS(10.13) and Android Studio(3.1)

Go to your Android project directory to execute the gradle command below:

./gradlew assembleDebug --info

Note:If you have permission problems while executing the above command,you can use this to deal with it:

chmod +x gradlew

And then I got this(Some unimportant parts are omitted):

> Task :app:compileDebugJavaWithJavac FAILED
Putting task artifact state for task ':app:compileDebugJavaWithJavac' into context took 0.0 secs.
file or directory '/Users/ifeegoo/workspace/android/android-bluetooth-color-lamp-karma-lighting/app/src/debug/java', not found
Up-to-date check for task ':app:compileDebugJavaWithJavac' took 0.009 secs. It is not up-to-date because:
  Task has failed previously.
All input files are considered out-of-date for incremental task ':app:compileDebugJavaWithJavac'.
Compiling with source level 1.7 and target level 1.7.
Creating new cache for classAnalysis, path /Users/ifeegoo/workspace/android/android-bluetooth-color-lamp-karma-lighting/.gradle/4.4.1/javaCompile/classAnalysis.bin, access org.gradle.cache.internal.DefaultCacheAccess@156d7504
Creating new cache for jarAnalysis, path /Users/ifeegoo/workspace/android/android-bluetooth-color-lamp-karma-lighting/.gradle/4.4.1/javaCompile/jarAnalysis.bin, access org.gradle.cache.internal.DefaultCacheAccess@156d7504
Creating new cache for taskJars, path /Users/ifeegoo/workspace/android/android-bluetooth-color-lamp-karma-lighting/.gradle/4.4.1/javaCompile/taskJars.bin, access org.gradle.cache.internal.DefaultCacheAccess@156d7504
Creating new cache for taskHistory, path /Users/ifeegoo/workspace/android/android-bluetooth-color-lamp-karma-lighting/.gradle/4.4.1/javaCompile/taskHistory.bin, access org.gradle.cache.internal.DefaultCacheAccess@156d7504
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
file or directory '/Users/ifeegoo/workspace/android/android-bluetooth-color-lamp-karma-lighting/app/src/debug/java', not found
Compiling with JDK Java compiler API.
/Users/ifeegoo/workspace/android/android-bluetooth-color-lamp-karma-lighting/app/src/main/java/com/chipsguide/app/colorbluetoothlamp/v2/karmalighting/frags/banner/VideoActivity.java:10: error: package com.android.tedcoder.wkvideoplayer.model does not exist
import com.android.tedcoder.wkvideoplayer.model.Video;
                                               ^
/Users/ifeegoo/workspace/android/android-bluetooth-color-lamp-karma-lighting/app/src/main/java/com/chipsguide/app/colorbluetoothlamp/v2/karmalighting/frags/banner/VideoActivity.java:11: error: package com.android.tedcoder.wkvideoplayer.model does not exist
import com.android.tedcoder.wkvideoplayer.model.VideoUrl;
                                               ^
/Users/ifeegoo/workspace/android/android-bluetooth-color-lamp-karma-lighting/app/src/main/java/com/chipsguide/app/colorbluetoothlamp/v2/karmalighting/frags/banner/VideoActivity.java:12: error: package com.android.tedcoder.wkvideoplayer.view does not exist
import com.android.tedcoder.wkvideoplayer.view.MediaController;
                                              ^
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
35 errors

:app:compileDebugJavaWithJavac (Thread[Task worker for ':',5,main]) completed. Took 0.84 secs.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
15 actionable tasks: 1 executed, 14 up-to-date 

I have got the most important details information,because of one module imported not properly which makes the class not found.So, I got it and solve the problem.

Some other gradle command:

*clean project
./gradlew clean  

*build project
./gradlew build

*build for debug package
./gradlew assembleDebug or ./gradlew aD

*build for release package
./gradlew assembleRelease or ./gradlew aR

*build for release package and install
./gradlew installRelease or ./gradlew iR Release

*build for debug package and install
./gradlew installDebug or ./gradlew iD Debug

*uninstall release package
./gradlew uninstallRelease or ./gradlew uR

*uninstall debug package
./gradlew uninstallDebug or ./gradlew uD 

*all the above command + "--info" or "--debug" or "--scan" or "--stacktrace" can get more detail information.

If you cannot get enough information by --info,please use --debug/--scan/--stacktrace instead.

Remember that the more details will help you to solve the problem the more.

Note:Gradle commands are really powerful,if you want to do more complicated operation,especially about how to deal with debug/release or multi-channels or modules,go to Android Studio to check the Gradle Window,then you will know how to do it!

enter image description here

enter image description here

How to write std::string to file?

You're currently writing the binary data in the string-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.

If you want to write to a text file, the best way to do this would probably be with an ofstream, an "out-file-stream". It behaves exactly like std::cout, but the output is written to a file.

The following example reads one string from stdin, and then writes this string to the file output.txt.

#include <fstream>
#include <string>
#include <iostream>

int main()
{
    std::string input;
    std::cin >> input;
    std::ofstream out("output.txt");
    out << input;
    out.close();
    return 0;
}

Note that out.close() isn't strictly neccessary here: the deconstructor of ofstream can handle this for us as soon as out goes out of scope.

For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/

Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str(). So you could use:

write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );

Call method when home button pressed

KeyEvent.KEYCODE_HOME can NOT be intercepted.

It would be quite bad if it would be possible.

(Edit): I just see Nicks answer, which is perfectly complete ;)

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

I encountered the same problem even I set "UseDefaultCredentials" to false. Later I found that the root cause is that I turned on "2-step Verification" in my account. After I turned it off, the problem is gone.

How do I extract the contents of an rpm?

To debug / inspect your rpm I suggest to use redline which is a java program

Usage :

java -cp redline-1.2.1-jar-with-dependencies.jar org.redline_rpm.Scanner foo.rpm

Download : https://github.com/craigwblake/redline/releases

How do I apply a perspective transform to a UIView?

Swift 5.0

func makeTransform(horizontalDegree: CGFloat, verticalDegree: CGFloat, maxVertical: CGFloat,rotateDegree: CGFloat, maxHorizontal: CGFloat) -> CATransform3D {
    var transform = CATransform3DIdentity
           
    transform.m34 = 1 / -500
    
    let xAnchor = (horizontalDegree / (2 * maxHorizontal)) + 0.5
    let yAnchor = (verticalDegree / (-2 * maxVertical)) + 0.5
    let anchor = CGPoint(x: xAnchor, y: yAnchor)
    
    setAnchorPoint(anchorPoint: anchor, forView: self.imgView)
    let hDegree  = (CGFloat(horizontalDegree) * .pi)  / 180
    let vDegree  = (CGFloat(verticalDegree) * .pi)  / 180
    let rDegree  = (CGFloat(rotateDegree) * .pi)  / 180
    transform = CATransform3DRotate(transform, vDegree , 1, 0, 0)
    transform = CATransform3DRotate(transform, hDegree , 0, 1, 0)
    transform = CATransform3DRotate(transform, rDegree , 0, 0, 1)
    
    return transform
}

func setAnchorPoint(anchorPoint: CGPoint, forView view: UIView) {
    var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y)
    var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y)
    
    newPoint = newPoint.applying(view.transform)
    oldPoint = oldPoint.applying(view.transform)
    
    var position = view.layer.position
    position.x -= oldPoint.x
    position.x += newPoint.x
    
    position.y -= oldPoint.y
    position.y += newPoint.y
    
    print("Anchor: \(anchorPoint)")
    
    view.layer.position = position
    view.layer.anchorPoint = anchorPoint
}

you only need to call the function with your degree. for example:

var transform = makeTransform(horizontalDegree: 20.0 , verticalDegree: 25.0, maxVertical: 25, rotateDegree: 20, maxHorizontal: 25)
imgView.layer.transform = transform

TypeScript: Interfaces vs Types

As per the TypeScript Language Specification:

Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.

The specification goes on to mention:

Interface types have many similarities to type aliases for object type literals, but since interface types offer more capabilities they are generally preferred to type aliases. For example, the interface type

interface Point {
    x: number;
    y: number;
}

could be written as the type alias

type Point = {
    x: number;
    y: number;
};

However, doing so means the following capabilities are lost:

  • An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot No longer true since TS 2.7.
  • An interface can have multiple merged declarations, but a type alias for an object type literal cannot.

css rotate a pseudo :after or :before content:""

.process-list:after{
    content: "\2191";
    position: absolute;
    top:50%;
    right:-8px;
    background-color: #ea1f41;
    width:35px;
    height: 35px;
    border:2px solid #ffffff;
    border-radius: 5px;
    color: #ffffff;
    z-index: 10000;
    -webkit-transform: rotate(50deg) translateY(-50%);
    -moz-transform: rotate(50deg) translateY(-50%);
    -ms-transform: rotate(50deg) translateY(-50%);
    -o-transform: rotate(50deg) translateY(-50%);
    transform: rotate(50deg) translateY(-50%);
}

you can check this code . i hope you will easily understand.

How to use onClick() or onSelect() on option tag in a JSP page?

Even more simplified: You can pass the value attribute directly!

<html>
 <head>
  <script type="text/javascript">

   function changeFunc($i) {
    alert($i);
   }

  </script>
 </head>
 <body>
  <select id="selectBox" onchange="changeFunc(value);">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
  </select>
 </body>
</html>

The alert will either return 1 or 2.

Date Comparison using Java

You are probably looking for:

!toDate.before(currentDate)

before() and after() test whether the date is strictly before or after. So you have to take the negation of the other one to get non strict behaviour.

How to reshape data from long to wide format

Using reshape function:

reshape(dat1, idvar = "name", timevar = "numbers", direction = "wide")

Correct way to pause a Python program

By this method, you can resume your program just by pressing any specified key you've specified that:

import keyboard
while True:
    key = keyboard.read_key()
    if key == 'space':  # You can put any key you like instead of 'space'
        break

The same method, but in another way:

import keyboard
while True:
    if keyboard.is_pressed('space'):  # The same. you can put any key you like instead of 'space'
        break

Note: you can install the keyboard module simply by writing this in you shell or cmd:

pip install keyboard

How to create a byte array in C++?

Try

class MissileLauncher
{
public:
    MissileLauncher(void);

private:
    unsigned char abc[3];
};

or

using byte = unsigned char;

class MissileLauncher
{
public:
    MissileLauncher(void);

private:
    byte abc[3];
};

**Note: In older compilers (non-C++11) replace the using line with typedef unsigned char byte;

Undo a merge by pull request?

If the pull was the last thing he did then

git reset --hard HEAD~1

Remove the first character of a string

deleting a char:

def del_char(string, indexes):

    'deletes all the indexes from the string and returns the new one'

    return ''.join((char for idx, char in enumerate(string) if idx not in indexes))

it deletes all the chars that are in indexes; you can use it in your case with del_char(your_string, [0])

Efficient way to update all rows in a table

update Hotels set Discount=30 where Hotelid >= 1 and Hotelid <= 5504

Parsing JSON array into java.util.List with Gson

Below code is using com.google.gson.JsonArray. I have printed the number of element in list as well as the elements in List

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class Test {

    static String str = "{ "+ 
            "\"client\":\"127.0.0.1\"," + 
            "\"servers\":[" + 
            "    \"8.8.8.8\"," + 
            "    \"8.8.4.4\"," + 
            "    \"156.154.70.1\"," + 
            "    \"156.154.71.1\" " + 
            "    ]" + 
            "}";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {

            JsonParser jsonParser = new JsonParser();
            JsonObject jo = (JsonObject)jsonParser.parse(str);
            JsonArray jsonArr = jo.getAsJsonArray("servers");
            //jsonArr.
            Gson googleJson = new Gson();
            ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
            System.out.println("List size is : "+jsonObjList.size());
                    System.out.println("List Elements are  : "+jsonObjList.toString());


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

OUTPUT

List size is : 4

List Elements are  : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]

Is it acceptable and safe to run pip install under sudo?

I had a problem installing virtualenvwrapper after successfully installing virtualenv.

My terminal complained after I did this:

pip install virtualenvwrapper

So, I unsuccessfully tried this (NOT RECOMMENDED):

sudo pip install virtualenvwrapper

Then, I successfully installed it with this:

pip install --user virtualenvwrapper

Angular JS break ForEach

As far as I know, Angular doesn't provide such a function. You may want to use underscore's find() function for this (it's basically a forEach which breaks out of the loop once the function returns true).

http://underscorejs.org/#find

How do I pipe a subprocess call to a text file?

The options for popen can be used in call

args, 
bufsize=0, 
executable=None, 
stdin=None, 
stdout=None, 
stderr=None, 
preexec_fn=None, 
close_fds=False, 
shell=False, 
cwd=None, 
env=None, 
universal_newlines=False, 
startupinfo=None, 
creationflags=0

So...

subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=myoutput)

Then you can do what you want with myoutput (which would need to be a file btw).

Also, you can do something closer to a piped output like this.

dmesg | grep hda

would be:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

There's plenty of lovely, useful info on the python manual page.

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

Attach the Source in Eclipse of a jar

A .jar file usually only contains the .class files, not the .java files they were compiled from. That's why eclipse is telling you it doesn't know the source code of that class.

"Attaching" the source to a JAR means telling eclipse where the source code can be found. Of course, if you don't know yourself, that feature is of little help. Of course, you could try googling for the source code (or check wherever you got the JAR file from).

That said, you don't necessarily need the source to debug.

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I also had similar problem where redirects were giving 404 or 405 randomly on my development server. It was an issue with gunicorn instances.

Turns out that I had not properly shut down the gunicorn instance before starting a new one for testing. Somehow both of the processes were running simultaneously, listening to the same port 8080 and interfering with each other. Strangely enough they continued running in background after I had killed all my terminals. Had to kill them manually using fuser -k 8080/tcp

How do you specify table padding in CSS? ( table, not cell padding )

Funny, I was doing precisely this yesterday. You just need this in your css file

.ablock table td {
     padding:5px;
}

then wrap the table in a suitable div

<div class="ablock ">
<table>
  <tr>
    <td>

How to remove unused imports in Intellij IDEA on commit?

If you are using IntelliJ IDEA or Android Studio:

Android optimize imports

Go to Settings > Editor > General >Auto Import and check the Optimize imports on the fly checkbox.

PHP Sort a multidimensional array by element containing date

This should work. I converted the date to unix time via strtotime.

  foreach ($originalArray as $key => $part) {
       $sort[$key] = strtotime($part['datetime']);
  }
  array_multisort($sort, SORT_DESC, $originalArray);

One-liner version would be using multiple array methods:

array_multisort(array_map('strtotime',array_column($originalArray,'datetime')),
                SORT_DESC, 
                $originalArray);

How to change the color of an image on hover

If the icon is from Font Awesome (https://fontawesome.com/icons/) then you could tap into the color css property to change it's background.

fb-icon{
color:none;
}

fb-icon:hover{
color:#0000ff;
}

This is irrespective of the color it had. So you could use an entirely different color in its usual state and define another in its active state.

How to set the first option on a select box using jQuery?

You can try this:

$( 'select' ).each( function () {
    if ( $( this ).children().length > 0 ) {
        $( $( this ).children()[0] ).attr( 'selected', 'selected' );
        $( this ).change();
    }
} );