Programs & Examples On #Nimble

max(length(field)) in mysql

I suppose you could use a solution such as this one :

select name, length(name)
from users
where id = (
    select id
    from users
    order by length(name) desc
    limit 1
);

Might not be the optimal solution, though... But seems to work.

How do I find the absolute position of an element using jQuery?

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

Load a HTML page within another HTML page

iframe is the tag which you can use for call other html pages into your web page

<iframe src="http://www.google.co.in" name="targetframe" allowTransparency="true" scrolling="no" frameborder="0" >
    </iframe>

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

Iterate over each line in a string in PHP

Potential memory issues with strtok:

Since one of the suggested solutions uses strtok, unfortunately it doesn't point out a potential memory issue (though it claims to be memory efficient). When using strtok according to the manual, the:

Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string.

It does this by loading the file into memory. If you're using large files, you need to flush them if you're done looping through the file.

<?php
function process($str) {
    $line = strtok($str, PHP_EOL);

    /*do something with the first line here...*/

    while ($line !== FALSE) {
        // get the next line
        $line = strtok(PHP_EOL);

        /*do something with the rest of the lines here...*/

    }
    //the bit that frees up memory
    strtok('', '');
}

If you're only concerned with physical files (eg. datamining):

According to the manual, for the file upload part you can use the file command:

 //Create the array
 $lines = file( $some_file );

 foreach ( $lines as $line ) {
   //do something here.
 }

Installing and Running MongoDB on OSX

Problem here is you are trying to open a mongo shell without starting a mongo db which is listening to port 127.0.0.1:27017(deafault for mongo db) thats what the error is all about:

Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145 exception: connect failed

The easiest solution is to open the terminal and type

$ mongod --dbpath ~/data/db

Note: dbpath here is "Users/user" where data/db directories are created

i.e., you need to create directory data and sub directory db in your user folder. For e.g say `

/Users/johnny/data

After mongo db is up. Open another terminal in new window and type

$ mongo

it will open mongo shell with your mongo db connection opened in another terminal.

Error in plot.window(...) : need finite 'xlim' values

This error appears when the column contains character, if you check the data type it would be of type 'chr' converting the column to 'Factor' would solve this issue.

For e.g. In case you plot 'City' against 'Sales', you have to convert column 'City' to type 'Factor'

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

How to do what @connor said:

iOS

  • Open platforms/ios on XCode
  • Find & Replace io.ionic.starter in all files for a unique identifier
  • Click the project to open settings
  • Signing > Select a team
  • Go to your device Settings > General > DeviceManagement
    • Trust your account/team
  • ionic cordova run ios --device --livereload

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I'm not sure why py.test does not add the current directory in the PYTHONPATH itself, but here's a workaround (to be executed from the root of your repository):

python -m pytest tests/

It works because Python adds the current directory in the PYTHONPATH for you.

What is the proper way to check if a string is empty in Perl?

To check for an empty string you could also do something as follows

if (!defined $val || $val eq '')
{
    # empty
}

Create a one to many relationship using SQL Server

If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId. If this is not what you are looking for, please elaborate your question.

Volley - POST/GET parameters

Dealing with GET parameters I iterated on Andrea Motto' solution. The problem was that Volley called GetUrl several times and his solution, using an Iterator, destroyed original Map object. The subsequent Volley internal calls had an empty params object.

I added also the encode of parameters.

This is an inline usage (no subclass).

public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) {
    final Map<String, String> mParams = params;
    final String mAPI_KEY = API_KEY;
    final String mUrl = url;

    StringRequest stringRequest = new StringRequest(
            Request.Method.GET,
            mUrl,
            response_listener,
            error_listener
    ) {
        @Override
        protected Map<String, String> getParams() {
            return mParams;
        }

        @Override
        public String getUrl() {
            StringBuilder stringBuilder = new StringBuilder(mUrl);
            int i = 1;
            for (Map.Entry<String,String> entry: mParams.entrySet()) {
                String key;
                String value;
                try {
                    key = URLEncoder.encode(entry.getKey(), "UTF-8");
                    value = URLEncoder.encode(entry.getValue(), "UTF-8");
                    if(i == 1) {
                        stringBuilder.append("?" + key + "=" + value);
                    } else {
                        stringBuilder.append("&" + key + "=" + value);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                i++;

            }
            String url = stringBuilder.toString();

            return url;
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> headers = new HashMap<>();
            if (!(mAPI_KEY.equals(""))) {
                headers.put("X-API-KEY", mAPI_KEY);
            }
            return headers;
        }
    };

    if (stringRequestTag != null) {
        stringRequest.setTag(stringRequestTag);
    }

    mRequestQueue.add(stringRequest);
}

This function uses headers to pass an APIKEY and sets a TAG to the request useful to cancel it before its completion.

Hope this helps.

How to get values from IGrouping

var groups = list.GroupBy(x => x.ID);

Can anybody suggest how to get the values (List) from an IGrouping<int, smth> in such a context?

"IGrouping<int, smth> group" is actually an IEnumerable with a key, so you either:

  • iterate on the group or
  • use group.ToList() to convert it to a List
foreach (IGrouping<int, smth> group in groups)
{
   var thisIsYourGroupKey = group.Key; 
   List<smth> list = group.ToList();     // or use directly group.foreach
}

Pandas dataframe groupby plot

Simple plot,

you can use:

df.plot(x='Date',y='adj_close')

Or you can set the index to be Date beforehand, then it's easy to plot the column you want:

df.set_index('Date', inplace=True)
df['adj_close'].plot()

If you want a chart with one series by ticker on it

You need to groupby before:

df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)

enter image description here


If you want a chart with individual subplots:

grouped = df.groupby('ticker')

ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(ax=ax)

ax.legend()
plt.show()

enter image description here

How to set variables in HIVE scripts

Try this method:

set t=20;
select *
from myTable
where age > '${hiveconf:t}'; 

it works well on my platform.

Converting double to string

This code compiles and works for me. It converts a double to a string using the calls you tried.

public class TestDouble {

    public static void main(String[] args) {
        double total = 44;
        String total2 = Double.toString(total);

        System.out.println("Double is " + total2);
    }
}

I am puzzled by your seeing the NumberFormatException. Look at the stack trace. I'm guessing you have other code that you are not showing in your example that is causing that exception to be thrown.

Height equal to dynamic width (CSS fluid layout)

really this belongs as a comment to Nathan's answer, but I'm not allowed to do that yet...
I wanted to maintain the aspect ratio, even if there is too much stuff to fit in the box. His example expands the height, changing the aspect ratio. I found adding

overflow: hidden;
overflow-x: auto;
overflow-y: auto;

to the .element helped. See http://jsfiddle.net/B8FU8/3111/

git: Your branch is ahead by X commits

I went through every solution on this page, and fortunately @anatolii-pazhyn commented because his solution was the one that worked. Unfortunately I don't have enough reputation to upvote him, but I recommend trying his solution first:

git reset --hard origin/master

Which gave me:

HEAD is now at 900000b Comment from my last git commit here

I also recommend:

git rev-list origin..HEAD
# to see if the local repository is ahead, push needed

git rev-list HEAD..origin
# to see if the local repository is behind, pull needed

You can also use:

git rev-list --count --left-right origin/master...HEAD
# if you have numbers for both, then the two repositories have diverged

Best of luck

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

I had the same error when tried to run my tests in a JSF project.

I´m using Eclipse IDE (kepler). So, I did "project > clean" and then ran the tests again of the same project.

It worked!

Compiling and Running Java Code in Sublime Text 2

I am using Windows 7. The below solution works for me!!

**Open** the file JavaC.sublime-build and replace all the code in the file with the code below:

{
 "cmd": ["javac", "$file_name","&&","java", "$file_base_name"],
 "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
 **"path": "C:\\Program Files\\Java\\jdk1.6.0\\bin\\",**
 "selector": "source.java",
 "shell": true
 }

Remember to replace "C:\Program Files\Java\jdk1.6.0\bin\" with the path where you put your jdk. And make sure to add the path of you java JDK to the environment variable "PATH". Refer to bunnyDrug's post to set up the environment variable. Best!!

Print a file's last modified date in Bash

You can use:

ls -lrt filename |awk '{print "%02d",$7}'

This will display the date in 2 digits.

If between 1 to 9 it adds "0" prefix to it and converts to 01 - 09.

Hope this meets the expectation.

How to get a file directory path from file path?

On a related note, if you only have the filename or relative path, dirname on its own won't help. For me, the answer ended up being readlink.

fname='txtfile'    
echo $(dirname "$fname")                # output: .
echo $(readlink -f "$fname")            # output: /home/me/work/txtfile

You can then combine the two to get just the directory.

echo $(dirname $(readlink -f "$fname")) # output: /home/me/work

Can I specify multiple users for myself in .gitconfig?

This answer is partially inspired by the post by @Saucier, but I was looking for an automated way to set user.name and user.email on a per repo basis, based on the remote, that was a little more light weight than the git-passport package that he developed. Also h/t to @John for the useConfigOnly setting. Here is my solution:

.gitconfig changes:

[github]
    name = <github username>
    email = <github email>
[gitlab]
    name = <gitlab username>
    email = <gitlab email>
[init]
    templatedir = ~/.git-templates
[user]
    useConfigOnly = true

post-checkout hook which should be saved to the following path: ~/.git-templates/hooks/post-checkout:

#!/usr/bin/env bash

# make regex matching below case insensitive
shopt -s nocasematch

# values in the services array should have a corresponding section in
# .gitconfig where the 'name' and 'email' for that service are specified
remote_url="$( git config --get --local remote.origin.url )"
services=(
    'github'
    'gitlab'
)

set_local_user_config() {
    local service="${1}"
    local config="${2}"
    local service_config="$( git config --get ${service}.${config} )"
    local local_config="$( git config --get --local user.${config} )"

    if [[ "${local_config}" != "${service_config}" ]]; then
        git config --local "user.${config}" "${service_config}"
        echo "repo 'user.${config}' has been set to '${service_config}'"
    fi
}

# if remote_url doesn't contain the any of the values in the services
# array the user name and email will remain unset and the
# user.useConfigOnly = true setting in .gitconfig will prompt for those
# credentials and prevent commits until they are defined
for s in "${services[@]}"; do
    if [[ "${remote_url}" =~ "${s}" ]]; then
        set_local_user_config "${s}" 'name'
        set_local_user_config "${s}" 'email'
        break
    fi
done

I use different credentials for github and gitlab, but those references in the code above could be replaced or augmented with any service that you use. In order to have the post-checkout hook automatically set the user name and email locally for a repo after a checkout make sure the service name appears in the remote url, add it to the services array in the post-checkout script and create a section for it in your .gitconfig that contains your user name and email for that service.

If none of the service names appear in the remote url or the repo doesn't have a remote the user name and email will not be set locally. In these cases the user.useConfigOnly setting will be in play which will not allow you to make commits until the user name and email are set at the repo level, and will prompt the user to configure that information.

Converting a string to a date in a cell

To accomodate both data scenarios you have, you will want to use this:

datevalue(text(a2,"mm/dd/yyyy"))

That will give you the date number representation for a cell that Excel has in date, or in text datatype.

How to catch all exceptions in c# using try and catch?

try
{

..
..
..

}

catch(Exception ex)
{

..
..
..

}

the Exception ex means all the exceptions.

How do I put variable values into a text string in MATLAB?

I just realized why I was having so much trouble - in MATLAB you can't store strings of different lengths as an array using square brackets. Using square brackets concatenates strings of varying lengths into a single character array.

    >> a=['matlab','is','fun']

a =

matlabisfun

>> size(a)

ans =

     1    11

In a character array, each character in a string counts as one element, which explains why the size of a is 1X11.

To store strings of varying lengths as elements of an array, you need to use curly braces to save as a cell array. In cell arrays, each string is treated as a separate element, regardless of length.

>> a={'matlab','is','fun'}

a = 

    'matlab'    'is'    'fun'

>> size(a)

ans =

     1     3

Class Not Found Exception when running JUnit test

I fixed my issue by running maven update. Right click project your project > Maven > Update Project

Service Reference Error: Failed to generate code for the service reference

Have to uncheck the Reuse types in all referenced assemblies from Configure service reference option

Check this for details

JavaScript equivalent of PHP’s die

If you're using nodejs, you can use

process.exit(<code>);

Subtracting 2 lists in Python

If you plan on performing more than simple one liners, it would be better to implement your own class and override the appropriate operators as they apply to your case.

Taken from Mathematics in Python:

class Vector:

  def __init__(self, data):
    self.data = data

  def __repr__(self):
    return repr(self.data)  

  def __add__(self, other):
    data = []
    for j in range(len(self.data)):
      data.append(self.data[j] + other.data[j])
    return Vector(data)  

x = Vector([1, 2, 3])    
print x + x

split string in two on given index and return both parts

If you want a really hacky one-liner using regular expressions and interpolated strings...

_x000D_
_x000D_
const splitString = (value, idx) => value.split(new RegExp(`(?<=^.{${idx}})`));
console.log(splitString('abcdefgh', 5));
_x000D_
_x000D_
_x000D_

This code says split the string by replacing the value returned in the regex. The regex returns a position, not a character, so we don't lose in characters in the initial string. The way it does this is finding the position, via a look-behind and the ^ anchor, where there were index characters from the start of the string.


To solve your proposed problem of adding commas every third position from the end, the regex would be slightly different and we'd use replace rather than split.

_x000D_
_x000D_
const values = [ 8211, 98700, 1234567890 ];
const addCommas = (value, idx) => value.replace(new RegExp(`(?=(.{${idx}})+$)`, 'g'), ',');

console.log(values.map(v => addCommas(v.toString(), 3)));
_x000D_
_x000D_
_x000D_

Here we find the idxth position from the end by using a look-ahead and the $ anchor, but we also capture any number of those sets of positions from the end. Then we replace the position with a comma. We use the g flag (global) so it replaces every occurrence, not just the first found.

How to change the default port of mysql from 3306 to 3360

When server first starts the my.ini may not be created where everyone has stated. I was able to find mine in C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.6

This location has the defaults for every setting.

# CLIENT SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by MySQL client applications.
# Note that only client applications shipped by MySQL are guaranteed
# to read this section. If you want your own MySQL client program to
# honor these values, you need to specify it as an option during the
# MySQL client library initialization.
#
[client]

# pipe
# socket=0.0
port=4306  !!!!!!!!!!!!!!!!!!!Change this!!!!!!!!!!!!!!!!!

[mysql]
no-beep

default-character-set=utf8

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

As the error messages stated, ngFor only supports Iterables such as Array, so you cannot use it for Object.

change

private extractData(res: Response) {
  let body = <Afdelingen[]>res.json();
  return body || {};       // here you are return an object
}

to

private extractData(res: Response) {
  let body = <Afdelingen[]>res.json().afdelingen;    // return array from json file
  return body || [];     // also return empty array if there is no data
}

DATEDIFF function in Oracle

Just subtract the two dates:

select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;

The result will be the difference in days.

More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

How to call a .NET Webservice from Android using KSOAP2?

How does your .NET Webservice look like?

I had the same effect using ksoap 2.3 from code.google.com. I followed the tutorial on The Code Project (which is great BTW.)

And everytime I used

    Integer result = (Integer)envelope.getResponse();

to get the result of a my webservice (regardless of the type, I tried Object, String, int) I ran into the org.ksoap2.serialization.SoapPrimitive exception.

I found a solution (workaround). The first thing I had to do was to remove the "SoapRpcMethod() attribute from my webservice methods.

    [SoapRpcMethod(), WebMethod]
    public Object GetInteger1(int i)
    {
        // android device will throw exception
        return 0;
    }

    [WebMethod]
    public Object GetInteger2(int i)
    {
        // android device will get the value
        return 0;
    }

Then I changed my Android code to:

    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

However, I get a SoapPrimitive object, which has a "value" filed that is private. Luckily the value is passed through the toString() method, so I use Integer.parseInt(result.toString()) to get my value, which is enough for me, because I don't have any complex types that I need to get from my Web service.

Here is the full source:

private static final String SOAP_ACTION = "http://tempuri.org/GetInteger2";
private static final String METHOD_NAME = "GetInteger2";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:4711/Service1.asmx";

public int GetInteger2() throws IOException, XmlPullParserException {
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    PropertyInfo pi = new PropertyInfo();
    pi.setName("i");
    pi.setValue(123);
    request.addProperty(pi);

    SoapSerializationEnvelope envelope =
        new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);

    AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
    androidHttpTransport.call(SOAP_ACTION, envelope);

    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
    return Integer.parseInt(result.toString());
}

Clicking a button within a form causes page refresh

I use directive to prevent default behaviour:

module.directive('preventDefault', function() {
    return function(scope, element, attrs) {
        angular.element(element).bind('click', function(event) {
            event.preventDefault();
            event.stopPropagation();
        });
    }
});

And then, in html:

<button class="secondaryButton" prevent-default>Secondary action</button>

This directive can also be used with <a> and all other tags

How can I start and check my MySQL log?

Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html

Changing git commit message after push (given that no one pulled from remote)

Use these two step in console :

git commit --amend -m "new commit message"

and then

git push -f

Done :)

Printing with sed or awk a line following a matching pattern

Piping some greps can do it (it runs in POSIX shell and under BusyBox):

cat my-file | grep -A1 my-regexp | grep -v -- '--' | grep -v my-regexp
  1. -v will show non-matching lines
  2. -- is printed by grep to separate each match, so we skip that too

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

Dynamic Height Issue for UITableView Cells (Swift)

Unfortunately, I am not sure what I was missing. The above methods don't work for me to get the xib cell's height or let the layoutifneeded()or UITableView.automaticDimension to do the height calculation. I've been searching and trying for 3 to 4 nights but could not find an answer. Some answers here or on another post did give me hints for the workaround though. It's a stupid method but it works. Just add all your cells into an Array. And then set the outlet of each of your height constraint in the xib storyboard. Finally, add them up in the heightForRowAt method. It's just straight forward if you are not familiar with the those APIs.

Swift 4.2

CustomCell.Swift

@IBOutlet weak var textViewOneHeight: NSLayoutConstraint!
@IBOutlet weak var textViewTwoHeight: NSLayoutConstraint!
@IBOutlet weak var textViewThreeHeight: NSLayoutConstraint!

@IBOutlet weak var textViewFourHeight: NSLayoutConstraint!
@IBOutlet weak var textViewFiveHeight: NSLayoutConstraint!

MyTableViewVC.Swift

.
.
var myCustomCells:[CustomCell] = []
.
.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = Bundle.main.loadNibNamed("CustomCell", owner: self, options: nil)?.first as! CustomCell

.
.
myCustomCells.append(cell)
return cell

}


override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

   let totalHeight = myCustomCells[indexPath.row].textViewOneHeight.constant + myCustomCells[indexPath.row].textViewTwoHeight.constant +  myCustomCells[indexPath.row].textViewThreeHeight.constant + myCustomCells[indexPath.row].textViewFourHeight.constant + myCustomCells[indexPath.row].textViewFiveHeight.constant

  return totalHeight + 40 //some magic number


}

Running conda with proxy

You can configure a proxy with conda by adding it to the .condarc, like

proxy_servers:
    http: http://user:[email protected]:8080
    https: https://user:[email protected]:8080

Then in cmd Anaconda Power Prompt (base) PS C:\Users\user> run:

conda update -n root conda

Fastest way to iterate over all the chars in a String

Just for curiosity and to compare with Saint Hill's answer.

If you need to process heavy data you should not use JVM in client mode. Client mode is not made for optimizations.

Let's compare results of @Saint Hill benchmarks using a JVM in Client mode and Server mode.

Core2Quad Q6600 G0 @ 2.4GHz
JavaSE 1.7.0_40

See also: Real differences between "java -server" and "java -client"?


CLIENT MODE:

len =      2:    111k charAt(i),  105k cbuff[i],   62k new[i],   17k field access.   (chars/ms) 
len =      4:    285k charAt(i),  166k cbuff[i],  114k new[i],   43k field access.   (chars/ms) 
len =      6:    315k charAt(i),  230k cbuff[i],  162k new[i],   69k field access.   (chars/ms) 
len =      8:    333k charAt(i),  275k cbuff[i],  181k new[i],   85k field access.   (chars/ms) 
len =     12:    342k charAt(i),  342k cbuff[i],  222k new[i],  117k field access.   (chars/ms) 
len =     16:    363k charAt(i),  347k cbuff[i],  275k new[i],  152k field access.   (chars/ms) 
len =     20:    363k charAt(i),  392k cbuff[i],  289k new[i],  180k field access.   (chars/ms) 
len =     24:    375k charAt(i),  428k cbuff[i],  311k new[i],  205k field access.   (chars/ms) 
len =     28:    378k charAt(i),  474k cbuff[i],  341k new[i],  233k field access.   (chars/ms) 
len =     32:    376k charAt(i),  492k cbuff[i],  340k new[i],  251k field access.   (chars/ms) 
len =     64:    374k charAt(i),  551k cbuff[i],  374k new[i],  367k field access.   (chars/ms) 
len =    128:    385k charAt(i),  624k cbuff[i],  415k new[i],  509k field access.   (chars/ms) 
len =    256:    390k charAt(i),  675k cbuff[i],  436k new[i],  619k field access.   (chars/ms) 
len =    512:    394k charAt(i),  703k cbuff[i],  439k new[i],  695k field access.   (chars/ms) 
len =   1024:    395k charAt(i),  718k cbuff[i],  462k new[i],  742k field access.   (chars/ms) 
len =   2048:    396k charAt(i),  725k cbuff[i],  471k new[i],  767k field access.   (chars/ms) 
len =   4096:    396k charAt(i),  727k cbuff[i],  459k new[i],  780k field access.   (chars/ms) 
len =   8192:    397k charAt(i),  712k cbuff[i],  446k new[i],  772k field access.   (chars/ms) 

SERVER MODE:

len =      2:     86k charAt(i),   41k cbuff[i],   46k new[i],   80k field access.   (chars/ms) 
len =      4:    571k charAt(i),  250k cbuff[i],   97k new[i],  222k field access.   (chars/ms) 
len =      6:    666k charAt(i),  333k cbuff[i],  125k new[i],  315k field access.   (chars/ms) 
len =      8:    800k charAt(i),  400k cbuff[i],  181k new[i],  380k field access.   (chars/ms) 
len =     12:    800k charAt(i),  521k cbuff[i],  260k new[i],  545k field access.   (chars/ms) 
len =     16:    800k charAt(i),  592k cbuff[i],  296k new[i],  640k field access.   (chars/ms) 
len =     20:    800k charAt(i),  666k cbuff[i],  408k new[i],  800k field access.   (chars/ms) 
len =     24:    800k charAt(i),  705k cbuff[i],  452k new[i],  800k field access.   (chars/ms) 
len =     28:    777k charAt(i),  736k cbuff[i],  368k new[i],  933k field access.   (chars/ms) 
len =     32:    800k charAt(i),  780k cbuff[i],  571k new[i],  969k field access.   (chars/ms) 
len =     64:    800k charAt(i),  901k cbuff[i],  800k new[i],  1306k field access.   (chars/ms) 
len =    128:    1084k charAt(i),  888k cbuff[i],  633k new[i],  1620k field access.   (chars/ms) 
len =    256:    1122k charAt(i),  966k cbuff[i],  729k new[i],  1790k field access.   (chars/ms) 
len =    512:    1163k charAt(i),  1007k cbuff[i],  676k new[i],  1910k field access.   (chars/ms) 
len =   1024:    1179k charAt(i),  1027k cbuff[i],  698k new[i],  1954k field access.   (chars/ms) 
len =   2048:    1184k charAt(i),  1043k cbuff[i],  732k new[i],  2007k field access.   (chars/ms) 
len =   4096:    1188k charAt(i),  1049k cbuff[i],  742k new[i],  2031k field access.   (chars/ms) 
len =   8192:    1157k charAt(i),  1032k cbuff[i],  723k new[i],  2048k field access.   (chars/ms) 

CONCLUSION:

As you can see, server mode is much faster.

How to redirect page after click on Ok button on sweet alert?

I think this will help. It's same as given by Mr. Barmer. But I have enclosed this within php tags.

Here it goes....

    <?php if(!empty($_GET['submitted'])):?>
        <script>
        setTimeout(function() {
            swal({
                title: "Congratulaions!",
                text: "Signed up successfully, now verify your mail",
                type: "success",
                confirmButtonText: "Ok"
            }, function() {
                window.location = "index.php";
            }, 1000);
        });
        </script>   
    <?php endif;?>

How to save a Python interactive session?

Some comments were asking how to save all of the IPython inputs at once. For %save magic in IPython, you can save all of the commands programmatically as shown below, to avoid the prompt message and also to avoid specifying the input numbers. currentLine = len(In)-1 %save -f my_session 1-$currentLine

The -f option is used for forcing file replacement and the len(IN)-1 shows the current input prompt in IPython, allowing you to save the whole session programmatically.

Difference between Visual Basic 6.0 and VBA

Actually VBA can be used to compile DLLs. The Office 2000 and Office XP Developer editions included a VBA editor that could be used for making DLLs for use as COM Addins.

This functionality was removed in later versions (2003 and 2007) with the advent of the VSTO (VS Tools for Office) software, although obviously you could still create COM addins in a similar fashion without the use of VSTO (or VS.Net) by using VB6 IDE.

Reading data from XML

Alternatively, you can use XPathNavigator:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();

string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");

..

/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
                                      XPathNavigator navigator, string xpath) {
    StringBuilder sb = new StringBuilder();
    sb.Append(description);
    XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
    while (bookNodesIterator.MoveNext())
       sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
    return sb.ToString();
}

Gson - convert from Json to a typed ArrayList<T>

If you want convert from Json to a typed ArrayList , it's wrong to specify the type of the object contained in the list. The correct syntax is as follows:

 Gson gson = new Gson(); 
 List<MyClass> myList = gson.fromJson(inputString, ArrayList.class);

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Considering all of your API requests located with a url pattern of /api/.. you can tell spring to secure only this url pattern by using below configuration. Which means that you are telling spring what to secure instead of what to ignore.

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
    .csrf().disable()
     .authorizeRequests()
      .antMatchers("/api/**").authenticated()
      .anyRequest().permitAll()
      .and()
    .httpBasic().and()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

Java executors: how to be notified, without blocking, when a task completes?

You may use a implementation of Callable such that

public class MyAsyncCallable<V> implements Callable<V> {

    CallbackInterface ci;

    public MyAsyncCallable(CallbackInterface ci) {
        this.ci = ci;
    }

    public V call() throws Exception {

        System.out.println("Call of MyCallable invoked");
        System.out.println("Result = " + this.ci.doSomething(10, 20));
        return (V) "Good job";
    }
}

where CallbackInterface is something very basic like

public interface CallbackInterface {
    public int doSomething(int a, int b);
}

and now the main class will look like this

ExecutorService ex = Executors.newFixedThreadPool(2);

MyAsyncCallable<String> mac = new MyAsyncCallable<String>((a, b) -> a + b);
ex.submit(mac);

Select subset of columns in data.table R

If it's not mandatory to specify column names:

> cor(dt[, !c(1:3, 5)])
             V4          V6          V7         V8          V9         V10
V4   1.00000000 -0.50472635 -0.07123705  0.9089868 -0.17232607 -0.77988709
V6  -0.50472635  1.00000000  0.05757776 -0.2374420  0.67334474  0.29476983
V7  -0.07123705  0.05757776  1.00000000 -0.1812176 -0.36093750  0.01102428
V8   0.90898683 -0.23744196 -0.18121755  1.0000000  0.21372140 -0.75798418
V9  -0.17232607  0.67334474 -0.36093750  0.2137214  1.00000000 -0.01179544
V10 -0.77988709  0.29476983  0.01102428 -0.7579842 -0.01179544  1.00000000

How to calculate growth with a positive and negative number?

Simplest solution is the following:

=(NEW/OLD-1)*SIGN(OLD)

The SIGN() function will result in -1 if the value is negative and 1 if the value is positive. So multiplying by that will conditionally invert the result if the previous value is negative.

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

Adding JPanel to JFrame

Test2 test = new Test2();
...
frame.add(test, BorderLayout.CENTER);

Are you sure of this? test is NOT a component! To do what you're trying to do you should let Test2 extend JPanel !

jQuery: How to get the event object in an event handler function without passing it as an argument?

If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:

Markup:

  <a href="#" id="link1" >click</a>

Javascript:

  $(document).ready(function(){
      $("#link1").click(clickWithEvent);  //Bind the click event to the link
  });
  function clickWithEvent(evt){
     myFunc('p1', 'p2', 'p3');
     function myFunc(p1,p2,p3){  //Defined as local function, but has access to evt
        alert(evt.type);        
     }
  }

Since the event ob

How to get a string between two characters?

public String getStringBetweenTwoChars(String input, String startChar, String endChar) {
    try {
        int start = input.indexOf(startChar);
        if (start != -1) {
            int end = input.indexOf(endChar, start + startChar.length());
            if (end != -1) {
                return input.substring(start + startChar.length(), end);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return input; // return null; || return "" ;
}

Usage :

String input = "test string (67)";
String startChar = "(";
String endChar   = ")";
String output = getStringBetweenTwoChars(input, startChar, endChar);
System.out.println(output);
// Output: "67"

Using a dispatch_once singleton model in Swift

In swift, you can create a singleton class following way:

class AppSingleton: NSObject {

    //Shared instance of class
    static let sharedInstance = AppSingleton()

    override init() {
        super.init()
    }
}

Drop all tables command

To delete also views add 'view' keyword:

delete from sqlite_master where type in ('view', 'table', 'index', 'trigger');

Meaning of - <?xml version="1.0" encoding="utf-8"?>

This is the XML optional preamble.

  • version="1.0" means that this is the XML standard this file conforms to
  • encoding="utf-8" means that the file is encoded using the UTF-8 Unicode encoding

Android 'Unable to add window -- token null is not for an application' exception

You can continue to use getApplicationContext(), but before use, you should add this flag: dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT), and the error will not show.

And don't forget to add permission:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

What is an alternative to execfile in Python 3?

While exec(open("filename").read()) is often given as an alternative to execfile("filename"), it misses important details that execfile supported.

The following function for Python3.x is as close as I could get to having the same behavior as executing a file directly. That matches running python /path/to/somefile.py.

def execfile(filepath, globals=None, locals=None):
    if globals is None:
        globals = {}
    globals.update({
        "__file__": filepath,
        "__name__": "__main__",
    })
    with open(filepath, 'rb') as file:
        exec(compile(file.read(), filepath, 'exec'), globals, locals)

# execute the file
execfile("/path/to/somefile.py")

Notes:

  • Uses binary reading to avoid encoding issues
  • Guaranteed to close the file (Python3.x warns about this)
  • Defines __main__, some scripts depend on this to check if they are loading as a module or not for eg. if __name__ == "__main__"
  • Setting __file__ is nicer for exception messages and some scripts use __file__ to get the paths of other files relative to them.
  • Takes optional globals & locals arguments, modifying them in-place as execfile does - so you can access any variables defined by reading back the variables after running.

  • Unlike Python2's execfile this does not modify the current namespace by default. For that you have to explicitly pass in globals() & locals().

Detecting an "invalid date" Date instance in JavaScript

you can convert your date and time to milliseconds getTime()

this getTime() Method return Not a Number NaN when not valid

if(!isNaN(new Date("2012/25/255").getTime()))
  return 'valid date time';
  return 'Not a valid date time';

How to set specific Java version to Maven

You could configure compiling sources using different JDK with maven-compiler-plugin.

Just specify path to javac in <executable> tag. E.g for java11 it looks like:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <source>11</source>
        <target>11</target>
        <fork>true</fork>
        <executable>C:\Program Files\Java\jdk-11.0.1\bin\javac</executable> <!--PATH TO JAVAC -->
    </configuration>
</plugin>

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:

  1. The fd is already closed somewhere.
  2. The fd has a wrong value, which is inconsistent with the value obtained from socket() api

AddRange to a Collection

No, this seems perfectly reasonable. There is a List<T>.AddRange() method that basically does just this, but requires your collection to be a concrete List<T>.

How can I wait for a thread to finish with .NET?

The previous two answers are great and will work for simple scenarios. There are other ways to synchronize threads, however. The following will also work:

public void StartTheActions()
{
    ManualResetEvent syncEvent = new ManualResetEvent(false);

    Thread t1 = new Thread(
        () =>
        {
            // Do some work...
            syncEvent.Set();
        }
    );
    t1.Start();

    Thread t2 = new Thread(
        () =>
        {
            syncEvent.WaitOne();

            // Do some work...
        }
    );
    t2.Start();
}

ManualResetEvent is one of the various WaitHandle's that the .NET framework has to offer. They can provide much richer thread synchronization capabilities than the simple, but very common tools like lock()/Monitor, Thread.Join, etc.

They can also be used to synchronize more than two threads, allowing complex scenarios such as a 'master' thread that coordinates multiple 'child' threads, multiple concurrent processes that are dependent upon several stages of each other to be synchronized, etc.

Multiple definition of ... linker error

Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)

How to install 2 Anacondas (Python 2 and 3) on Mac OS

This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.

  1. Install anaconda. Latest version can be found here
  2. Open the navigator by typing anaconda-navigator in terminal
  3. Open environments. Click on create and then choose your python version in that.
  4. Now new environment will be created for your python version and you can install the IDE's(which are listed there) just by clicking install in that.
  5. Launch the IDE in your environment so that that IDE will use the specified version for that environment.

Hope it helps!!

Prevent scroll-bar from adding-up to the Width of page on Chrome

All you need to do is add:

html {
    overflow-y: scroll;
}

In your css file as this will have the scroller whether it is needed or not though you just won't be able to scroll

This means that the viewport will have the same width for both

How do I specify "close existing connections" in sql script

Go to management studio and do everything you describe, only instead of clicking OK, click on Script. It will show the code it will run which you can then incorporate in your scripts.

In this case, you want:

ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

vi/vim editor, copy a block (not usual action)

just use V to select lines or v to select chars or Ctrlv to select a block.

When the selection spans the area you'd like to copy just hit y and use p to paste it anywhere you like...

Validate form field only on submit or user input

Invoking of validation on form element could be handled by triggering change event on this element:

a) exemple: trigger change on separated element in form

$scope.formName.elementName.$$element.change();

b) exemple: trigger change event for each of form elements for example on ng-submit, ng-click, ng-blur ...

vm.triggerChangeForFormElements = function() {
    // trigger change event for each of form elements
    angular.forEach($scope.formName, function (element, name) {
        if (!name.startsWith('$')) {
            element.$$element.change();
        }
    });
};

c) and one more way for that

    var handdleChange = function(form){
        var formFields = angular.element(form)[0].$$controls;
        angular.forEach(formFields, function(field){
            field.$$element.change();
        });
    };

How can I open the interactive matplotlib window in IPython notebook?

According to the documentation, you should be able to switch back and forth like this:

In [2]: %matplotlib inline 
In [3]: plot(...)

In [4]: %matplotlib qt  # wx, gtk, osx, tk, empty uses default
In [5]: plot(...) 

and that will pop up a regular plot window (a restart on the notebook may be necessary).

I hope this helps.

How to verify CuDNN installation?

Installing CuDNN just involves placing the files in the CUDA directory. If you have specified the routes and the CuDNN option correctly while installing caffe it will be compiled with CuDNN.

You can check that using cmake. Create a directory caffe/build and run cmake .. from there. If the configuration is correct you will see these lines:

-- Found cuDNN (include: /usr/local/cuda-7.0/include, library: /usr/local/cuda-7.0/lib64/libcudnn.so)

-- NVIDIA CUDA:
--   Target GPU(s)     :   Auto
--   GPU arch(s)       :   sm_30
--   cuDNN             :   Yes

If everything is correct just run the make orders to install caffe from there.

Using SSIS BIDS with Visual Studio 2012 / 2013

First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]

Basically this question has the title ...Visual Studio 2012 / 2013 What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.

So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj project. Now this computer does not yet have sql server installed on it yet.

Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates

Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.

In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396

How to change href of <a> tag on button click through javascript

<a href="#" id="a" onclick="ChangeHref()">1.Change 2.Go</a>

<script>
function ChangeHref(){
document.getElementById("a").setAttribute("onclick", "location.href='http://religiasatanista.ro'");
}
</script>

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

I have the same problem and fix by add "new." before the field is updated. And I post full trigger here for someone to want to write a trigger

DELIMITER $$

USE `nc`$$

CREATE
    TRIGGER `nhachung_province_count_update` BEFORE UPDATE ON `nhachung` 
    FOR EACH ROW BEGIN

    DECLARE slug_province VARCHAR(128);
    DECLARE slug_district VARCHAR(128);

    IF old.status!=new.status THEN  /* neu doi status */
        IF new.status="Y" THEN
            UPDATE province SET `count`=`count`+1 WHERE id = new.district_id;
        ELSE 
            UPDATE province SET `count`=`count`-1 WHERE id = new.district_id;
        END IF;
    ELSEIF old.province_id!=new.province_id THEN /* neu doi province_id + district_id */

        UPDATE province SET `count`=`count`+1 WHERE id = new.province_id; /* province_id */
        UPDATE province SET `count`=`count`-1 WHERE id = old.province_id;
        UPDATE province SET `count`=`count`+1 WHERE id = new.district_id; /* district_id */
        UPDATE province SET `count`=`count`-1 WHERE id = old.district_id;

        SET slug_province = ( SELECT slug FROM province WHERE id= new.province_id LIMIT 0,1 );
        SET slug_district = ( SELECT slug FROM province WHERE id= new.district_id LIMIT 0,1 );
        SET new.prov_dist_url=CONCAT(slug_province, "/", slug_district);

    ELSEIF old.district_id!=new.district_id THEN 

        UPDATE province SET `count`=`count`+1 WHERE id = new.district_id;
        UPDATE province SET `count`=`count`-1 WHERE id = old.district_id;

        SET slug_province = ( SELECT slug FROM province WHERE id= new.province_id LIMIT 0,1 );
        SET slug_district = ( SELECT slug FROM province WHERE id= new.district_id LIMIT 0,1 );
        SET new.prov_dist_url=CONCAT(slug_province, "/", slug_district);

    END IF;


    END;
$$

DELIMITER ;

Hope this help someone

How to properly use unit-testing's assertRaises() with NoneType objects?

The problem is the TypeError gets raised 'before' assertRaises gets called since the arguments to assertRaises need to be evaluated before the method can be called. You need to pass a lambda expression like:

self.assertRaises(TypeError, lambda: self.testListNone[:1])

Generating UML from C++ code?

StarUML does just that and it is free. Unfortunately it hasn't been updated for a while. There were a couple of offshoot projects (as the project admins wouldn't allow it to be taken over) but they too have died a death.

How to draw a graph in PHP?

There are a number of libraries available for generating graphs.

More are listed above and here.

How can I change the color of AlertDialog title and the color of the line under it

If your using custom title layout then you can use it like alertDialog.setCustomTitle(customTitle);

Example

On UI thread use dialog like:

 LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
 View customTitle = inflater.inflate(R.layout.customtitlebar, null);
 AlertDialog.Builder d = new AlertDialog.Builder(this);
 d.setCustomTitle(customTitle);
 d.setMessage("Message");
 d.setNeutralButton("OK", null);
 d.show();

customtitlebar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#525f67">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_launcher"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true" >
    </ImageView>

    <TextView
        android:id="@+id/customtitlebar"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textColor="#ffffff"
        android:text="Title Name"
        android:padding="3px"
        android:textStyle="bold" 
        android:layout_toRightOf="@id/icon"
        android:layout_alignParentTop="true"
        android:gravity="center_vertical"/>

     <ImageView
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="#ff0000" 
        android:layout_below="@id/icon"><!-- This is line below the title -->
    </ImageView>

</RelativeLayout>

How to select records without duplicate on just one field in SQL?

Duplicate rows can be removed for Complex Queries by,

First storing the result to a #TempTable or @TempTableVariable

Delete from #TempTable or @TempTableVariable where your condition

Then select the rest of the data.

If need to create a row number create an identity column.

What is the purpose of the "final" keyword in C++11 for functions?

What you are missing, as idljarn already mentioned in a comment is that if you are overriding a function from a base class, then you cannot possibly mark it as non-virtual:

struct base {
   virtual void f();
};
struct derived : base {
   void f() final;       // virtual as it overrides base::f
};
struct mostderived : derived {
   //void f();           // error: cannot override!
};

Directory index forbidden by Options directive

The Problem

Indexes visible in a web browser for directories that do not contain an index.html or index.php file.

I had a lot of trouble with the configuration on Scientific Linux's httpd web server to stop showing these indexes.

The Configuration that did not work

httpd.conf virtual host directory directives:

<Directory /home/mydomain.com/htdocs>
    Options FollowSymLinks
    AllowOverride all
    Require all granted
</Directory>

and the addition of the following line to .htaccess:

Options -Indexes

Directory indexes were still showing up. .htaccess settings weren't working!

How could that be, other settings in .htaccess were working, so why not this one? What's going? It should be working! %#$&^$%@# !!

The Fix

Change httpd.conf's Options line to:

Options +FollowSymLinks

and restart the webserver.

From Apache's core mod page: ( https://httpd.apache.org/docs/2.4/mod/core.html#options )

Mixing Options with a + or - with those without is not valid syntax and will be rejected during server startup by the syntax check with an abort.

Voilà directory indexes were no longer showing up for directories that did not contain an index.html or index.php file.

Now What! A New Wrinkle

New entries started to show up in the 'error_log' when such a directory access was attempted:

[Fri Aug 19 02:57:39.922872 2016] [autoindex:error] [pid 12479] [client aaa.bbb.ccc.ddd:xxxxx] AH01276: Cannot serve directory /home/mydomain.com/htdocs/dir-without-index-file/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive

This entry is from the Apache module 'autoindex' with a LogLevel of 'error' as indicated by [autoindex:error] of the error message---the format is [module_name:loglevel].

To stop these new entries from being logged, the LogLevel needs to be changed to a higher level (e.g. 'crit') to log fewer---only more serious error messages.

Apache 2.4 LogLevels

See Apache 2.4's core directives for LogLevel.

emerg, alert, crit, error, warn, notice, info, debug, trace1, trace2, trace3, tracr4, trace5, trace6, trace7, trace8

Each level deeper into the list logs all the messages of any previous level(s).

Apache 2.4's default level is 'warn'. Therefore, all messages classified as emerg, alert, crit, error, and warn are written to error_log.

Additional Fix to Stop New error_log Entries

Added the following line inside the <Directory>..</Directory> section of httpd.conf:

LogLevel crit

The Solution 1

My virtual host's httpd.conf <Directory>..</Directory> configuration:

<Directory /home/mydomain.com/htdocs>
    Options +FollowSymLinks
    AllowOverride all
    Require all granted
    LogLevel crit
</Directory>

and adding to /home/mydomain.com/htdocs/.htaccess, the root directory of your website's .htaccess file:

Options -Indexes

If you don't mind the 'error' level messages, omit

LogLevel crit

Scientific Linux - Solution 2 - Disables mod_autoindex

No more autoindex'ing of directories inside your web space. No changes to .htaccess. But, need access to the httpd configuration files in /etc/httpd

  1. Edit /etc/httpd/conf.modules.d/00-base.conf and comment the line:

    LoadModule autoindex_module modules/mod_autoindex.so
    

    by adding a # in front of it then save the file.

  2. In the directory /etc/httpd/conf.d rename (mv)

    sudo mv autoindex.conf autoindex.conf.<something_else>
    
  3. Restart httpd:

    sudo httpd -k restart
    

    or

    sudo apachectl restart
    

The autoindex_mod is now disabled.

Linux distros with ap2dismod/ap2enmod Commands

Disable autoindex module enter the command

    sudo a2dismod autoindex

to enable autoindex module enter

    sudo a2enmod autoindex

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

@angular/material/index.d.ts' is not a module

After upgrading to Angular 9 (released today), I ran into this issue as well and found that they made the breaking change mentioned in the answer. I can't find a reason for why they made this change.

I have a material.module.ts file that I import / export all the material components (not the most efficient, but useful for quick development). I went through and updated all my imports to the individual material folders, although an index.ts barrel might be better. Again, not sure why they made this change, but I'm guessing it has to do with tree-shaking efficiencies.

Including my material.module.ts below in case it helps anyone, it's inspired off other material modules I've found:

NOTE: As other blog posts have mentioned and from my personal experience, be careful when using a shared module like below. I have 5~ different feature modules (lazy loaded) in my app that I imported my material module into. Out of curiosity, I stopped using the shared module and instead only imported the individual material components each feature module needed. This reduced my bundle size quite a bit, almost a 200kb reduction. I assumed that the build optimization process would properly drop any component not used by my modules, but it doesn't seem to be the case...

// material.module.ts
import { ModuleWithProviders, NgModule} from "@angular/core";
import { MAT_LABEL_GLOBAL_OPTIONS, MatNativeDateModule, MAT_DATE_LOCALE } from '@angular/material/core';
import { MatIconRegistry } from '@angular/material/icon';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatRippleModule } from '@angular/material/core';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatTreeModule } from '@angular/material/tree';

@NgModule({
    imports: [
        MatAutocompleteModule,
        MatBadgeModule,
        MatButtonModule,
        MatButtonToggleModule,
        MatCardModule,
        MatCheckboxModule,
        MatChipsModule,
        MatStepperModule,
        MatDatepickerModule,
        MatDialogModule,
        MatExpansionModule,
        MatFormFieldModule,
        MatGridListModule,
        MatIconModule,
        MatInputModule,
        MatListModule,
        MatMenuModule,
        MatPaginatorModule,
        MatProgressBarModule,
        MatProgressSpinnerModule,
        MatRadioModule,
        MatRippleModule,
        MatSelectModule,
        MatSidenavModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatSnackBarModule,
        MatSortModule,
        MatTableModule,
        MatTabsModule,
        MatToolbarModule,
        MatTooltipModule,
        MatTreeModule,
        MatNativeDateModule
    ],
    exports: [
        MatAutocompleteModule,
        MatBadgeModule,
        MatButtonModule,
        MatButtonToggleModule,
        MatCardModule,
        MatCheckboxModule,
        MatChipsModule,
        MatStepperModule,
        MatDatepickerModule,
        MatDialogModule,
        MatExpansionModule,
        MatFormFieldModule,
        MatGridListModule,
        MatIconModule,
        MatInputModule,
        MatListModule,
        MatMenuModule,
        MatPaginatorModule,
        MatProgressBarModule,
        MatProgressSpinnerModule,
        MatRadioModule,
        MatRippleModule,
        MatSelectModule,
        MatSidenavModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatSnackBarModule,
        MatSortModule,
        MatTableModule,
        MatTabsModule,
        MatToolbarModule,
        MatTooltipModule,
        MatTreeModule,
        MatNativeDateModule
    ],
    providers: [     
    ]
})
export class MaterialModule {
    constructor(public matIconRegistry: MatIconRegistry) {
        // matIconRegistry.registerFontClassAlias('fontawesome', 'fa');
    }

    static forRoot(): ModuleWithProviders<MaterialModule> {
        return {
            ngModule: MaterialModule,
            providers: [MatIconRegistry]
        };
    }
}

How to get input textfield values when enter key is pressed in react js?

Use onKeyDown event, and inside that check the key code of the key pressed by user. Key code of Enter key is 13, check the code and put the logic there.

Check this example:

_x000D_
_x000D_
class CartridgeShell extends React.Component {_x000D_
_x000D_
   constructor(props) {_x000D_
      super(props);_x000D_
      this.state = {value:''}_x000D_
_x000D_
      this.handleChange = this.handleChange.bind(this);_x000D_
      this.keyPress = this.keyPress.bind(this);_x000D_
   } _x000D_
 _x000D_
   handleChange(e) {_x000D_
      this.setState({ value: e.target.value });_x000D_
   }_x000D_
_x000D_
   keyPress(e){_x000D_
      if(e.keyCode == 13){_x000D_
         console.log('value', e.target.value);_x000D_
         // put the login here_x000D_
      }_x000D_
   }_x000D_
_x000D_
   render(){_x000D_
      return(_x000D_
         <input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />_x000D_
      )_x000D_
    }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<CartridgeShell/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
_x000D_
<div id = 'app' />
_x000D_
_x000D_
_x000D_

Note: Replace the input element by Material-Ui TextField and define the other properties also.

Generate random number between two numbers in JavaScript

This is about nine years late, but randojs.com makes this a simple one-liner:

rando(1, 6)

You just need to add this to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.

<script src="https://randojs.com/1.0.0.js"></script>

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

Several fixes:

  1. Use the right driver class name for your environment: if you are using an out-of-process Derby server, then you want ClientDriver (and need to use derbyclient.jar), the hostname and port, etc. If you want an in-process Derby server, then you want derby.jar, EmbeddedDriver, and a URL that is appropriate for an embedded database.

  2. Put your driver JAR file only in Tomcat's lib/ directory.

  3. Don't put anything in Tomcat's conf/context.xml: there's really no reason for it. Instead, use your webapp's META-INF/context.xml to define your <Resource>.

The error "Cannot create JDBC driver of class '' for connect URL 'null' usually occurs because the JDBC driver is not in the right place (or in too many places, like Tomcat's lib/ directory but also in the webapp's WEB-INF/lib/ directory). Please verify that you have the right driver JAR file in the right place.

Importing CSV File to Google Maps

We have now (jan2017) a csv layer import inside Google Maps itself.enter image description here

Google Maps > "Your Places" > "Open in My Maps"

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

Does Eclipse have line-wrap

As mentioned in the post by VonC on this same page. Eclipse now has this capability as of 06/2016 Neon.

Try this plugin Eclipse platform plugin

It looks like eclipse only has the ability to do it manually on its own and here are the commands. At that point you must reformat the highlighted text manually.

It's not terribly obvious how to control Eclipse line width and line wrapping in your Java source files. Here's how and where:

Comment width and line wrapping is set in Preferences->Java->Code Style->Formatter, then click on the Edit button and select the Comments tab. I like Line Width for Comments to be 120.

Code line wrapping is set nearby, in Preferences->Java->Code Style- >Formatter, then click on the Edit button and select the Line Wrapping tab. I like a line width of 120 and indent size of 4.

Indentation is set separately, in Preferences->Java->Code Style- >Formatter, then click on the Edit button and select the Indentation tab. I like an indent size of 4, consistent with the Line Wrapping indent setting.

As if that's not enough, you can also set printer margins, tab size, etc, in Preferences>General>Editors>Text Editors where I set the Displayed Tab Width to 4 and Print Margin Column to 120 or more.

You can also check the Show Print Margin box to get a faint vertical line at the printer margin column

What is the difference between procedural programming and functional programming?

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast with the procedural programming style that emphasizes changes in state.

Difference between <input type='submit' /> and <button type='submit'>text</button>

In summary :

<input type="submit">

<button type="submit"> Submit </button>

Both by default will visually draw a button that performs the same action (submit the form).

However, it is recommended to use <button type="submit"> because it has better semantics, better ARIA support and it is easier to style.

Is there a Public FTP server to test upload and download?

I have found an FTP server and its working. I was successfully able to upload a file to this FTP server and then see file created by hitting same url. Visit here and read properly before use. Good luck...!

Edit: link is now dead, but the FTP server is still up! Connect with the username "anonymous" and an email address as a password: ftp://ftp.swfwmd.state.fl.us

BUT FIRST read this before using it

Gradient text color

_x000D_
_x000D_
@import url(https://fonts.googleapis.com/css?family=Roboto+Slab:400);_x000D_
_x000D_
body {_x000D_
  background: #222;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  display: table;_x000D_
  margin: 0 auto;_x000D_
  font-family: "Roboto Slab";_x000D_
  font-weight: 600;_x000D_
  font-size: 7em;_x000D_
  background: linear-gradient(330deg, #e05252 0%, #99e052 25%, #52e0e0 50%, #9952e0 75%, #e05252 100%);_x000D_
  -webkit-background-clip: text;_x000D_
  -webkit-text-fill-color: transparent;_x000D_
  line-height: 200px;_x000D_
}
_x000D_
<h1>beautiful</h1>
_x000D_
_x000D_
_x000D_

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Have you tried editing the shell entry in account settings.

Go to the Accounts preferences, unlock, and right-click on your user account for the Advanced Settings dialog. Your shell should be /bin/zsh, and you can edit that invocation appropriately (i.e. add the --login argument).

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

undefined reference to `std::ios_base::Init::Init()'

Most of these linker errors occur because of missing libraries.

I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.

That solved it for me on Xcode 6.3.2 for iOS 8.3

Cheers!

Custom header to HttpClient request

There is a Headers property in the HttpRequestMessage class. You can add custom headers there, which will be sent with each HTTP request. The DefaultRequestHeaders in the HttpClient class, on the other hand, sets headers to be sent with each request sent using that client object, hence the name Default Request Headers.

Hope this makes things more clear, at least for someone seeing this answer in future.

Nginx: stat() failed (13: permission denied)

I've just had the same problem on a CentOS 7 box.

Seems I'd hit selinux. Putting selinux into permissive mode (setenforce permissive) has worked round the problem for now. I'll try and get back with a proper fix.

Counting number of occurrences in column?

Just adding some extra sorting if needed

=QUERY(A2:A,"select A, count(A) where A is not null group by A order by count(A) DESC label A 'Name', count(A) 'Count'",-1)

enter image description here

How to trap the backspace key using jQuery?

Regular javascript can be used to trap the backspace key. You can use the event.keyCode method. The keycode is 8, so the code would look something like this:

if (event.keyCode == 8) {
    // Do stuff...
}

If you want to check for both the [delete] (46) as well as the [backspace] (8) keys, use the following:

if (event.keyCode == 8 || event.keyCode == 46) {
    // Do stuff...
}

Understanding Linux /proc/id/maps

memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more

How to invoke function from external .c file in C?

use #include "ClasseAusiliaria.c" [Dont use angle brackets (< >) ]

and I prefer save file with .h extension in the same Directory/folder.

#include "ClasseAusiliaria.h"

Print array without brackets and commas

I have used Arrays.toString(array_name).replace("[","").replace("]","").replace(", ",""); as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.

How can I autoplay a video using the new embed code style for Youtube?

None of yours are solved my problem. But, I found a good solution for me to work properly right now. In between tags write this code:

<div style="position: fixed; z-index: -99; width: 100%; height: 100%">
  <iframe frameborder="0" height="100%" width="100%" 
    src="https://youtube.com/embed/**[CHANGE HERE WITH YOUR YOUTUBE VIDEO ID]**?autoplay=1&controls=0&showinfo=0&autohide=1">
  </iframe>
</div>

click or change event on radio using jquery

This code worked for me:

$(function(){

    $('input:radio').change(function(){
        alert('changed');   
    });          

});

http://jsfiddle.net/3q29L/

Compare two files and write it to "match" and "nomatch" files

Though its really long back this question was posted, I wish to answer as it might help others. This can be done easily by means of JOINKEYS in a SINGLE step. Here goes the pseudo code:

  • Code JOINKEYS PAIRED(implicit) and get both the records via reformatting filed. If there is NO match from either of files then append/prefix some special character say '$'
  • Compare via IFTHEN for '$', if exists then it doesnt have a paired record, it'll be written into unpaired file and rest to paired file.

Please do get back incase of any questions.

complex if statement in python

if
  ...
  # several checks
  ...
elif ((var1 > 65535) or ((var1 < 1024)) and (var1 != 80) and (var1 != 443)):
  # fail
else
  ...

You missed a parenthesis.

Mounting multiple volumes on a docker container?

Docker now recommends migrating towards using --mount.

Multiple volume mounts are also explained in detail in the current Docker documentation.

From: https://docs.docker.com/storage/bind-mounts/

$ docker run -d \
  -it \
  --name devtest \
  --mount type=bind,source="$(pwd)"/target,target=/app \
  --mount type=bind,source="$(pwd)"/target,target=/app2,readonly,bind-propagation=rslave \
  nginx:latest

Original older answer should still work; just trying to keep the answer aligned to current best known method.

How to set the matplotlib figure default size in ipython notebook?

Worked liked a charm for me:

matplotlib.rcParams['figure.figsize'] = (20, 10)

How to save LogCat contents to file?

Open command prompt and locate your adb.exe(it will be in your android-sdk/platform-tools)

adb logcat -d > <path-where-you-want-to-save-file>/filename.txt

If you omit path, it will save logcat in current working directory

The -d option indicates that you are dumping the current contents and then exiting. Prefer notepad++ to open this file so that you can get everything in a proper readable format.

How to deploy a war file in Tomcat 7

step-1. here I'm deploying pos.war First go to tomcat webapps folder and paste it

enter image description here

step-2. go to tomcat->bin folder start tomcat by clicking startup.bat

step-3. go to browser write localhost:port/project name eg. localhost:8080/pos (here my tomcat run on port 8080)

Done....

enter image description here

Git Pull vs Git Rebase

git-pull - Fetch from and integrate with another repository or a local branch GIT PULL

Basically you are pulling remote branch to your local, example:

git pull origin master

Will pull master branch into your local repository

git-rebase - Forward-port local commits to the updated upstream head GIT REBASE

This one is putting your local changes on top of changes done remotely by other users. For example:

  • You have committed some changes on your local branch for example called SOME-FEATURE
  • Your friend in the meantime was working on other features and he merged his branch into master

Now you want to see his and your changes on your local branch. So then you checkout master branch:

git checkout master

then you can pull:

git pull origin master

and then you go to your branch:

git checkout SOME-FEATURE

and you can do rebase master to get lastest changes from it and put your branch commits on top:

git rebase master

I hope now it's a bit more clear for you.

Android: how to parse URL String with spaces to URI object?

URL url = Test.class.getResource(args[0]);  // reading demo file path from                                                   
                                            // same location where class                                    
File input=null;
try {
    input = new File(url.toURI());
} catch (URISyntaxException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

Uncaught TypeError: Cannot set property 'value' of null

h_url=document.getElementById("u") is null here

There is no element exist with id as u

Gradle DSL method not found: 'runProguard'

By changing runProguard to minifyEnabled, part of the issue gets fixed.

But the fix can cause "Library Projects cannot set application Id" (you can find the fix for this here Android Studio 1.0 and error "Library projects cannot set applicationId").

By removing application Id in the build.gradle file, you should be good to go.

React eslint error missing in props validation

I know this answer is ridiculous, but consider just disabling this rule until the bugs are worked out or you've upgraded your tooling:

/* eslint-disable react/prop-types */ // TODO: upgrade to latest eslint tooling

Or disable project-wide in your eslintrc:

"rules": {
  "react/prop-types": "off"
}

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

Instead of mysql_connect use mysqli_connect.

mysqli is provide a functionality for connect multiple database at a time.

$Db1 = new mysqli($hostname,$username,$password,$db_name1); 
// this is connection 1 for DB 1

$Db2 = new mysqli($hostname,$username,$password,$db_name2); 
// this is connection 2 for DB 2

No Network Security Config specified, using platform default - Android Log

I have a same problem, with volley, but this is my solution:

  1. In Android Manifiest, in tag application add:

    android:usesCleartextTraffic="true"
    android:networkSecurityConfig="@xml/network_security_config"
    
  2. create in folder xml this file network_security_config.xml and write this:

    <?xml version="1.0" encoding="utf-8"?>
      <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
      </network-security-config>
    
  3. inside tag application add this tag:

    <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    

CSS media query to target iPad and iPad only?

These days you can use a Media Queries Level 4 feature to check if the device has the ability to 'hover' over elements.

@media (hover: hover) { ... }

Since the ipad has no 'hover' state you can effectively target touch devices like the ipad.

Bash script processing limited number of commands in parallel

Use the wait built-in:

process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait

For the above example, 4 processes process1 ... process4 would be started in the background, and the shell would wait until those are completed before starting the next set.

From the GNU manual:

wait [jobspec or pid ...]

Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.

How can I find a specific element in a List<T>?

You can create a search variable to hold your searching criteria. Here is an example using database.

 var query = from o in this.mJDBDataset.Products 
             where o.ProductStatus == textBox1.Text || o.Karrot == textBox1.Text 
             || o.ProductDetails == textBox1.Text || o.DepositDate == textBox1.Text 
             || o.SellDate == textBox1.Text
             select o;

 dataGridView1.DataSource = query.ToList();

 //Search and Calculate
 search = textBox1.Text;
 cnn.Open();
 string query1 = string.Format("select * from Products where ProductStatus='"
               + search +"'");
 SqlDataAdapter da = new SqlDataAdapter(query1, cnn);
 DataSet ds = new DataSet();
 da.Fill(ds, "Products");
 SqlDataReader reader;
 reader = new SqlCommand(query1, cnn).ExecuteReader();

 List<double> DuePayment = new List<double>();

 if (reader.HasRows)
 {

  while (reader.Read())
  {

   foreach (DataRow row in ds.Tables["Products"].Rows)
   {

     DuePaymentstring.Add(row["DuePayment"].ToString());
     DuePayment = DuePaymentstring.Select(x => double.Parse(x)).ToList();

   }
  }

  tdp = 0;
  tdp = DuePayment.Sum();                        
  DuePaymentstring.Remove(Convert.ToString(DuePaymentstring.Count));
  DuePayment.Clear();
 }
 cnn.Close();
 label3.Text = Convert.ToString(tdp + " Due Payment Count: " + 
 DuePayment.Count + " Due Payment string Count: " + DuePaymentstring.Count);
 tdp = 0;
 //DuePaymentstring.RemoveRange(0,DuePaymentstring.Count);
 //DuePayment.RemoveRange(0, DuePayment.Count);
 //Search and Calculate

Here "var query" is generating the search criteria you are giving through the search variable. Then "DuePaymentstring.Select" is selecting the data matching your given criteria. Feel free to ask if you have problem understanding.

How to convert list data into json in java

JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();

List<String> ls =new  ArrayList<String>();

for(product cj:cities.getList()) {
    ls.add(cj);
    JSONObject formDetailsJson = new JSONObject();
    formDetailsJson.put("id", cj.id);
    formDetailsJson.put("name", cj.name);
    jsonArray.put(formDetailsJson);
}

responseDetailsJson.put("Cities", jsonArray);

return responseDetailsJson;

Does C# have an equivalent to JavaScript's encodeURIComponent()?

I tried to do full compatible analog of javascript's encodeURIComponent for c# and after my 4 hour experiments I found this

c# CODE:

string a = "!@#$%^&*()_+ some text here ??? ??????? ????";
a = System.Web.HttpUtility.UrlEncode(a);
a = a.Replace("+", "%20");

the result is: !%40%23%24%25%5e%26*()_%2b%20some%20text%20here%20%d0%b0%d0%bb%d0%b8%20%d0%bc%d0%b0%d0%bc%d0%b5%d0%b4%d0%be%d0%b2%20%d0%b1%d0%b0%d0%ba%d1%83

After you decode It with Javascript's decodeURLComponent();

you will get this: !@#$%^&*()_+ some text here ??? ??????? ????

Thank You for attention

Group by month and year in MySQL

You must do something like this

SELECT onDay, id, 
sum(pxLow)/count(*),sum(pxLow),count(`*`),
CONCAT(YEAR(onDay),"-",MONTH(onDay)) as sdate 
FROM ... where stockParent_id =16120 group by sdate order by onDay

pass array to method Java

In this way we can pass an array to a function, here this print function will print the contents of the array.

public class PassArrayToFunc {

    public static void print(char [] arr) {
        for(int i = 0 ; i<arr.length;i++) {
            System.out.println(arr[i]);
        }
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        char [] array = scan.next().toCharArray();
        print(array);
        scan.close();
    }

}

How do I save a stream to a file in C#?

//If you don't have .Net 4.0  :)

public void SaveStreamToFile(Stream stream, string filename)
{  
   using(Stream destination = File.Create(filename))
      Write(stream, destination);
}

//Typically I implement this Write method as a Stream extension method. 
//The framework handles buffering.

public void Write(Stream from, Stream to)
{
   for(int a = from.ReadByte(); a != -1; a = from.ReadByte())
      to.WriteByte( (byte) a );
}

/*
Note, StreamReader is an IEnumerable<Char> while Stream is an IEnumbable<byte>.
The distinction is significant such as in multiple byte character encodings 
like Unicode used in .Net where Char is one or more bytes (byte[n]). Also, the
resulting translation from IEnumerable<byte> to IEnumerable<Char> can loose bytes
or insert them (for example, "\n" vs. "\r\n") depending on the StreamReader instance
CurrentEncoding.
*/

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

At the risk of being flamed for using C constructs, I do think this sscanf example is more elegant than most Boost solutions. And you don't have to worry about linkage if you're running anywhere that has a Python interpreter!

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    for (int i = 1; i != argc; ++i) {
        int number = 0;
        int size = 0;
        sscanf(argv[i], "--foo=%d%n", &number, &size);
        if (size == strlen(argv[i])) {
            printf("number: %d\n", number);
        }
        else {
            printf("not-a-number\n");
        }
    }
    return 0;
}

Here's some example output that demonstrates the solution handles leading/trailing garbage as correctly as the equivalent Python code, and more correctly than anything using atoi (which will erroneously ignore a non-numeric suffix).

$ ./scan --foo=2 --foo=2d --foo='2 ' ' --foo=2'
number: 2
not-a-number
not-a-number
not-a-number

Get pixel color from canvas, on mousemove

If you need to get the average color of a rectangular area, rather than the color of a single pixel, please take a look at this other question:

JavaScript - Get average color from a certain area of an image

Anyway, both are done in a very similar way:

Getting The Color/Value of A Single Pixel from An Image or Canvas

To get the color of a single pixel, you would first draw that image to a canvas, which you have already done:

const image = document.getElementById('image');
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const width = image.width;
const height = image.height;

canvas.width = width;
canvas.height = height;

context.drawImage(image, 0, 0, width, height);

And then get the value of a single pixel like this:

const data = context.getImageData(X, Y, 1, 1).data;

// RED   = data[0]
// GREEN = data[1]
// BLUE  = data[2]
// ALPHA = data[3]

Speeding Thins Up by Getting all ImageData at Once

You need to use this same CanvasRenderingContext2D.getImageData() to get the values of the whole image, which you do by changing its third and fourth params. The signature of that function is:

ImageData ctx.getImageData(sx, sy, sw, sh);
  • sx: The x coordinate of the upper left corner of the rectangle from which the ImageData will be extracted.
  • sy: The y coordinate of the upper left corner of the rectangle from which the ImageData will be extracted.
  • sw: The width of the rectangle from which the ImageData will be extracted.
  • sh: The height of the rectangle from which the ImageData will be extracted.

You can see it returns an ImageData object, whatever that is. The important part here is that that object has a .data property which contains all our pixel values.

However, note that .data property is a 1-dimension Uint8ClampedArray, which means that all the pixel's components have been flattened, so you are getting something that looks like this:

Let's say you have a 2x2 image like this:

 RED PIXEL |       GREEN PIXEL
BLUE PIXEL | TRANSPARENT PIXEL

Then, you will get them like this:

[ 255, 0, 0, 255,    0, 255, 0, 255,    0, 0, 255, 255,    0, 0, 0, 0          ]
|   RED PIXEL   |    GREEN PIXEL   |     BLUE PIXEL   |    TRANSPAERENT  PIXEL |
|   1ST PIXEL   |      2ND PIXEL   |      3RD PIXEL   |             4TH  PIXEL | 

As calling getImageData is a slow operation, you can call it only once to get the data of all the image (sw = image width, sh = image height).

Then, in the example above, if you want to access the components of the TRANSPARENT PIXEL, that is, the one at position x = 1, y = 1 of this imaginary image, you would find its first index i in its ImageData's data property as:

const i = (y * imageData.width + x) * 4;

? Let's See It in Action

_x000D_
_x000D_
const solidColor = document.getElementById('solidColor');_x000D_
const alphaColor = document.getElementById('alphaColor');_x000D_
const solidWeighted = document.getElementById('solidWeighted');_x000D_
_x000D_
const solidColorCode = document.getElementById('solidColorCode');_x000D_
const alphaColorCode = document.getElementById('alphaColorCode');_x000D_
const solidWeightedCOde = document.getElementById('solidWeightedCode');_x000D_
_x000D_
const brush = document.getElementById('brush');_x000D_
const image = document.getElementById('image');_x000D_
const canvas = document.createElement('canvas');_x000D_
const context = canvas.getContext('2d');_x000D_
const width = image.width;_x000D_
const height = image.height;_x000D_
_x000D_
const BRUSH_SIZE = brush.offsetWidth;_x000D_
const BRUSH_CENTER = BRUSH_SIZE / 2;_x000D_
const MIN_X = image.offsetLeft + 4;_x000D_
const MAX_X = MIN_X + width - 1;_x000D_
const MIN_Y = image.offsetTop + 4;_x000D_
const MAX_Y = MIN_Y + height - 1;_x000D_
_x000D_
canvas.width = width;_x000D_
canvas.height = height;_x000D_
_x000D_
context.drawImage(image, 0, 0, width, height);_x000D_
_x000D_
const imageDataData = context.getImageData(0, 0, width, height).data;_x000D_
_x000D_
function sampleColor(clientX, clientY) {_x000D_
  if (clientX < MIN_X || clientX > MAX_X || clientY < MIN_Y || clientY > MAX_Y) {_x000D_
    requestAnimationFrame(() => {_x000D_
      brush.style.transform = `translate(${ clientX }px, ${ clientY }px)`;_x000D_
      solidColorCode.innerText = solidColor.style.background = 'rgb(0, 0, 0)';_x000D_
      alphaColorCode.innerText = alphaColor.style.background = 'rgba(0, 0, 0, 0.00)';_x000D_
      solidWeightedCode.innerText = solidWeighted.style.background = 'rgb(0, 0, 0)';_x000D_
    });_x000D_
    _x000D_
    return;_x000D_
  }_x000D_
  _x000D_
  const imageX = clientX - MIN_X;_x000D_
  const imageY = clientY - MIN_Y;_x000D_
  _x000D_
  const i = (imageY * width + imageX) * 4;_x000D_
_x000D_
  // A single pixel (R, G, B, A) will take 4 positions in the array:_x000D_
  const R = imageDataData[i];_x000D_
  const G = imageDataData[i + 1];_x000D_
  const B = imageDataData[i + 2];_x000D_
  const A = imageDataData[i + 3] / 255;_x000D_
  const iA = 1 - A;_x000D_
_x000D_
  // Alpha-weighted color:_x000D_
  const wR = (R * A + 255 * iA) | 0;_x000D_
  const wG = (G * A + 255 * iA) | 0;_x000D_
  const wB = (B * A + 255 * iA) | 0;_x000D_
_x000D_
  // Update UI:_x000D_
  _x000D_
  requestAnimationFrame(() => {_x000D_
    brush.style.transform = `translate(${ clientX }px, ${ clientY }px)`;_x000D_
_x000D_
    solidColorCode.innerText = solidColor.style.background_x000D_
      = `rgb(${ R }, ${ G }, ${ B })`;_x000D_
_x000D_
    alphaColorCode.innerText = alphaColor.style.background_x000D_
      = `rgba(${ R }, ${ G }, ${ B }, ${ A.toFixed(2) })`;_x000D_
_x000D_
    solidWeightedCode.innerText = solidWeighted.style.background_x000D_
      = `rgb(${ wR }, ${ wG }, ${ wB })`;_x000D_
  });_x000D_
}_x000D_
_x000D_
document.onmousemove = (e) => sampleColor(e.clientX, e.clientY);_x000D_
  _x000D_
sampleColor(MIN_X, MIN_Y);
_x000D_
body {_x000D_
  margin: 0;_x000D_
  height: 100vh;_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  cursor: none;_x000D_
  font-family: monospace;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#image {_x000D_
  border: 4px solid white;_x000D_
  border-radius: 2px;_x000D_
  box-shadow: 0 0 32px 0 rgba(0, 0, 0, .25);_x000D_
  width: 150px;_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
#brush {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  pointer-events: none;_x000D_
  width: 1px;_x000D_
  height: 1px;_x000D_
  mix-blend-mode: exclusion;_x000D_
  border-radius: 100%;_x000D_
}_x000D_
_x000D_
#brush::before,_x000D_
#brush::after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  background: magenta;_x000D_
}_x000D_
_x000D_
#brush::before {_x000D_
  top: -16px;_x000D_
  left: 0;_x000D_
  height: 33px;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#brush::after {_x000D_
  left: -16px;_x000D_
  top: 0;_x000D_
  width: 33px;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
#samples {_x000D_
  position: relative;_x000D_
  list-style: none;_x000D_
  padding: 0;_x000D_
  width: 250px;_x000D_
}_x000D_
_x000D_
#samples::before {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 27px;_x000D_
  width: 2px;_x000D_
  height: 100%;_x000D_
  background: black;_x000D_
  border-radius: 1px;_x000D_
}_x000D_
_x000D_
#samples > li {_x000D_
  position: relative;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  padding-left: 56px;_x000D_
}_x000D_
_x000D_
#samples > li + li {_x000D_
  margin-top: 8px;_x000D_
}_x000D_
_x000D_
.sample {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 16px;_x000D_
  transform: translate(0, -50%);_x000D_
  display: block;_x000D_
  width: 24px;_x000D_
  height: 24px;_x000D_
  border-radius: 100%;_x000D_
  box-shadow: 0 0 16px 4px rgba(0, 0, 0, .25);  _x000D_
  margin-right: 8px;_x000D_
}_x000D_
_x000D_
.sampleLabel {_x000D_
  font-weight: bold;_x000D_
  margin-bottom: 8px;_x000D_
}_x000D_
_x000D_
.sampleCode {_x000D_
  _x000D_
}
_x000D_
<img id="image" src="data:image/gif;base64,R0lGODlhSwBLAPEAACMfIO0cJAAAAAAAACH/C0ltYWdlTWFnaWNrDWdhbW1hPTAuNDU0NTUAIf4jUmVzaXplZCBvbiBodHRwczovL2V6Z2lmLmNvbS9yZXNpemUAIfkEBQAAAgAsAAAAAEsASwAAAv+Uj6mb4A+QY7TaKxvch+MPKpC0eeUUptdomOzJqnLUvnFcl7J6Pzn9I+l2IdfII8DZiCnYsYdK4qRTptAZwQKRVK71CusOgx2nFRrlhMu+33o2NEalC6S9zQvfi3Mlnm9WxeQ396F2+HcQsMjYGEBRVbhy5yOp6OgIeVIHpEnZyYCZ6cklKBJX+Kgg2riqKoayOWl2+VrLmtDqBptIOjZ6K4qAeSrL8PcmHExsgMs2dpyIxPpKvdhM/YxaTMW2PGr9GP76BN3VHTMurh7eoU14jsc+P845Vn6OTb/P/I68iYOfwGv+JOmRNHBfsV5ujA1LqM4eKDoNvXyDqItTxYX/DC9irKBlIhkKGPtFw1JDiMeS7CqWqySPZcKGHH/JHGgIpb6bCl1O0LmT57yCOqoI5UcU0YKjPXmFjMm0ZQ4NIVdGBdZRi9WrjLxJNMY1Yr4dYeuNxWApl1ALHb+KDHrTV1owlriedJgSr4Cybu/9dFiWYAagsqAGVkkzaZTAuqD9ywKWMUG9dCO3u2zWpVzIhpW122utZlrHnTN+Bq2Mqrlnqh8CQ+0Mrq3Kc++q7eo6dlB3rLuh3abPVbbbI2mxBdhWdsZhid8cr0oy9F08q0k5FXSadiyL1mF5z51a8VsQOp3/LlodkBfzmzWf2bOrtfzr48k/1hupDaLa9rUbO+zlwndfaOCURAXRNaCBqBT2BncJakWfTzSYkmCEFr60RX0V8sKaHOltCBJ1tAAFYhHaVVbig3jxp0IBADs=" >_x000D_
_x000D_
<div id="brush"></div>_x000D_
_x000D_
<ul id="samples">_x000D_
  <li>_x000D_
    <span class="sample" id="solidColor"></span>_x000D_
    <div class="sampleLabel">solidColor</div>_x000D_
    <div class="sampleCode" id="solidColorCode">rgb(0, 0, 0)</div>_x000D_
  </li>_x000D_
  <li>_x000D_
    <span class="sample" id="alphaColor"></span>_x000D_
    <div class="sampleLabel">alphaColor</div>_x000D_
    <div class="sampleCode" id="alphaColorCode">rgba(0, 0, 0, 0.00)</div>_x000D_
  </li>_x000D_
  <li>_x000D_
    <span class="sample" id="solidWeighted"></span>_x000D_
    <div class="sampleLabel">solidWeighted (with white)</div>_x000D_
    <div class="sampleCode" id="solidWeightedCode">rgb(0, 0, 0)</div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

?? Note I'm using a small data URI to avoid Cross-Origin issues if I include an external image or an answer that is larger than allowed if I try to use a longer data URI.

? These colors look weird, don't they?

If you move the cursor around the borders of the asterisk shape, you will see sometimes avgSolidColor is red, but the pixel you are sampling looks white. That's because even though the R component for that pixel might be high, the alpha channel is low, so the color is actually an almost transparent shade of red, but avgSolidColor ignores that.

On the other hand, avgAlphaColor looks pink. Well, that's actually not true, it just looks pink because we are now using the alpha channel, which makes it semitransparent and allows us to see the background of the page, which in this case is white.

Alpha-weighted color

Then, what can we do to fix this? Well, it turns out we just need to use the alpha channel and its inverse as the weights to calculate the components of our new sample, in this case merging it with white, as that's the color we use as background.

That means that if a pixel is R, G, B, A, where A is in the interval [0, 1], we will compute the inverse of the alpha channel, iA, and the components of the weighted sample as:

const iA = 1 - A;
const wR = (R * A + 255 * iA) | 0;
const wG = (G * A + 255 * iA) | 0;
const wB = (B * A + 255 * iA) | 0;

Note how the more transparent a pixel is (A closer to 0), the lighter the color.

Show/Hide the console window of a C# console application

See my post here:

Show Console in Windows Application

You can make a Windows application (with or without the window) and show the console as desired. Using this method the console window never appears unless you explicitly show it. I use it for dual-mode applications that I want to run in either console or gui mode depending on how they are opened.

psql: server closed the connection unexepectedly

In my case I was making an connection through pgAdmin with ssh tunneling and set to host field ip address but it was necessary to set localhost

DBNull if statement

Yes, just a syntax problem. Try this instead:

if (reader["usr.ursrdaystime"] != DBNull.Value)

.Equals() is checking to see if two Object instances are the same.

Getting the length of two-dimensional array

use

   System.out.print( nir[0].length);

look at this for loop which print the content of the 2 dimension array the second loop iterate over the column in each row

for(int row =0 ; row < ntr.length; ++row)
 for(int column =0; column<ntr[row].length;++column)
    System.out.print(ntr[row][column]);

Getting a list of files in a directory with a glob

You can achieve this pretty easily with the help of NSPredicate, like so:

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:bundleRoot error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"];
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];

If you need to do it with NSURL instead it looks like this:

NSURL *bundleRoot = [[NSBundle mainBundle] bundleURL];
NSArray * dirContents = 
      [fm contentsOfDirectoryAtURL:bundleRoot
        includingPropertiesForKeys:@[] 
                           options:NSDirectoryEnumerationSkipsHiddenFiles
                             error:nil];
NSPredicate * fltr = [NSPredicate predicateWithFormat:@"pathExtension='jpg'"];
NSArray * onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];

Make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

Javascript Array inside Array - how can I call the child array name?

Array is just like any other object. You can give it a name if you want.

var size = new Array("S", "M", "L", "XL", "XXL");
var color = new Array("Red", "Blue", "Green", "White", "Black");
var options = new Array( size, color);
color.name = "color";
size.name = "size";
options[0].name == "size"
>true

How to convert an array to object in PHP?

Using json_encode is problematic because of the way that it handles non UTF-8 data. It's worth noting that the json_encode/json_encode method also leaves non-associative arrays as arrays. This may or may not be what you want. I was recently in the position of needing to recreate the functionality of this solution but without using json_ functions. Here's what I came up with:

/**
 * Returns true if the array has only integer keys
 */
function isArrayAssociative(array $array) {
    return (bool)count(array_filter(array_keys($array), 'is_string'));
}

/**
 * Converts an array to an object, but leaves non-associative arrays as arrays. 
 * This is the same logic that `json_decode(json_encode($arr), false)` uses.
 */
function arrayToObject(array $array, $maxDepth = 10) {
    if($maxDepth == 0) {
        return $array;
    }

    if(isArrayAssociative($array)) {
        $newObject = new \stdClass;
        foreach ($array as $key => $value) {
            if(is_array($value)) {
                $newObject->{$key} = arrayToObject($value, $maxDepth - 1);
            } else {
                $newObject->{$key} = $value;
            }
        }
        return $newObject;
    } else {

        $newArray = array();
        foreach ($array as $value) {
            if(is_array($value)) {
                $newArray[] = arrayToObject($value, $maxDepth - 1);
            } else {
                $newArray[] = $value;
            }                
        }
        return $newArray;
    }
}

SQL Error: ORA-00933: SQL command not properly ended

Semicolon ; on the end of command had caused the same error on me.

cmd.CommandText = "INSERT INTO U_USERS_TABLE (USERNAME, PASSWORD, FIRSTNAME, LASTNAME) VALUES ("
                + "'" + txtUsername.Text + "',"
                + "'" + txtPassword.Text + "',"
                + "'" + txtFirstname.Text + "',"
                + "'" + txtLastname.Text + "');"; <== Semicolon in "" is the cause.
                                                      Removing it will be fine.

Hope it helps.

How to target only IE (any version) within a stylesheet?

Internet Explorer 9 and lower : You could use conditional comments to load an IE-specific stylesheet for any version (or combination of versions) that you wanted to specifically target.like below using external stylesheet.

<!--[if IE]>
  <link rel="stylesheet" type="text/css" href="all-ie-only.css" />
<![endif]-->

However, beginning in version 10, conditional comments are no longer supported in IE.

Internet Explorer 10 & 11 : Create a media query using -ms-high-contrast, in which you place your IE 10 and 11-specific CSS styles. Because -ms-high-contrast is Microsoft-specific (and only available in IE 10+), it will only be parsed in Internet Explorer 10 and greater.

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
     /* IE10+ CSS styles go here */
}

Microsoft Edge 12 : Can use the @supports rule Here is a link with all the info about this rule

@supports (-ms-accelerator:true) {
  /* IE Edge 12+ CSS styles go here */ 
}

Inline rule IE8 detection

I have 1 more option but it is only detect IE8 and below version.

  /* For IE css hack */
  margin-top: 10px\9 /* apply to all ie from 8 and below */
  *margin-top:10px;  /* apply to ie 7 and below */
  _margin-top:10px; /* apply to ie 6 and below */

As you specefied for embeded stylesheet. I think you need to use media query and condition comment for below version.

Android open pdf file

String dir="/Attendancesystem";

 public void displaypdf() {

        File file = null;
            file = new File(Environment.getExternalStorageDirectory()+dir+ "/sample.pdf");
        Toast.makeText(getApplicationContext(), file.toString() , Toast.LENGTH_LONG).show();
        if(file.exists()) {
            Intent target = new Intent(Intent.ACTION_VIEW);
            target.setDataAndType(Uri.fromFile(file), "application/pdf");
            target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

            Intent intent = Intent.createChooser(target, "Open File");
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                // Instruct the user to install a PDF reader here, or something
            }
        }
        else
            Toast.makeText(getApplicationContext(), "File path is incorrect." , Toast.LENGTH_LONG).show();
    }

FFmpeg on Android

I had the same issue, I found most of the answers here out dated. I ended up writing a wrapper on FFMPEG to access from Android with a single line of code.

https://github.com/madhavanmalolan/ffmpegandroidlibrary

Python Error: "ValueError: need more than 1 value to unpack"

You can't run this particular piece of code in the interactive interpreter. You'll need to save it into a file first so that you can pass the argument to it like this

$ python hello.py user338690

PHP: HTML: send HTML select option attribute in POST

just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:

<form name='add'>
Age: <select name='age'>
     <option value='1_sre'>23</option>
     <option value='2_sam>24</option>
     <option value='5_john>25</option>
     </select>
<input type='submit' name='submit'/>
</form>

How do I print bytes as hexadecimal?

C:

static void print_buf(const char *title, const unsigned char *buf, size_t buf_len)
{
    size_t i = 0;
    fprintf(stdout, "%s\n", title);
    for(i = 0; i < buf_len; ++i)
    fprintf(stdout, "%02X%s", buf[i],
             ( i + 1 ) % 16 == 0 ? "\r\n" : " " );

}

C++:

void print_bytes(std::ostream& out, const char *title, const unsigned char *data, size_t dataLen, bool format = true) {
    out << title << std::endl;
    out << std::setfill('0');
    for(size_t i = 0; i < dataLen; ++i) {
        out << std::hex << std::setw(2) << (int)data[i];
        if (format) {
            out << (((i + 1) % 16 == 0) ? "\n" : " ");
        }
    }
    out << std::endl;
}

how to add super privileges to mysql database?

You can add super privilege using phpmyadmin:

Go to PHPMYADMIN > privileges > Edit User > Under Administrator tab Click SUPER. > Go

If you want to do it through Console, do like this:

 mysql> GRANT SUPER ON *.* TO user@'localhost' IDENTIFIED BY 'password';

After executing above code, end it with:

mysql> FLUSH PRIVILEGES;

You should do in on *.* because SUPER is not the privilege that applies just to one database, it's global.

Calculate median in c#

Is there a function in the .net Math library?

No.

It's not hard to write your own though. The naive algorithm sorts the array and picks the middle (or the average of the two middle) elements. However, this algorithm is O(n log n) while its possible to solve this problem in O(n) time. You want to look at selection algorithms to get such an algorithm.

Changing an AIX password via script?

This is from : Script to change password on linux servers over ssh

The script below will need to be saved as a file (eg ./passwdWrapper) and made executable (chmod u+x ./passwdWrapper)

#!/usr/bin/expect -f
#wrapper to make passwd(1) be non-interactive
#username is passed as 1st arg, passwd as 2nd

set username [lindex $argv 0]
set password [lindex $argv 1]
set serverid [lindex $argv 2]
set newpassword [lindex $argv 3]

spawn ssh $serverid passwd
expect "assword:"
send "$password\r"
expect "UNIX password:"
send "$password\r"
expect "password:"
send "$newpassword\r"
expect "password:"
send "$newpassword\r"
expect eof

Then you can run ./passwdWrapper $user $password $server $newpassword which will actually change the password.

Note: This requires that you install expect on the machine from which you will be running the command. (sudo apt-get install expect) The script works on CentOS 5/6 and Ubuntu 14.04, but if the prompts in passwd change, you may have to tweak the expect lines.

Bootstrap 3 hidden-xs makes row narrower

How does it work if you only are using visible-md at Col4 instead? Do you use the -lg at all? If not this might work.

<div class="container">
    <div class="row">
        <div class="col-xs-4 col-sm-2 col-md-1" align="center">
            Col1
        </div>
        <div class="col-xs-4 col-sm-2" align="center">
            Col2
        </div>
        <div class="hidden-xs col-sm-6 col-md-5" align="center">
            Col3
        </div>
        <div class="visible-md col-md-3 " align="center">
            Col4
        </div>
        <div class="col-xs-4 col-sm-2 col-md-1" align="center">
            Col5
        </div>
    </div>
</div>

How to display HTML in TextView?

If you are trying to show HTML from a string resource id, the formatting may not show up on screen. If that is happening to you, try using CDATA tags instead:

strings.xml:
<string name="sample_string"><![CDATA[<h2>Title</h2><br><p>Description here</p>]]></string>

...

MainActivity.java:
text.setText(Html.fromHtml(getString(R.string.sample_string));

See this post for further details.

How do I close a single buffer (out of many) in Vim?

Those using a buffer or tree navigation plugin, like Buffergator or NERDTree, will need to toggle these splits before destroying the current buffer - else you'll send your splits into wonkyville

I use:

"" Buffer Navigation                                                                                                                                                                                        
" Toggle left sidebar: NERDTree and BufferGator                                                                                                                                                             
fu! UiToggle()                                                                                                                                                                                              
  let b = bufnr("%")                                                                                                                                                                                        
  execute "NERDTreeToggle | BuffergatorToggle"                                                                                                                                                              
  execute ( bufwinnr(b) . "wincmd w" )                                                                                                                                                                      
  execute ":set number!"                                                                                                                                                                                    
endf                                                                                                                                                                                                        
map  <silent> <Leader>w  <esc>:call UiToggle()<cr>   

Where "NERDTreeToggle" in that list is the same as typing :NERDTreeToggle. You can modify this function to integrate with your own configuration.

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

First letter capitalization for EditText

Just use android:inputType="textCapWords" in your EditText element.

For example:

<EditText
    android:id="@+id/txtName"
    android:layout_width="0dp"
    android:layout_height="40dp"
    android:layout_weight="0.7"
    android:inputType="textCapWords"
    android:textColorHint="#aaa"
    android:hint="Name Surname"
    android:textSize="12sp" />

Refer to the following link for reference: http://developer.android.com/reference/android/widget/TextView.html#attr_android%3ainputType

How can I change the text inside my <span> with jQuery?

Try this

$("#abc").html('<span class = "xyz"> SAMPLE TEXT</span>');

Handle all the css relevant to that span within xyz

Compile/run assembler in Linux?

The assembler(GNU) is as(1)

Asynchronous Requests with Python requests

I know this has been closed for a while, but I thought it might be useful to promote another async solution built on the requests library.

list_of_requests = ['http://moop.com', 'http://doop.com', ...]

from simple_requests import Requests
for response in Requests().swarm(list_of_requests):
    print response.content

The docs are here: http://pythonhosted.org/simple-requests/

jQuery "blinking highlight" effect on div?

<script>
$(document).ready(function(){
    var count = 0;
    do {
        $('#toFlash').fadeOut(500).fadeIn(500);
        count++;
    } while(count < 10);/*set how many time you want it to flash*/
});
</script

Caesar Cipher Function in Python

I have a hard time remember the char to int conversions so this could be optimized

def decryptCaesar(encrypted, shift):
    minRange = ord('a')
    decrypted = ""
    for char in encrypted:
        decrypted += chr(((ord(char) - minRange + shift) % 26) + minRange)

    return decrypted

Setting up enviromental variables in Windows 10 to use java and javac

Just set the path variable to JDK bin in environment variables.

Variable Name : PATH 
Variable Value : C:\Program Files\Java\jdk1.8.0_31\bin

But the best practice is to set JAVA_HOME and PATH as follow.

Variable Name : JAVA_HOME
Variable Value : C:\Program Files\Java\jdk1.8.0_31

Variable Name : PATH 
Variable Value : %JAVA_HOME%\bin

There is no tracking information for the current branch

This happens due to current branch has no tracking on the branch on the remote. so you can do it with 2 ways.

  1. Pull with specific branch name

git pull origin master

  1. Or you can specific branch to track to the local branch.

git branch --set-upstream-to=origin/

Programmatically Hide/Show Android Soft Keyboard

Did you try InputMethodManager.SHOW_IMPLICIT in first window.

and for hiding in second window use InputMethodManager.HIDE_IMPLICIT_ONLY

EDIT :

If its still not working then probably you are putting it at the wrong place. Override onFinishInflate() and show/hide there.

@override
public void onFinishInflate() {
     /* code to show keyboard on startup */
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
}

How to detect the OS from a Bash script?

I wrote these sugars in my .bashrc:

if_os () { [[ $OSTYPE == *$1* ]]; }
if_nix () { 
    case "$OSTYPE" in
        *linux*|*hurd*|*msys*|*cygwin*|*sua*|*interix*) sys="gnu";;
        *bsd*|*darwin*) sys="bsd";;
        *sunos*|*solaris*|*indiana*|*illumos*|*smartos*) sys="sun";;
    esac
    [[ "${sys}" == "$1" ]];
}

So I can do stuff like:

if_nix gnu && alias ls='ls --color=auto' && export LS_COLORS="..."
if_nix bsd && export CLICOLORS=on && export LSCOLORS="..."
if_os linux && alias psg="ps -FA | grep" #alternative to pgrep
if_nix bsd && alias psg="ps -alwx | grep -i" #alternative to pgrep
if_os darwin && alias finder="open -R"

Print all but the first three columns

awk '{for(i=1;i<4;i++) $i="";print}' file

Return index of highest value in an array

Something like this should do the trick

function array_max_key($array) {
  $max_key = -1;
  $max_val = -1;

  foreach ($array as $key => $value) {
    if ($value > $max_val) {
      $max_key = $key;
      $max_val = $value;
    }
  }

  return $max_key;
}

Regex how to match an optional character

You can make the single letter optional by adding a ? after it as:

([A-Z]{1}?)

The quantifier {1} is redundant so you can drop it.

Why can't I call a public method in another class?

You have to create a variable of the type of the class, and set it equal to a new instance of the object first.

GradeBook myGradeBook = new GradeBook();

Then call the method on the obect you just created.

myGradeBook.[method you want called]

Entity Framework is Too Slow. What are my options?

We have an similar application (Wcf -> EF -> database) that does 120 Requests per second easily, so I am more than sure that EF is not your problem here, that being said, I have seen major performance improvements with compiled queries.

How to Generate Unique Public and Private Key via RSA

When you use a code like this:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   // Do something with the key...
   // Encrypt, export, etc.
}

.NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET

This means:

  1. Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.

  2. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).

To resolve these issues:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   try
   {
      // Do something with the key...
      // Encrypt, export, etc.
   }
   finally
   {
      rsa.PersistKeyInCsp = false;
   }
}

ALWAYS

How to select the first row of each group?

A nice way of doing this with the dataframe api is using the argmax logic like so

  val df = Seq(
    (0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
    (1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
    (2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
    (3,"cat8",35.6)).toDF("Hour", "Category", "TotalValue")

  df.groupBy($"Hour")
    .agg(max(struct($"TotalValue", $"Category")).as("argmax"))
    .select($"Hour", $"argmax.*").show

 +----+----------+--------+
 |Hour|TotalValue|Category|
 +----+----------+--------+
 |   1|      28.5|   cat67|
 |   3|      35.6|    cat8|
 |   2|      39.6|   cat56|
 |   0|      30.9|   cat26|
 +----+----------+--------+

Where are static methods and static variables stored in Java?

In addition to the Thomas's answer , static variable are stored in non heap area which is called Method Area.

Adding an .env file to React Project

  1. Install dotenv as devDependencies:
npm i --save-dev dotenv
  1. Create a .env file in the root directory:
my-react-app/
|- node-modules/
|- public/
|- src/
|- .env
|- .gitignore
|- package.json
|- package.lock.json.
|- README.md
  1. Update the .env file like below & REACT_APP_ is the compulsory prefix for the variable name.
REACT_APP_BASE_URL=http://localhost:8000
REACT_APP_API_KEY=YOUR-API-KEY
  1. [ Optional but Good Practice ] Now you can create a configuration file to store the variables and export the variable so can use it from others file.

For example, I've create a file named base.js and update it like below:

export const BASE_URL = process.env.REACT_APP_BASE_URL;
export const API_KEY = process.env.REACT_APP_API_KEY;
  1. Or you can simply just call the environment variable in your JS file in the following way:
process.env.REACT_APP_BASE_URL

How can I loop through all rows of a table? (MySQL)

Mr Purple's example I used in mysql trigger like that,

begin
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
Select COUNT(*) from user where deleted_at is null INTO n;
SET i=0;
WHILE i<n DO 
  INSERT INTO user_notification(notification_id,status,userId)values(new.notification_id,1,(Select userId FROM user LIMIT i,1)) ;
  SET i = i + 1;
END WHILE;
end

Updating GUI (WPF) using a different thread

You have a couple of options here, I think.

One would be to use a BackgroundWorker. This is a common helper for multithreading in applications. It exposes a DoWork event which is handled on a background thread from the Thread Pool and a RunWorkerCompleted event which is invoked back on the main thread when the background thread completes. It also has the benefit of try/catching the code running on the background thread so that an unhandled exception doesn't kill the application.

If you don't want to go that route, you can use the WPF dispatcher object to invoke an action to update the GUI back onto the main thread. Random reference:

http://www.switchonthecode.com/tutorials/working-with-the-wpf-dispatcher

There are many other options around too, but these are the two most common that come to mind.

Adding ID's to google map markers

Why not use an cache that stores each marker object and references an ID?

var markerCache= {};
var idGen= 0;

function codeAddress(addr, contentStr){
    // create marker
    // store
    markerCache[idGen++]= marker;
}

Edit: of course this relies on a numeric index system that doesn't offer a length property like an array. You could of course prototype the Object object and create a length, etc for just such a thing. OTOH, generating a unique ID value (MD5, etc) of each address might be the way to go.

How to check db2 version

I used

SELECT * FROM TABLE(SYSPROC.ENV_GET_INST_INFO()); 

from tyranitar and that worked on Z/OS. Here's what I got:

SERVICE_LEVEL
DB2 v9.7.0.6

I'd vote up if I could! Thanks!!

Declare an array in TypeScript

Here are the different ways in which you can create an array of booleans in typescript:

let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();

let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();

let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];

let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();

let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();

You can access them using the index:

console.log(arr[5]);

and you add elements using push:

arr.push(true);

When creating the array you can supply the initial values:

let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);

Update TensorFlow

for a specific version

pip install --upgrade tensorflow==2.2

Count with IF condition in MySQL query

Use sum() in place of count()

Try below:

SELECT
    ccc_news . * , 
    SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
    ccc_news
    LEFT JOIN
        ccc_news_comments
    ON
        ccc_news_comments.news_id = ccc_news.news_id
WHERE
    `ccc_news`.`category` = 'news_layer2'
    AND `ccc_news`.`status` = 'Active'
GROUP BY
    ccc_news.news_id
ORDER BY
    ccc_news.set_order ASC
LIMIT 20 

Correct way to import lodash

I just put them in their own file and export it for node and webpack:

// lodash-cherries.js
module.exports = {
  defaults: require('lodash/defaults'),
  isNil: require('lodash/isNil'),
  isObject: require('lodash/isObject'),
  isArray: require('lodash/isArray'),
  isFunction: require('lodash/isFunction'),
  isInteger: require('lodash/isInteger'),
  isBoolean: require('lodash/isBoolean'),
  keys: require('lodash/keys'),
  set: require('lodash/set'),
  get: require('lodash/get'),
}

How to empty the content of a div

An alternative way to do it is:

var div = document.getElementById('myDiv');
while(div.firstChild)
    div.removeChild(div.firstChild);

However, using document.getElementById('myDiv').innerHTML = ""; is faster.

See: Benchmark test

N.B.

Both methods preserve the div.

Comparing date part only without comparing time in JavaScript

The date.js library is handy for these things. It makes all JS date-related scriping a lot easier.

How can I catch an error caused by mail()?

According to http://php.net/manual/en/function.error-get-last.php, use:

print_r(error_get_last());

Which will return an array of the last error generated. You can access the [message] element to display the error.

Swift's guard keyword

There are really two big benefits to guard. One is avoiding the pyramid of doom, as others have mentioned – lots of annoying if let statements nested inside each other moving further and further to the right.

The other benefit is often the logic you want to implement is more "if not let” than "if let { } else".

Here’s an example: suppose you want to implement accumulate – a cross between map and reduce where it gives you back an array of running reduces. Here it is with guard:

extension Sliceable where SubSlice.Generator.Element == Generator.Element {

    func accumulate(combine: (Generator.Element,Generator.Element)->Generator.Element) -> [Generator.Element] {
        // if there are no elements, I just want to bail out and
        // return an empty array
        guard var running = self.first else { return [] }

        // running will now be an unwrapped non-optional
        var result = [running]

        // dropFirst is safe because the collection
        // must have at least one element at this point
        for x in dropFirst(self) {
            running = combine(running, x)
            result.append(running)
        }
        return result
    }

}


let a = [1,2,3].accumulate(+)  // [1,3,6]
let b = [Int]().accumulate(+)  // []

How would you write it without guard, but still using first that returns an optional? Something like this:

extension Sliceable where SubSlice.Generator.Element == Generator.Element {

    func accumulate(combine: (Generator.Element,Generator.Element)->Generator.Element) -> [Generator.Element] {

        if var running = self.first  {
            var result = [running]

            for x in dropFirst(self) {
                running = combine(running, x)
                result.append(running)
            }
            return result
        }
        else {
            return []
        }
    }

}

The extra nesting is annoying, but also, it’s not as logical to have the if and the else so far apart. It’s much more readable to have the early exit for the empty case, and then continue with the rest of the function as if that wasn’t a possibility.

How to delete a specific file from folder using asp.net

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files. 
    foreach (string f in picList)
    {
        // Remove path from the file name. 
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path. 
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files. 
    foreach (string f in txtList)
    {

        // Remove path from the file name. 
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied. 
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied. 
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}

Python xml ElementTree from a string source?

You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse() and fromstring() methods.

How do I remove blue "selected" outline on buttons?

You can remove this by adding !important to your outline.

button{
 outline: none !important;
}

Passing an Object from an Activity to a Fragment

Passing arguments by bundle is restricted to some data types. But you can transfer any data to your fragment this way:

In your fragment create a public method like this

public void passData(Context context, List<LexItem> list, int pos) {
    mContext = context;
    mLexItemList = list;
    mIndex = pos;
}

and in your activity call passData() with all your needed data types after instantiating the fragment

        WebViewFragment myFragment = new WebViewFragment();
        myFragment.passData(getApplicationContext(), mLexItemList, index);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.my_fragment_container, myFragment);
        ft.addToBackStack(null);
        ft.commit();

Remark: My fragment extends "android.support.v4.app.Fragment", therefore I have to use "getSupportFragmentManager()". Of course, this principle will work also with a fragment class extending "Fragment", but then you have to use "getFragmentManager()".

Excel column number from column name

Based on Anastasiya's answer. I think this is the shortest vba command:

Option Explicit

Sub Sample()
    Dim sColumnLetter as String
    Dim iColumnNumber as Integer

    sColumnLetter = "C"
    iColumnNumber = Columns(sColumnLetter).Column

    MsgBox "The column number is " & iColumnNumber
End Sub

Caveat: The only condition for this code to work is that a worksheet is active, because Columns is equivalent to ActiveSheet.Columns. ;)

Unit testing void methods?

Use Rhino Mocks to set what calls, actions and exceptions might be expected. Assuming you can mock or stub out parts of your method. Hard to know without knowing some specifics here about the method, or even context.

Checking for a null object in C++

You can use a special designated object as the null object in case of references as follows:

class SomeClass
{
    public:

        int operator==(SomeClass &object)
        {
            if(this == &object) 
            {
                    return true;
            }

            return false;
        }


    static SomeClass NullObject;
};

SomeClass SomeClass::NullObject;

void print(SomeClass &val)
{
    if(val == SomeClass::NullObject)
    {
        printf("\nNULL");
    }
    else
    {
        printf("\nNOT NULL");
    }
}

wget can't download - 404 error

I had the same problem. Solved using single quotes like this:

$ wget 'http://www.icerts.com/images/logo.jpg'

wget version in use:

$ wget --version
GNU Wget 1.11.4 Red Hat modified

Reading data from DataGridView in C#

If you wish, you can also use the column names instead of column numbers.

For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.

dataGridView.Rows[4].Cells["Name"].Value.ToString();

Hope it helps.

Days between two dates?

Assuming you’ve literally got two date objects, you can subtract one from the other and query the resulting timedelta object for the number of days:

>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7

And it works with datetimes too — I think it rounds down to the nearest day:

>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6

JPA or JDBC, how are they different?

In layman's terms:

  • JDBC is a standard for Database Access
  • JPA is a standard for ORM

JDBC is a standard for connecting to a DB directly and running SQL against it - e.g SELECT * FROM USERS, etc. Data sets can be returned which you can handle in your app, and you can do all the usual things like INSERT, DELETE, run stored procedures, etc. It is one of the underlying technologies behind most Java database access (including JPA providers).

One of the issues with traditional JDBC apps is that you can often have some crappy code where lots of mapping between data sets and objects occur, logic is mixed in with SQL, etc.

JPA is a standard for Object Relational Mapping. This is a technology which allows you to map between objects in code and database tables. This can "hide" the SQL from the developer so that all they deal with are Java classes, and the provider allows you to save them and load them magically. Mostly, XML mapping files or annotations on getters and setters can be used to tell the JPA provider which fields on your object map to which fields in the DB. The most famous JPA provider is Hibernate, so it's a good place to start for concrete examples.

Other examples include OpenJPA, toplink, etc.

Under the hood, Hibernate and most other providers for JPA write SQL and use JDBC to read and write from and to the DB.