Programs & Examples On #Anonymize

Loading and parsing a JSON file with multiple JSON objects

for those stumbling upon this question: the python jsonlines library (much younger than this question) elegantly handles files with one json document per line. see https://jsonlines.readthedocs.io/

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

How to render html with AngularJS templates

Use-

<span ng-bind-html="myContent"></span>

You need to tell angular to not escape it.

Difference between "while" loop and "do while" loop

The do while loop executes the content of the loop once before checking the condition of the while.

Whereas a while loop will check the condition first before executing the content.

In this case you are waiting for user input with scanf(), which will never execute in the while loop as wdlen is not initialized and may just contain a garbage value which may be greater than 2.

Converting file size in bytes to human-readable string

Here is a prototype to convert a number to a readable string respecting the new international standards.

There are two ways to represent big numbers: You could either display them in multiples of 1000 = 10 3 (base 10) or 1024 = 2 10 (base 2). If you divide by 1000, you probably use the SI prefix names, if you divide by 1024, you probably use the IEC prefix names. The problem starts with dividing by 1024. Many applications use the SI prefix names for it and some use the IEC prefix names. The current situation is a mess. If you see SI prefix names you do not know whether the number is divided by 1000 or 1024

https://wiki.ubuntu.com/UnitsPolicy

http://en.wikipedia.org/wiki/Template:Quantities_of_bytes

Object.defineProperty(Number.prototype,'fileSize',{value:function(a,b,c,d){
 return (a=a?[1e3,'k','B']:[1024,'K','iB'],b=Math,c=b.log,
 d=c(this)/c(a[0])|0,this/b.pow(a[0],d)).toFixed(2)
 +' '+(d?(a[1]+'MGTPEZY')[--d]+a[2]:'Bytes');
},writable:false,enumerable:false});

This function contains no loop, and so it's probably faster than some other functions.

Usage:

IEC prefix

console.log((186457865).fileSize()); // default IEC (power 1024)
//177.82 MiB
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB

SI prefix

console.log((186457865).fileSize(1)); //1,true for SI (power 1000)
//186.46 MB 
//kB,MB,GB,TB,PB,EB,ZB,YB

i set the IEC as default because i always used binary mode to calculate the size of a file... using the power of 1024


If you just want one of them in a short oneliner function:

SI

function fileSizeSI(a,b,c,d,e){
 return (b=Math,c=b.log,d=1e3,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
 +' '+(e?'kMGTPEZY'[--e]+'B':'Bytes')
}
//kB,MB,GB,TB,PB,EB,ZB,YB

IEC

function fileSizeIEC(a,b,c,d,e){
 return (b=Math,c=b.log,d=1024,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
 +' '+(e?'KMGTPEZY'[--e]+'iB':'Bytes')
}
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB

Usage:

console.log(fileSizeIEC(7412834521));

if you have some questions about the functions just ask

How can I check if a view is visible or not in Android?

Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.

View.VISIBLE The view is visible.

View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"

View.GONE The view is gone, you can't see it and it doesn't take up the "spot".

So to answer your question, you're looking for:

if (myImageView.getVisibility() == View.VISIBLE) {
    // Its visible
} else {
    // Either gone or invisible
}

Setting the number of map tasks and reduce tasks

One way you can increase the number of mappers is to give your input in the form of split files [you can use linux split command]. Hadoop streaming usually assigns that many mappers as there are input files[if there are a large number of files] if not it will try to split the input into equal sized parts.

Draw path between two points using Google Maps Android API v2

First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.

 public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.googleapis.com/maps/api/directions/json");
        urlString.append("?origin=");// from
        urlString.append(Double.toString(sourcelat));
        urlString.append(",");
        urlString.append(Double.toString( sourcelog));
        urlString.append("&destination=");// to
        urlString.append(Double.toString( destlat));
        urlString.append(",");
        urlString.append(Double.toString( destlog));
        urlString.append("&sensor=false&mode=driving&alternatives=true");
        urlString.append("&key=YOUR_API_KEY");
        return urlString.toString();
 }

This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public String getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return json;

    }
}

This parser will return us string. We will call it like that.

JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);

Now we will send this string to our drawpath function. The drawpath function is

public void drawPath(String  result) {

    try {
            //Tranform the string into a json object
           final JSONObject json = new JSONObject(result);
           JSONArray routeArray = json.getJSONArray("routes");
           JSONObject routes = routeArray.getJSONObject(0);
           JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
           String encodedString = overviewPolylines.getString("points");
           List<LatLng> list = decodePoly(encodedString);
           Polyline line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(12)
                                    .color(Color.parseColor("#05b1fb"))//Google maps blue color
                                    .geodesic(true)
                    );
           /*
           for(int z = 0; z<list.size()-1;z++){
                LatLng src= list.get(z);
                LatLng dest= list.get(z+1);
                Polyline line = mMap.addPolyline(new PolylineOptions()
                .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,   dest.longitude))
                .width(2)
                .color(Color.BLUE).geodesic(true));
            }
           */
    } 
    catch (JSONException e) {

    }
} 

Above code will draw the path on mMap. The code of decodePoly is

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng( (((double) lat / 1E5)),
                 (((double) lng / 1E5) ));
        poly.add(p);
    }

    return poly;
}

As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was

private class connectAsyncTask extends AsyncTask<Void, Void, String>{
    private ProgressDialog progressDialog;
    String url;
    connectAsyncTask(String urlPass){
        url = urlPass;
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Fetching route, Please wait...");
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }
    @Override
    protected String doInBackground(Void... params) {
        JSONParser jParser = new JSONParser();
        String json = jParser.getJSONFromUrl(url);
        return json;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);   
        progressDialog.hide();        
        if(result!=null){
            drawPath(result);
        }
    }
}

I hope it will help.

How to position a Bootstrap popover?

Sure you can. Fortunately there is a clean way to do that and it is in the Bootstrap popover / tooltip documentation as well.

let mySpecialTooltip = $('#mySpecialTooltip); 
mySpecialTooltip.tooltip({
 container: 'body',
 placement: 'bottom',
 html: true,
 template: '<div class="tooltip your-custom-class" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
}); 

in your css file:-

.your-custom-class {
 bottom: your value;
}

Make sure to add the template in bootstrap's tooltip documentation and add your custom class name and style it using css

And, that's it. You can find more about this on https://getbootstrap.com/docs/4.0/components/tooltips/

What size should TabBar images be?

30x30 is points, which means 30px @1x, 60px @2x, not somewhere in-between. Also, it's not a great idea to embed the title of the tab into the image—you're going to have pretty poor accessibility and localization results like that.

How do I capture the output of a script if it is being ran by the task scheduler?

You can write to a log file on the lines that you want to output like this:

@echo off
echo Debugging started >C:\logfile.txt
echo More stuff
echo Debugging stuff >>C:\logfile.txt
echo Hope this helps! >>C:\logfile.txt

This way you can choose which commands to output if you don't want to trawl through everything, just get what you need to see. The > will output it to the file specified (creating the file if it doesn't exist and overwriting it if it does). The >> will append to the file specified (creating the file if it doesn't exist but appending to the contents if it does).

Specify sudo password for Ansible

I don't think ansible will let you specify a password in the flags as you wish to do. There may be somewhere in the configs this can be set but this would make using ansible less secure overall and would not be recommended.

One thing you can do is to create a user on the target machine and grant them passwordless sudo privileges to either all commands or a restricted list of commands.

If you run sudo visudo and enter a line like the below, then the user 'privilegedUser' should not have to enter a password when they run something like sudo service xxxx start:

%privilegedUser ALL= NOPASSWD: /usr/bin/service

Test if registry value exists

My version, matching the exact text from the caught exception. It will return true if it's a different exception but works for this simple case. Also Get-ItemPropertyValue is new in PS 5.0

Function Test-RegValExists($Path, $Value){
$ee = @() # Exception catcher
try{
    Get-ItemPropertyValue -Path $Path -Name $Value | Out-Null
   }
catch{$ee += $_}

    if ($ee.Exception.Message -match "Property $Value does not exist"){return $false}
else {return $true}
}

Cannot get a text value from a numeric cell “Poi”

Using the DataFormatter this issue is resolved. Thanks to "Gagravarr" for the initial post.

DataFormatter formatter = new DataFormatter();

String empno = formatter.formatCellValue(cell0);

How can I get color-int from color resource?

For more information on another use-case that may help surface this question in search results, I wanted to apply alpha to a color defined in my resources.

Using @sat's correct answer:

int alpha = ... // 0-255, calculated based on some business logic
int actionBarBackground = getResources().getColor(R.color.actionBarBackground);
int actionBarBackgroundWithAlpha = Color.argb(
        alpha,
        Color.red(actionbarBackground),
        Color.green(actionbarBackground),
        Color.blue(actionbarBackground)
);

Initialising an array of fixed size in python

An easy solution is x = [None]*length, but note that it initializes all list elements to None. If the size is really fixed, you can do x=[None,None,None,None,None] as well. But strictly speaking, you won't get undefined elements either way because this plague doesn't exist in Python.

accepting HTTPS connections with self-signed certificates

Maybe this will helpful... it works on java clients using self-signed certificates (there is no check of the certificate). Be careful and use it only for development cases because that is no secure at all!!

How to ignore SSL certificate errors in Apache HttpClient 4.0

Hope it will works on Android just adding HttpClient library... good luck!!

How to get the data-id attribute?

To get the contents of the attribute data-id (like in <a data-id="123">link</a>) you have to use

$(this).attr("data-id") // will return the string "123"

or .data() (if you use newer jQuery >= 1.4.3)

$(this).data("id") // will return the number 123

and the part after data- must be lowercase, e.g. data-idNum will not work, but data-idnum will.

Is it possible to get multiple values from a subquery?

you can use cross apply:

select
    a.x,
    bb.y,
    bb.z
from
    a
    cross apply
    (   select b.y, b.z
        from b
        where b.v = a.v
    ) bb

If there will be no row from b to mach row from a then cross apply wont return row. If you need such a rows then use outer apply

If you need to find only one specific row for each of row from a, try:

    cross apply
    (   select top 1 b.y, b.z
        from b
        where b.v = a.v
        order by b.order
    ) bb

Store output of sed into a variable

line=`sed -n 2p myfile`
echo $line

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

Try doing this, using firefox as fake user agent (moreover, it's a good startup script for web scraping with the use of cookies):

#!/usr/bin/env python2
# -*- coding: utf8 -*-
# vim:ts=4:sw=4


import cookielib, urllib2, sys

def doIt(uri):
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    page = opener.open(uri)
    page.addheaders = [('User-agent', 'Mozilla/5.0')]
    print page.read()

for i in sys.argv[1:]:
    doIt(i)

USAGE:

python script.py "http://www.ichangtou.com/#company:data_000008.html"

Debug JavaScript in Eclipse

For Node.js there is Nodeclipse 0.2 with some bug fixes for chromedevtools

How to get next/previous record in MySQL?

next:

select * from foo where id = (select min(id) from foo where id > 4)

previous:

select * from foo where id = (select max(id) from foo where id < 4)

Is it possible to break a long line to multiple lines in Python?

As far as I know, it can be done. Python has implicit line continuation (inside parentheses, brackets, and strings) for triple-quoted strings ("""like this""")and the indentation of continuation lines is not important. For more info, you may want to read this article on lexical analysis, from python.org.

How to connect to remote Oracle DB with PL/SQL Developer?

The problem is not the TNS file, in PLSQL Developer, if you don't have the oracle installation, you need to provide the location of the OCI.DLL file.

In PLSQL DEV app go to Tools-Preferences-Oracle/connections-OCI Library.

In my case I put the next address C:\Oracle\InstantClient-win32-11.2.0.1.0\oci.dll.

If have Weblogic app installed, I didnt tried but if you want try to put the next location

C:\Oracle\Middleware\wlserver_10.3\server\adr.

Creating an iframe with given HTML dynamically

There is an alternative for creating an iframe whose contents are a string of HTML: the srcdoc attribute. This is not supported in older browsers (chief among them: Internet Explorer, and possibly Safari?), but there is a polyfill for this behavior, which you could put in conditional comments for IE, or use something like has.js to conditionally lazy load it.

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

The other answers are great but I thought I'd take a different tact.

If all you are really looking for is to slow down a specific file in linux:

 rm slowfile; mkfifo slowfile; perl -e 'select STDOUT; $| = 1; while(<>) {print $_; sleep(1) if (($ii++ % 5) == 0); }' myfile > slowfile  &

node myprog slowfile

This will sleep 1 sec every five lines. The node program will go as slow as the writer. If it is doing other things they will continue at normal speed.

The mkfifo creates a first-in-first-out pipe. It's what makes this work. The perl line will write as fast as you want. The $|=1 says don't buffer the output.

How to download Google Play Services in an Android emulator?

I got it working by

  • Installing the Google Play Services through the Android SDK Manager
  • Using a Galaxy Nexus Device (4.65", 720 x 1280: xhdpi)
  • Targeting the Android 4.2.2 Google API Level 17

How to read string from keyboard using C?

#include<stdio.h>

int main()
{
    char str[100];
    scanf("%[^\n]s",str);
    printf("%s",str);
    return 0;
}

input: read the string
ouput: print the string

This code prints the string with gaps as shown above.

How can I insert a line break into a <Text> component in React Native?

You can also do:

<Text>{`
Hi~
this is a test message.
`}</Text>

Easier in my opinion, because you don't have to insert stuff within the string; just wrap it once and it keeps all your line-breaks.

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

TL;DR: To access newer versions of mysql/mariadb after as the root user, after a new install, you need to be in a root shell (ie sudo mysql -u root, or mysql -u root inside a shell started by su - or sudo -i first)


Having just done the same upgrade, on Ubuntu, I had the same issue.

What was odd was that

sudo /usr/bin/mysql_secure_installation

Would accept my password, and allow me to set it, but I couldn't log in as root via the mysql client

I had to start mariadb with

sudo mysqld_safe --skip-grant-tables

to get access as root, whilst all the other users could still access fine.

Looking at the mysql.user table I noticed for root the plugin column is set to unix_socket whereas all other users it is set to 'mysql_native_password'. A quick look at this page: https://mariadb.com/kb/en/mariadb/unix_socket-authentication-plugin/ explains that the Unix Socket enables logging in by matching uid of the process running the client with that of the user in the mysql.user table. In other words to access mariadb as root you have to be logged in as root.

Sure enough restarting my mariadb daemon with authentication required I can login as root with

sudo mysql -u root -p

or

sudo su -
mysql -u root -p

Having done this I thought about how to access without having to do the sudo, which is just a matter of running these mysql queries

GRANT ALL PRIVILEGES on *.* to 'root'@'localhost' IDENTIFIED BY '<password>';
FLUSH PRIVILEGES;

(replacing <password> with your desired mysql root password). This enabled password logins for the root user.

Alternatively running the mysql query:

UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';
FLUSH PRIVILEGES;

Will change the root account to use password login without changing the password, but this may leave you with a mysql/mariadb install with no root password on it.

After either of these you need to restarting mysql/mariadb:

sudo service mysql restart

And voila I had access from my personal account via mysql -u root -p

PLEASE NOTE THAT DOING THIS IS REDUCING SECURITY Presumably the MariaDB developers have opted to have root access work like this for a good reason.

Thinking about it I'm quite happy to have to sudo mysql -u root -p so I'm switching back to that, but I thought I'd post my solution as I couldn't find one elsewhere.

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

Most efficient way to convert an HTMLCollection to an Array

I suppose that calling Array.prototype functions on instances of HTMLCollection is a much better option than converting collections to arrays (e.g.,[...collection] or Array.from(collection)), because in the latter case a collection is unnecessarily implicitly iterated and a new array object is created, and this eats up additional resources. Array.prototype iterating functions can be safely called upon objects with consecutive numeric keys starting from [0] and a length property with a valid number value of such keys' quantity (including, e.g., instances of HTMLCollection and FileList), so it's a reliable way. Also, if there is a frequent need in such operations, an empty array [] can be used for quick access to Array.prototype functions; or a shortcut for Array.prototype can be created instead. A runnable example:

_x000D_
_x000D_
const _ = Array.prototype;
const collection = document.getElementById('ol').children;
alert(_.reduce.call(collection, (acc, { textContent }, i) => {
  return acc += `${i+1}) ${textContent}` + '\n';
}, ''));
_x000D_
<ol id="ol">
    <li>foo</li>
    <li>bar</li>
    <li>bat</li>
    <li>baz</li>
</ol>
_x000D_
_x000D_
_x000D_

How to connect to SQL Server database from JavaScript in the browser?

Playing with JavaScript in an HTA I had no luck with a driver={SQL Server};... connection string, but a named DSN was OK :
I set up TestDSN and it tested OK, and then var strConn= "DSN=TestDSN"; worked, so I carried on experimenting for my in-house testing and learning purposes.

Our server has several instances running, e.g. server1\dev and server1\Test which made things slightly more tricky as I managed to waste some time forgetting to escape the \ as \\ :)
After some dead-ends with server=server1;instanceName=dev in the connection strings, I eventually got this one to work :
var strConn= "Provider=SQLOLEDB;Data Source=server1\\dev;Trusted_Connection=Yes;Initial Catalog=MyDatabase;"

Using Windows credentials rather than supplying a user/pwd, I found an interesting diversion was discovering the subtleties of Integrated Security = true v Integrated Security = SSPI v Trusted_Connection=Yes - see Difference between Integrated Security = True and Integrated Security = SSPI

Beware that RecordCount will come back as -1 if using the default adOpenForwardOnly type. If you're working with small result sets and/or don't mind the whole lot in memory at once, use rs.Open(strQuery, objConnection, 3); (3=adOpenStatic) and this gives a valid rs.RecordCount

How to import a csv file into MySQL workbench?

I guess you're missing the ENCLOSED BY clause

LOAD DATA LOCAL INFILE '/path/to/your/csv/file/model.csv'
INTO TABLE test.dummy FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n';

And specify the csv file full path

Load Data Infile - MySQL documentation

What is an Android PendingIntent?

A PendingIntent is a token that you give to another application (e.g. Notification Manager, Alarm Manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code. To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().

How does "FOR" work in cmd batch file?

Mark's idea was good, but maybe forgot some path have spaces in them. Replacing ';' with '" "' instead would cut all paths into quoted strings.

set _path="%PATH:;=" "%"
for %%p in (%_path%) do if not "%%~p"=="" echo %%~p

So here, you have your paths displayed.

FOR command in cmd has a tedious learning curve, notably because how variables react within ()'s statements... you can assign any variables, but you can't read then back within the ()'s, unless you use the "setlocal ENABLEDELAYEDEXPANSION" statement, and therefore also use the variables with !!'s instead of %%'s (!_var!)

I currently exclusively script with cmd, for work, had to learn all this :)

Math operations from string

Regex won't help much. First of all, you will want to take into account the operators precedence, and second, you need to work with parentheses which is impossible with regex.

Depending on what exactly kind of expression you need to parse, you may try either Python AST or (more likely) pyparsing. But, first of all, I'd recommend to read something about syntax analysis in general and the Shunting yard algorithm in particular.

And fight the temptation of using eval, that's not safe.

How to make a phone call using intent in Android?

11-25 14:47:01.681: ERROR/AndroidRuntime(302): blah blah...requires android.permission.CALL_PHONE

^ The answer lies in the exception output "requires android.permission.CALL_PHONE" :)

Allowed characters in filename

For "English locale" file names, this works nicely. I'm using this for sanitizing uploaded file names. The file name is not meant to be linked to anything on disk, it's for when the file is being downloaded hence there are no path checks.

$file_name = preg_replace('/([^\x20-~]+)|([\\/:?"<>|]+)/g', '_', $client_specified_file_name);

Basically it strips all non-printable and reserved characters for Windows and other OSs. You can easily extend the pattern to support other locales and functionalities.

How to run multiple Python versions on Windows

Running a different copy of Python is as easy as starting the correct executable. You mention that you've started a python instance, from the command line, by simply typing python.

What this does under Windows, is to trawl the %PATH% environment variable, checking for an executable, either batch file (.bat), command file (.cmd) or some other executable to run (this is controlled by the PATHEXT environment variable), that matches the name given. When it finds the correct file to run the file is being run.

Now, if you've installed two python versions 2.5 and 2.6, the path will have both of their directories in it, something like PATH=c:\python\2.5;c:\python\2.6 but Windows will stop examining the path when it finds a match.

What you really need to do is to explicitly call one or both of the applications, such as c:\python\2.5\python.exe or c:\python\2.6\python.exe.

The other alternative is to create a shortcut to the respective python.exe calling one of them python25 and the other python26; you can then simply run python25 on your command line.

Is there a 'box-shadow-color' property?

Yes there is a way

box-shadow 0 0 17px 13px rgba(30,140,255,0.80) inset

C#: what is the easiest way to subtract time?

These can all be done with DateTime.Add(TimeSpan) since it supports positive and negative timespans.

DateTime original = new DateTime(year, month, day, 8, 0, 0);
DateTime updated = original.Add(new TimeSpan(5,0,0));

DateTime original = new DateTime(year, month, day, 17, 0, 0);
DateTime updated = original.Add(new TimeSpan(-2,0,0));

DateTime original = new DateTime(year, month, day, 17, 30, 0);
DateTime updated = original.Add(new TimeSpan(0,45,0));

Or you can also use the DateTime.Subtract(TimeSpan) method analogously.

What is the best way to compare 2 folder trees on windows?

You could also execute tree > tree.txt in both folders and then diff both tree.txt files with any file based diff tool (git diff).

How do I center list items inside a UL element?

I had a problem slimier to yours I this quick and its the best solution I have found so far.

What the output looks like

Shows what the output of the code looks like The borders are just to show the spacing and are not needed.


Html:

    <div class="center">
      <ul class="dots">
        <span>
          <li></li>
          <li></li>
          <li></li>
        </span>
      </ul>
    </div>

CSS:

    ul {list-style-type: none;}
    ul li{
        display: inline-block;
        padding: 2px;
        border: 2px solid black;
        border-radius: 5px;}
    .center{
        width: 100%;
        border: 3px solid black;}
    .dots{
        padding: 0px;
        border: 5px solid red;
        text-align: center;}
    span{
        width: 100%;
        border: 5px solid blue;}

Not everything here is needed to center the list items.

You can cut the css down to this to get the same effect:

    ul {list-style-type: none;}
    ul li{display: inline-block;}
    .center{width: 100%;}
    .dots{
        text-align: center;
        padding: 0px;}
    span{width: 100%;}

Vim: How to insert in visual block mode?

if you want to add new text before or after the selected colum:

  • press ctrl+v
  • select columns
  • press shift+i
  • write your text
  • press esc
  • press "jj"

Python script to do something at the same time every day

I needed something similar for a task. This is the code I wrote: It calculates the next day and changes the time to whatever is required and finds seconds between currentTime and next scheduled time.

import datetime as dt

def my_job():
    print "hello world"
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,my_job,()).start()

Get Locale Short Date Format using javascript

Short date patterns:

const shortDatePatterns = {
'aa-DJ': "dd/MM/yyyy",
'aa-ER': "dd/MM/yyyy",
'aa-ET': "dd/MM/yyyy",
'af': "yyyy-MM-dd",
'af-NA': "yyyy-MM-dd",
'af-ZA': "yyyy-MM-dd",
'agq-CM': "d/M/yyyy",
'ak-GH': "yyyy/MM/dd",
'am': "dd/MM/yyyy",
'am-ET': "dd/MM/yyyy",
'ar': "dd/MM/yy",
'ar-001': "d/M/yyyy",
'ar-AE': "dd/MM/yyyy",
'ar-BH': "dd/MM/yyyy",
'ar-DJ': "d/M/yyyy",
'ar-DZ': "dd-MM-yyyy",
'ar-EG': "dd/MM/yyyy",
'ar-ER': "d/M/yyyy",
'ar-IL': "d/M/yyyy",
'ar-IQ': "dd/MM/yyyy",
'ar-JO': "dd/MM/yyyy",
'ar-KM': "d/M/yyyy",
'ar-KW': "dd/MM/yyyy",
'ar-LB': "dd/MM/yyyy",
'ar-LY': "dd/MM/yyyy",
'ar-MA': "dd-MM-yyyy",
'ar-MR': "d/M/yyyy",
'ar-OM': "dd/MM/yyyy",
'ar-PS': "d/M/yyyy",
'ar-QA': "dd/MM/yyyy",
'ar-SA': "dd/MM/yy",
'ar-SD': "d/M/yyyy",
'ar-SO': "d/M/yyyy",
'ar-SS': "d/M/yyyy",
'ar-SY': "dd/MM/yyyy",
'ar-TD': "d/M/yyyy",
'ar-TN': "dd-MM-yyyy",
'ar-YE': "dd/MM/yyyy",
'arn-CL': "dd-MM-yyyy",
'as': "dd-MM-yyyy",
'as-IN': "dd-MM-yyyy",
'asa-TZ': "dd/MM/yyyy",
'ast-ES': "d/M/yyyy",
'az': "dd.MM.yyyy",
'az-Cyrl-AZ': "dd.MM.yyyy",
'az-Latn-AZ': "dd.MM.yyyy",
'ba': "dd.MM.yy",
'ba-RU': "dd.MM.yy",
'bas-CM': "d/M/yyyy",
'be': "dd.MM.yy",
'be-BY': "dd.MM.yy",
'bem-ZM': "dd/MM/yyyy",
'bez-TZ': "dd/MM/yyyy",
'bg': "d.M.yyyy '?.'",
'bg-BG': "d.M.yyyy '?.'",
'bin-NG': "d/M/yyyy",
'bm': "d/M/yyyy",
'bm-Latn-ML': "d/M/yyyy",
'bn': "d/M/yyyy",
'bn-BD': "d/M/yyyy",
'bn-IN': "dd-MM-yy",
'bo': "yyyy/M/d",
'bo-CN': "yyyy/M/d",
'bo-IN': "yyyy-MM-dd",
'br': "dd/MM/yyyy",
'br-FR': "dd/MM/yyyy",
'brx-IN': "M/d/yyyy",
'bs': "d.M.yyyy.",
'bs-Cyrl-BA': "d.M.yyyy",
'bs-Latn-BA': "d.M.yyyy.",
'byn-ER': "dd/MM/yyyy",
'ca': "d/M/yyyy",
'ca-AD': "d/M/yyyy",
'ca-ES': "d/M/yyyy",
'ca-ES-valencia': "d/M/yyyy",
'ca-FR': "d/M/yyyy",
'ca-IT': "d/M/yyyy",
'ce-RU': "yyyy-MM-dd",
'cgg-UG': "dd/MM/yyyy",
'chr-Cher-US': "M/d/yyyy",
'co': "dd/MM/yyyy",
'co-FR': "dd/MM/yyyy",
'cs-CZ': "dd.MM.yyyy",
'cu': "yyyy.MM.dd",
'cu-RU': "yyyy.MM.dd",
'cy': "dd/MM/yyyy",
'cy-GB': "dd/MM/yyyy",
'da-DK': "dd-MM-yyyy",
'da-GL': "dd/MM/yyyy",
'dav-KE': "dd/MM/yyyy",
'de': "dd.MM.yyyy",
'de-AT': "dd.MM.yyyy",
'de-BE': "dd.MM.yyyy",
'de-CH': "dd.MM.yyyy",
'de-DE': "dd.MM.yyyy",
'de-IT': "dd.MM.yyyy",
'de-LI': "dd.MM.yyyy",
'de-LU': "dd.MM.yyyy",
'dje-NE': "d/M/yyyy",
'dsb-DE': "d. M. yyyy",
'dua-CM': "d/M/yyyy",
'dv-MV': "dd/MM/yy",
'dyo-SN': "d/M/yyyy",
'dz': "yyyy-MM-dd",
'dz-BT': "yyyy-MM-dd",
'ebu-KE': "dd/MM/yyyy",
'ee': "M/d/yyyy",
'ee-GH': "M/d/yyyy",
'ee-TG': "M/d/yyyy",
'el-CY': "d/M/yyyy",
'el-GR': "d/M/yyyy",
'en-001': "dd/MM/yyyy",
'en-029': "dd/MM/yyyy",
'en-150': "dd/MM/yyyy",
'en-AG': "dd/MM/yyyy",
'en-AI': "dd/MM/yyyy",
'en-AS': "M/d/yyyy",
'en-AT': "dd/MM/yyyy",
'en-AU': "d/MM/yyyy",
'en-BB': "dd/MM/yyyy",
'en-BE': "dd/MM/yyyy",
'en-BI': "M/d/yyyy",
'en-BM': "dd/MM/yyyy",
'en-BS': "dd/MM/yyyy",
'en-BW': "dd/MM/yyyy",
'en-BZ': "dd/MM/yyyy",
'en-CA': "yyyy-MM-dd",
'en-CC': "dd/MM/yyyy",
'en-CH': "dd/MM/yyyy",
'en-CK': "dd/MM/yyyy",
'en-CM': "dd/MM/yyyy",
'en-CX': "dd/MM/yyyy",
'en-CY': "dd/MM/yyyy",
'en-DE': "dd/MM/yyyy",
'en-DK': "dd/MM/yyyy",
'en-DM': "dd/MM/yyyy",
'en-ER': "dd/MM/yyyy",
'en-FI': "dd/MM/yyyy",
'en-FJ': "dd/MM/yyyy",
'en-FK': "dd/MM/yyyy",
'en-FM': "dd/MM/yyyy",
'en-GB': "dd/MM/yyyy",
'en-GD': "dd/MM/yyyy",
'en-GG': "dd/MM/yyyy",
'en-GH': "dd/MM/yyyy",
'en-GI': "dd/MM/yyyy",
'en-GM': "dd/MM/yyyy",
'en-GU': "M/d/yyyy",
'en-GY': "dd/MM/yyyy",
'en-HK': "d/M/yyyy",
'en-ID': "dd/MM/yyyy",
'en-IE': "dd/MM/yyyy",
'en-IL': "dd/MM/yyyy",
'en-IM': "dd/MM/yyyy",
'en-IN': "dd-MM-yyyy",
'en-IO': "dd/MM/yyyy",
'en-JE': "dd/MM/yyyy",
'en-JM': "d/M/yyyy",
'en-KE': "dd/MM/yyyy",
'en-KI': "dd/MM/yyyy",
'en-KN': "dd/MM/yyyy",
'en-KY': "dd/MM/yyyy",
'en-LC': "dd/MM/yyyy",
'en-LR': "dd/MM/yyyy",
'en-LS': "dd/MM/yyyy",
'en-MG': "dd/MM/yyyy",
'en-MH': "M/d/yyyy",
'en-MO': "dd/MM/yyyy",
'en-MP': "M/d/yyyy",
'en-MS': "dd/MM/yyyy",
'en-MT': "dd/MM/yyyy",
'en-MU': "dd/MM/yyyy",
'en-MW': "dd/MM/yyyy",
'en-MY': "d/M/yyyy",
'en-NA': "dd/MM/yyyy",
'en-NF': "dd/MM/yyyy",
'en-NG': "dd/MM/yyyy",
'en-NL': "dd/MM/yyyy",
'en-NR': "dd/MM/yyyy",
'en-NU': "dd/MM/yyyy",
'en-NZ': "d/MM/yyyy",
'en-PG': "dd/MM/yyyy",
'en-PH': "dd/MM/yyyy",
'en-PK': "dd/MM/yyyy",
'en-PN': "dd/MM/yyyy",
'en-PR': "M/d/yyyy",
'en-PW': "dd/MM/yyyy",
'en-RW': "dd/MM/yyyy",
'en-SB': "dd/MM/yyyy",
'en-SC': "dd/MM/yyyy",
'en-SD': "dd/MM/yyyy",
'en-SE': "yyyy-MM-dd",
'en-SG': "d/M/yyyy",
'en-SH': "dd/MM/yyyy",
'en-SI': "dd/MM/yyyy",
'en-SL': "dd/MM/yyyy",
'en-SS': "dd/MM/yyyy",
'en-SX': "dd/MM/yyyy",
'en-SZ': "dd/MM/yyyy",
'en-TC': "dd/MM/yyyy",
'en-TK': "dd/MM/yyyy",
'en-TO': "dd/MM/yyyy",
'en-TT': "dd/MM/yyyy",
'en-TV': "dd/MM/yyyy",
'en-TZ': "dd/MM/yyyy",
'en-UG': "dd/MM/yyyy",
'en-UM': "M/d/yyyy",
'en-US': "M/d/yyyy",
'en-VC': "dd/MM/yyyy",
'en-VG': "dd/MM/yyyy",
'en-VI': "M/d/yyyy",
'en-VU': "dd/MM/yyyy",
'en-WS': "dd/MM/yyyy",
'en-ZA': "yyyy/MM/dd",
'en-ZM': "dd/MM/yyyy",
'en-ZW': "d/M/yyyy",
'eo-001': "yyyy-MM-dd",
'es': "dd/MM/yyyy",
'es-419': "d/M/yyyy",
'es-AR': "d/M/yyyy",
'es-BO': "d/M/yyyy",
'es-BR': "d/M/yyyy",
'es-BZ': "d/M/yyyy",
'es-CL': "dd-MM-yyyy",
'es-CO': "d/MM/yyyy",
'es-CR': "d/M/yyyy",
'es-CU': "d/M/yyyy",
'es-DO': "d/M/yyyy",
'es-EC': "d/M/yyyy",
'es-ES': "dd/MM/yyyy",
'es-GQ': "d/M/yyyy",
'es-GT': "d/MM/yyyy",
'es-HN': "d/M/yyyy",
'es-MX': "dd/MM/yyyy",
'es-NI': "d/M/yyyy",
'es-PA': "MM/dd/yyyy",
'es-PE': "d/MM/yyyy",
'es-PH': "d/M/yyyy",
'es-PR': "MM/dd/yyyy",
'es-PY': "d/M/yyyy",
'es-SV': "d/M/yyyy",
'es-US': "M/d/yyyy",
'es-UY': "d/M/yyyy",
'es-VE': "d/M/yyyy",
'et': "dd.MM.yyyy",
'et-EE': "dd.MM.yyyy",
'eu-ES': "yyyy/M/d",
'ewo-CM': "d/M/yyyy",
'fa-IR': "dd/MM/yyyy",
'ff-CM': "d/M/yyyy",
'ff-GN': "d/M/yyyy",
'ff-Latn-SN': "dd/MM/yyyy",
'ff-MR': "d/M/yyyy",
'ff-NG': "d/M/yyyy",
'fi': "d.M.yyyy",
'fi-FI': "d.M.yyyy",
'fil-PH': "M/d/yyyy",
'fo': "dd.MM.yyyy",
'fo-DK': "dd.MM.yyyy",
'fo-FO': "dd.MM.yyyy",
'fr': "dd/MM/yyyy",
'fr-029': "dd/MM/yyyy",
'fr-BE': "dd-MM-yy",
'fr-BF': "dd/MM/yyyy",
'fr-BI': "dd/MM/yyyy",
'fr-BJ': "dd/MM/yyyy",
'fr-BL': "dd/MM/yyyy",
'fr-CA': "yyyy-MM-dd",
'fr-CD': "dd/MM/yyyy",
'fr-CF': "dd/MM/yyyy",
'fr-CG': "dd/MM/yyyy",
'fr-CH': "dd.MM.yyyy",
'fr-CI': "dd/MM/yyyy",
'fr-CM': "dd/MM/yyyy",
'fr-DJ': "dd/MM/yyyy",
'fr-DZ': "dd/MM/yyyy",
'fr-FR': "dd/MM/yyyy",
'fr-GA': "dd/MM/yyyy",
'fr-GF': "dd/MM/yyyy",
'fr-GN': "dd/MM/yyyy",
'fr-GP': "dd/MM/yyyy",
'fr-GQ': "dd/MM/yyyy",
'fr-HT': "dd/MM/yyyy",
'fr-KM': "dd/MM/yyyy",
'fr-LU': "dd/MM/yyyy",
'fr-MA': "dd/MM/yyyy",
'fr-MC': "dd/MM/yyyy",
'fr-MF': "dd/MM/yyyy",
'fr-MG': "dd/MM/yyyy",
'fr-ML': "dd/MM/yyyy",
'fr-MQ': "dd/MM/yyyy",
'fr-MR': "dd/MM/yyyy",
'fr-MU': "dd/MM/yyyy",
'fr-NC': "dd/MM/yyyy",
'fr-NE': "dd/MM/yyyy",
'fr-PF': "dd/MM/yyyy",
'fr-PM': "dd/MM/yyyy",
'fr-RE': "dd/MM/yyyy",
'fr-RW': "dd/MM/yyyy",
'fr-SC': "dd/MM/yyyy",
'fr-SN': "dd/MM/yyyy",
'fr-SY': "dd/MM/yyyy",
'fr-TD': "dd/MM/yyyy",
'fr-TG': "dd/MM/yyyy",
'fr-TN': "dd/MM/yyyy",
'fr-VU': "dd/MM/yyyy",
'fr-WF': "dd/MM/yyyy",
'fr-YT': "dd/MM/yyyy",
'fur-IT': "dd/MM/yyyy",
'fy-NL': "dd-MM-yyyy",
'ga': "dd/MM/yyyy",
'ga-IE': "dd/MM/yyyy",
'gd': "dd/MM/yyyy",
'gd-GB': "dd/MM/yyyy",
'gl': "dd/MM/yyyy",
'gl-ES': "dd/MM/yyyy",
'gn': "dd/MM/yyyy",
'gn-PY': "dd/MM/yyyy",
'gsw-CH': "dd.MM.yyyy",
'gsw-FR': "dd/MM/yyyy",
'gsw-LI': "dd.MM.yyyy",
'gu': "dd-MM-yy",
'gu-IN': "dd-MM-yy",
'guz-KE': "dd/MM/yyyy",
'gv-IM': "dd/MM/yyyy",
'ha-Latn-GH': "d/M/yyyy",
'ha-Latn-NE': "d/M/yyyy",
'ha-Latn-NG': "d/M/yyyy",
'haw-US': "d/M/yyyy",
'he-IL': "dd/MM/yyyy",
'hi-IN': "dd-MM-yyyy",
'hr': "d.M.yyyy.",
'hr-BA': "d. M. yyyy.",
'hr-HR': "d.M.yyyy.",
'hsb-DE': "d.M.yyyy",
'hu': "yyyy. MM. dd.",
'hu-HU': "yyyy. MM. dd.",
'hy-AM': "dd.MM.yyyy",
'ia-001': "yyyy/MM/dd",
'ia-FR': "yyyy/MM/dd",
'ibb-NG': "d/M/yyyy",
'id': "dd/MM/yyyy",
'id-ID': "dd/MM/yyyy",
'ig-NG': "dd/MM/yyyy",
'ii-CN': "yyyy/M/d",
'is': "d.M.yyyy",
'is-IS': "d.M.yyyy",
'it': "dd/MM/yyyy",
'it-CH': "dd.MM.yyyy",
'it-IT': "dd/MM/yyyy",
'it-SM': "dd/MM/yyyy",
'it-VA': "dd/MM/yyyy",
'iu-Cans-CA': "d/M/yyyy",
'iu-Latn-CA': "d/MM/yyyy",
'ja-JP': "yyyy/MM/dd",
'jgo-CM': "yyyy-MM-dd",
'jmc-TZ': "dd/MM/yyyy",
'jv-Java-ID': "dd/MM/yyyy",
'jv-Latn-ID': "dd/MM/yyyy",
'ka-GE': "dd.MM.yyyy",
'kab-DZ': "d/M/yyyy",
'kam-KE': "dd/MM/yyyy",
'kde-TZ': "dd/MM/yyyy",
'kea-CV': "d/M/yyyy",
'khq-ML': "d/M/yyyy",
'ki': "dd/MM/yyyy",
'ki-KE': "dd/MM/yyyy",
'kk-KZ': "dd.MM.yyyy",
'kkj-CM': "dd/MM yyyy",
'kl-GL': "dd-MM-yyyy",
'kln-KE': "dd/MM/yyyy",
'km': "dd/MM/yy",
'km-KH': "dd/MM/yy",
'kn': "dd-MM-yy",
'kn-IN': "dd-MM-yy",
'ko-KP': "yyyy. M. d.",
'ko-KR': "yyyy-MM-dd",
'kok-IN': "dd-MM-yyyy",
'kr': "d/M/yyyy",
'kr-NG': "d/M/yyyy",
'ks-Arab-IN': "M/d/yyyy",
'ks-Deva-IN': "dd-MM-yyyy",
'ksb-TZ': "dd/MM/yyyy",
'ksf-CM': "d/M/yyyy",
'ksh-DE': "d. M. yyyy",
'ku-Arab-IQ': "yyyy/MM/dd",
'ku-Arab-IR': "dd/MM/yyyy",
'kw': "dd/MM/yyyy",
'kw-GB': "dd/MM/yyyy",
'ky': "d-MMM yy",
'ky-KG': "d-MMM yy",
'la': "dd/MM/yyyy",
'la-001': "dd/MM/yyyy",
'lag-TZ': "dd/MM/yyyy",
'lb': "dd.MM.yy",
'lb-LU': "dd.MM.yy",
'lg-UG': "dd/MM/yyyy",
'lkt-US': "M/d/yyyy",
'ln-AO': "d/M/yyyy",
'ln-CD': "d/M/yyyy",
'ln-CF': "d/M/yyyy",
'ln-CG': "d/M/yyyy",
'lo-LA': "d/M/yyyy",
'lrc-IQ': "yyyy-MM-dd",
'lrc-IR': "dd/MM/yyyy",
'lt': "yyyy-MM-dd",
'lt-LT': "yyyy-MM-dd",
'lu': "d/M/yyyy",
'lu-CD': "d/M/yyyy",
'luo-KE': "dd/MM/yyyy",
'luy-KE': "dd/MM/yyyy",
'lv': "dd.MM.yyyy",
'lv-LV': "dd.MM.yyyy",
'mas-KE': "dd/MM/yyyy",
'mas-TZ': "dd/MM/yyyy",
'mer-KE': "dd/MM/yyyy",
'mfe-MU': "d/M/yyyy",
'mg': "yyyy-MM-dd",
'mg-MG': "yyyy-MM-dd",
'mgh-MZ': "dd/MM/yyyy",
'mgo-CM': "yyyy-MM-dd",
'mi-NZ': "dd/MM/yyyy",
'mk': "dd.M.yyyy",
'mk-MK': "dd.M.yyyy",
'ml': "d/M/yyyy",
'ml-IN': "d/M/yyyy",
'mn': "yyyy.MM.dd",
'mn-MN': "yyyy.MM.dd",
'mn-Mong-CN': "yyyy/M/d",
'mn-Mong-MN': "yyyy/M/d",
'mni-IN': "dd/MM/yyyy",
'moh-CA': "M/d/yyyy",
'mr': "dd-MM-yyyy",
'mr-IN': "dd-MM-yyyy",
'ms': "d/MM/yyyy",
'ms-BN': "d/MM/yyyy",
'ms-MY': "d/MM/yyyy",
'ms-SG': "d/MM/yyyy",
'mt': "dd/MM/yyyy",
'mt-MT': "dd/MM/yyyy",
'mua-CM': "d/M/yyyy",
'my': "dd-MM-yyyy",
'my-MM': "dd-MM-yyyy",
'mzn-IR': "dd/MM/yyyy",
'naq-NA': "dd/MM/yyyy",
'nb-NO': "dd.MM.yyyy",
'nb-SJ': "dd.MM.yyyy",
'nd-ZW': "dd/MM/yyyy",
'nds-DE': "d.MM.yyyy",
'nds-NL': "d.MM.yyyy",
'ne': "M/d/yyyy",
'ne-IN': "yyyy/M/d",
'ne-NP': "M/d/yyyy",
'nl': "d-M-yyyy",
'nl-AW': "dd-MM-yyyy",
'nl-BE': "d/MM/yyyy",
'nl-BQ': "dd-MM-yyyy",
'nl-CW': "dd-MM-yyyy",
'nl-NL': "d-M-yyyy",
'nl-SR': "dd-MM-yyyy",
'nl-SX': "dd-MM-yyyy",
'nmg-CM': "d/M/yyyy",
'nn-NO': "dd.MM.yyyy",
'nnh-CM': "dd/MM/yyyy",
'no': "dd.MM.yyyy",
'nqo-GN': "dd/MM/yyyy",
'nr': "yyyy-MM-dd",
'nr-ZA': "yyyy-MM-dd",
'nso-ZA': "yyyy-MM-dd",
'nus-SS': "d/MM/yyyy",
'nyn-UG': "dd/MM/yyyy",
'oc-FR': "dd/MM/yyyy",
'om': "dd/MM/yyyy",
'om-ET': "dd/MM/yyyy",
'om-KE': "dd/MM/yyyy",
'or-IN': "dd-MM-yy",
'os-GE': "dd.MM.yyyy",
'os-RU': "dd.MM.yyyy",
'pa': "dd-MM-yy",
'pa-Arab-PK': "dd-MM-yy",
'pa-IN': "dd-MM-yy",
'pap-029': "d-M-yyyy",
'pl': "dd.MM.yyyy",
'pl-PL': "dd.MM.yyyy",
'prg-001': "dd.MM.yyyy",
'prs-AF': "yyyy/M/d",
'ps': "yyyy/M/d",
'ps-AF': "yyyy/M/d",
'pt': "dd/MM/yyyy",
'pt-AO': "dd/MM/yyyy",
'pt-BR': "dd/MM/yyyy",
'pt-CH': "dd/MM/yyyy",
'pt-CV': "dd/MM/yyyy",
'pt-GQ': "dd/MM/yyyy",
'pt-GW': "dd/MM/yyyy",
'pt-LU': "dd/MM/yyyy",
'pt-MO': "dd/MM/yyyy",
'pt-MZ': "dd/MM/yyyy",
'pt-PT': "dd/MM/yyyy",
'pt-ST': "dd/MM/yyyy",
'pt-TL': "dd/MM/yyyy",
'quc-Latn-GT': "dd/MM/yyyy",
'quz-BO': "dd/MM/yyyy",
'quz-EC': "dd/MM/yyyy",
'quz-PE': "dd/MM/yyyy",
'rm-CH': "dd-MM-yyyy",
'rn-BI': "d/M/yyyy",
'ro': "dd.MM.yyyy",
'ro-MD': "dd.MM.yyyy",
'ro-RO': "dd.MM.yyyy",
'rof-TZ': "dd/MM/yyyy",
'ru': "dd.MM.yyyy",
'ru-BY': "dd.MM.yyyy",
'ru-KG': "dd.MM.yyyy",
'ru-KZ': "dd.MM.yyyy",
'ru-MD': "dd.MM.yyyy",
'ru-RU': "dd.MM.yyyy",
'ru-UA': "dd.MM.yyyy",
'rw': "yyyy-MM-dd",
'rw-RW': "yyyy-MM-dd",
'rwk-TZ': "dd/MM/yyyy",
'sa': "dd-MM-yyyy",
'sa-IN': "dd-MM-yyyy",
'sah-RU': "dd.MM.yyyy",
'saq-KE': "dd/MM/yyyy",
'sbp-TZ': "dd/MM/yyyy",
'sd': "dd/MM/yyyy",
'sd-Arab-PK': "dd/MM/yyyy",
'sd-Deva-IN': "dd/MM/yyyy",
'se': "yyyy-MM-dd",
'se-FI': "d.M.yyyy",
'se-NO': "yyyy-MM-dd",
'se-SE': "yyyy-MM-dd",
'seh-MZ': "d/M/yyyy",
'ses-ML': "d/M/yyyy",
'sg': "d/M/yyyy",
'sg-CF': "d/M/yyyy",
'shi-Latn-MA': "d/M/yyyy",
'shi-Tfng-MA': "d/M/yyyy",
'si': "yyyy-MM-dd",
'si-LK': "yyyy-MM-dd",
'sk': "d. M. yyyy",
'sk-SK': "d. M. yyyy",
'sl': "d. MM. yyyy",
'sl-SI': "d. MM. yyyy",
'sma-NO': "dd.MM.yyyy",
'sma-SE': "yyyy-MM-dd",
'smj-NO': "dd.MM.yyyy",
'smj-SE': "yyyy-MM-dd",
'smn-FI': "d.M.yyyy",
'sms-FI': "d.M.yyyy",
'sn': "yyyy-MM-dd",
'sn-Latn-ZW': "yyyy-MM-dd",
'so': "dd/MM/yyyy",
'so-DJ': "dd/MM/yyyy",
'so-ET': "dd/MM/yyyy",
'so-KE': "dd/MM/yyyy",
'so-SO': "dd/MM/yyyy",
'sq-AL': "d.M.yyyy",
'sq-MK': "d.M.yyyy",
'sq-XK': "d.M.yyyy",
'sr': "d.M.yyyy.",
'sr-Cyrl-BA': "d.M.yyyy.",
'sr-Cyrl-ME': "d.M.yyyy.",
'sr-Cyrl-RS': "dd.MM.yyyy.",
'sr-Cyrl-XK': "d.M.yyyy.",
'sr-Latn-BA': "d.M.yyyy.",
'sr-Latn-ME': "d.M.yyyy.",
'sr-Latn-RS': "d.M.yyyy.",
'sr-Latn-XK': "d.M.yyyy.",
'ss': "yyyy-MM-dd",
'ss-SZ': "yyyy-MM-dd",
'ss-ZA': "yyyy-MM-dd",
'ssy-ER': "dd/MM/yyyy",
'st': "yyyy-MM-dd",
'st-LS': "yyyy-MM-dd",
'st-ZA': "yyyy-MM-dd",
'sv': "yyyy-MM-dd",
'sv-AX': "yyyy-MM-dd",
'sv-FI': "dd-MM-yyyy",
'sv-SE': "yyyy-MM-dd",
'sw-CD': "dd/MM/yyyy",
'sw-KE': "dd/MM/yyyy",
'sw-TZ': "dd/MM/yyyy",
'sw-UG': "dd/MM/yyyy",
'syr-SY': "dd/MM/yyyy",
'ta-IN': "dd-MM-yyyy",
'ta-LK': "d/M/yyyy",
'ta-MY': "d/M/yyyy",
'ta-SG': "d/M/yyyy",
'te-IN': "dd-MM-yy",
'teo-KE': "dd/MM/yyyy",
'teo-UG': "dd/MM/yyyy",
'tg': "dd.MM.yyyy",
'tg-Cyrl-TJ': "dd.MM.yyyy",
'th': "d/M/yyyy",
'th-TH': "d/M/yyyy",
'ti-ER': "dd/MM/yyyy",
'ti-ET': "dd/MM/yyyy",
'tig-ER': "dd/MM/yyyy",
'tk': "dd.MM.yy 'ý.'",
'tk-TM': "dd.MM.yy 'ý.'",
'tn': "yyyy-MM-dd",
'tn-BW': "yyyy-MM-dd",
'tn-ZA': "yyyy-MM-dd",
'to': "d/M/yyyy",
'to-TO': "d/M/yyyy",
'tr': "d.MM.yyyy",
'tr-CY': "d.MM.yyyy",
'tr-TR': "d.MM.yyyy",
'ts-ZA': "yyyy-MM-dd",
'tt': "dd.MM.yyyy",
'tt-RU': "dd.MM.yyyy",
'twq-NE': "d/M/yyyy",
'tzm-Arab-MA': "d/M/yyyy",
'tzm-Latn-DZ': "dd-MM-yyyy",
'tzm-Latn-MA': "dd/MM/yyyy",
'tzm-Tfng-MA': "dd-MM-yyyy",
'ug': "yyyy-M-d",
'ug-CN': "yyyy-M-d",
'uk-UA': "dd.MM.yyyy",
'ur-IN': "d/M/yy",
'ur-PK': "dd/MM/yyyy",
'uz': "dd/MM/yyyy",
'uz-Arab-AF': "dd/MM yyyy",
'uz-Cyrl-UZ': "dd/MM/yyyy",
'uz-Latn-UZ': "dd/MM/yyyy",
'vai-Latn-LR': "dd/MM/yyyy",
'vai-Vaii-LR': "dd/MM/yyyy",
've': "yyyy-MM-dd",
've-ZA': "yyyy-MM-dd",
'vi': "dd/MM/yyyy",
'vi-VN': "dd/MM/yyyy",
'vo-001': "yyyy-MM-dd",
'vun-TZ': "dd/MM/yyyy",
'wae-CH': "yyyy-MM-dd",
'wal-ET': "dd/MM/yyyy",
'wo-SN': "dd/MM/yyyy",
'xh-ZA': "yyyy-MM-dd",
'xog-UG': "dd/MM/yyyy",
'yav-CM': "d/M/yyyy",
'yi-001': "dd/MM/yyyy",
'yo-BJ': "dd/MM/yyyy",
'yo-NG': "dd/MM/yyyy",
'zgh-Tfng-MA': "d/M/yyyy",
'zh-CN': "yyyy/M/d",
'zh-Hans-HK': "d/M/yyyy",
'zh-Hans-MO': "d/M/yyyy",
'zh-HK': "d/M/yyyy",
'zh-MO': "d/M/yyyy",
'zh-SG': "d/M/yyyy",
'zh-TW': "yyyy/M/d",
'zu-ZA': "M/d/yyyy",
};

jquery - fastest way to remove all rows from a very large table

this works for me :

1- add class for each row "removeRow"

2- in the jQuery

$(".removeRow").remove();

How do I return an int from EditText? (Android)

For now, use an EditText. Use android:inputType="number" to force it to be numeric. Convert the resulting string into an integer (e.g., Integer.parseInt(myEditText.getText().toString())).

In the future, you might consider a NumberPicker widget, once that becomes available (slated to be in Honeycomb).

Rounding float in Ruby

You can also provide a negative number as an argument to the round method to round to the nearest multiple of 10, 100 and so on.

# Round to the nearest multiple of 10. 
12.3453.round(-1)       # Output: 10

# Round to the nearest multiple of 100. 
124.3453.round(-2)      # Output: 100

Reload an iframe with jQuery

Below solution will work for sure:

window.parent.location.href = window.parent.location.href;

preg_match(); - Unknown modifier '+'

This happened to me because I put a variable in the regex and sometimes its string value included a slash. Solution: preg_quote.

How to obtain the last path segment of a URI

You can use getPathSegments() function. (Android Documentation)

Consider your example URI:

String uri = "http://base_path/some_segment/id"

You can get the last segment using:

List<String> pathSegments = uri.getPathSegments();
String lastSegment = pathSegments.get(pathSegments.size - 1);

lastSegment will be id.

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

You should probably set all of the cookie properties not just the value of it. setPath(), setDomain() ... etc

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

In the head section of your html document:

<link rel="stylesheet" type="text/css" href="/path/to/ABCD.css">

Your css file should be css only and not contain any markup.

How to configure Eclipse build path to use Maven dependencies?

if you execute

mvn eclipse:clean

followed by

mvn eclipse:eclipse

if will prepare the eclipse .classpath file for you. That is, these commands are run against maven from the command line i.e. outside of eclipse.

SQL to generate a list of numbers from 1 to 100

Using GROUP BY CUBE:

SELECT ROWNUM
FROM (SELECT 1 AS c FROM dual GROUP BY CUBE(1,1,1,1,1,1,1) ) sub
WHERE ROWNUM <=100;

Rextester Demo

Convert all strings in a list to int

Use a list comprehension:

results = [int(i) for i in results]

e.g.

>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]

How do you find out which version of GTK+ is installed on Ubuntu?

You can use this command:

$ dpkg -s libgtk2.0-0|grep '^Version'

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

It could be because of the property pageable -> pageSizes: true.

Remove this and check again.

How to open a web server port on EC2 instance

You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.

Check object empty

If your Object contains Objects then check if they are null, if it have primitives check for their default values.

for Instance:

Person Object 
name Property with getter and setter

to check if name is not initialized. 

Person p = new Person();
if(p.getName()!=null)

How can I get the last 7 characters of a PHP string?

It would be better to have a check before getting the string.

$newstring = substr($dynamicstring, -7);

if characters are greater then 7 return last 7 characters else return the provided string.

or do this if you need to return message or error if length is less then 7

$newstring = (strlen($dynamicstring)>7)?substr($dynamicstring, -7):"message";

substr documentation

Looping through rows in a DataView

//You can convert DataView to Table. using DataView.ToTable();

foreach (DataRow drGroup in dtGroups.Rows)
{
    dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";

    if (dtForms.DefaultView.Count > 0)
    {
        foreach (DataRow drForm in dtForms.DefaultView.ToTable().Rows)
        {
            drNew = dtNew.NewRow();

            drNew["FormId"] = drForm["FormId"];
            drNew["FormCaption"] = drForm["FormCaption"];
            drNew["GroupName"] = drGroup["GroupName"];
            dtNew.Rows.Add(drNew);
        }
    }
}

// Or You Can Use

// 2.

dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";

DataTable DTFormFilter = dtForms.DefaultView.ToTable();

foreach (DataRow drFormFilter in DTFormFilter.Rows)
{ 
                            //Your logic goes here
}

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

I was getting the xml as a String and using xml.getBytes() and getting this error. Changing to xml.getBytes(Charset.forName("UTF-8")) worked for me.

How to output only captured groups with sed?

Sed has up to nine remembered patterns but you need to use escaped parentheses to remember portions of the regular expression.

See here for examples and more detail

How to find the statistical mode?

The following function comes in three forms:

method = "mode" [default]: calculates the mode for a unimodal vector, else returns an NA
method = "nmodes": calculates the number of modes in the vector
method = "modes": lists all the modes for a unimodal or polymodal vector

modeav <- function (x, method = "mode", na.rm = FALSE)
{
  x <- unlist(x)
  if (na.rm)
    x <- x[!is.na(x)]
  u <- unique(x)
  n <- length(u)
  #get frequencies of each of the unique values in the vector
  frequencies <- rep(0, n)
  for (i in seq_len(n)) {
    if (is.na(u[i])) {
      frequencies[i] <- sum(is.na(x))
    }
    else {
      frequencies[i] <- sum(x == u[i], na.rm = TRUE)
    }
  }
  #mode if a unimodal vector, else NA
  if (method == "mode" | is.na(method) | method == "")
  {return(ifelse(length(frequencies[frequencies==max(frequencies)])>1,NA,u[which.max(frequencies)]))}
  #number of modes
  if(method == "nmode" | method == "nmodes")
  {return(length(frequencies[frequencies==max(frequencies)]))}
  #list of all modes
  if (method == "modes" | method == "modevalues")
  {return(u[which(frequencies==max(frequencies), arr.ind = FALSE, useNames = FALSE)])}  
  #error trap the method
  warning("Warning: method not recognised.  Valid methods are 'mode' [default], 'nmodes' and 'modes'")
  return()
}

Convert time.Time to string

You can use the Time.String() method to convert a time.Time to a string. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST".

If you need other custom format, you can use Time.Format(). For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss use the format string "2006-01-02 15:04:05".

Example:

t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))

Output (try it on the Go Playground):

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00

Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.

Also note that using Time.Format(), as the layout string you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format():

Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

How to call a JavaScript function, declared in <head>, in the body when I want to call it

You can call it like that:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript">
            var person = { name: 'Joe Blow' };
            function myfunction() {
               document.write(person.name);
            }
        </script>
    </head>
    <body>
        <script type="text/javascript">
            myfunction();
        </script>
    </body>
</html>

The result should be page with the only content: Joe Blow

Look here: http://jsfiddle.net/HWreP/

Best regards!

Angular redirect to login page

Usage with the final router

With the introduction of the new router it became easier to guard the routes. You must define a guard, which acts as a service, and add it to the route.

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { UserService } from '../../auth';

@Injectable()
export class LoggedInGuard implements CanActivate {
  constructor(user: UserService) {
    this._user = user;
  }

  canActivate() {
    return this._user.isLoggedIn();
  }
}

Now pass the LoggedInGuard to the route and also add it to the providers array of the module.

import { LoginComponent } from './components/login.component';
import { HomeComponent } from './components/home.component';
import { LoggedInGuard } from './guards/loggedin.guard';

const routes = [
    { path: '', component: HomeComponent, canActivate: [LoggedInGuard] },
    { path: 'login', component: LoginComponent },
];

The module declaration:

@NgModule({
  declarations: [AppComponent, HomeComponent, LoginComponent]
  imports: [HttpModule, BrowserModule, RouterModule.forRoot(routes)],
  providers: [UserService, LoggedInGuard],
  bootstrap: [AppComponent]
})
class AppModule {}

Detailed blog post about how it works with the final release: https://medium.com/@blacksonic86/angular-2-authentication-revisited-611bf7373bf9

Usage with the deprecated router

A more robust solution is to extend the RouterOutlet and when activating a route check if the user is logged in. This way you don't have to copy and paste your directive to every component. Plus redirecting based on a subcomponent can be misleading.

@Directive({
  selector: 'router-outlet'
})
export class LoggedInRouterOutlet extends RouterOutlet {
  publicRoutes: Array;
  private parentRouter: Router;
  private userService: UserService;

  constructor(
    _elementRef: ElementRef, _loader: DynamicComponentLoader,
    _parentRouter: Router, @Attribute('name') nameAttr: string,
    userService: UserService
  ) {
    super(_elementRef, _loader, _parentRouter, nameAttr);

    this.parentRouter = _parentRouter;
    this.userService = userService;
    this.publicRoutes = [
      '', 'login', 'signup'
    ];
  }

  activate(instruction: ComponentInstruction) {
    if (this._canActivate(instruction.urlPath)) {
      return super.activate(instruction);
    }

    this.parentRouter.navigate(['Login']);
  }

  _canActivate(url) {
    return this.publicRoutes.indexOf(url) !== -1 || this.userService.isLoggedIn()
  }
}

The UserService stands for the place where your business logic resides whether the user is logged in or not. You can add it easily with DI in the constructor.

When the user navigates to a new url on your website, the activate method is called with the current Instruction. From it you can grab the url and decide whether it is allowed or not. If not just redirect to the login page.

One last thing remain to make it work, is to pass it to our main component instead of the built in one.

@Component({
  selector: 'app',
  directives: [LoggedInRouterOutlet],
  template: template
})
@RouteConfig(...)
export class AppComponent { }

This solution can not be used with the @CanActive lifecycle decorator, because if the function passed to it resolves false, the activate method of the RouterOutlet won't be called.

Also wrote a detailed blog post about it: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492

how to print a string to console in c++

"Visual Studio does not support std::cout as debug tool for non-console applications"
- from Marius Amado-Alves' answer to "How can I see cout output in a non-console application?"

Which means if you use it, Visual Studio shows nothing in the "output" window (in my case VS2008)

How to serve .html files with Spring

It sounds like you are trying to do something like this:

  • Static HTML views
  • Spring controllers serving AJAX

If that is the case, as previously mentioned, the most efficient way is to let the web server(not Spring) handle HTML requests as static resources. So you'll want the following:

  1. Forward all .html, .css, .js, .png, etc requests to the webserver's resource handler
  2. Map all other requests to spring controllers

Here is one way to accomplish that...

web.xml - Map servlet to root (/)

<servlet>
            <servlet-name>sprung</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            ...
<servlet>

<servlet-mapping>
            <servlet-name>sprung</servlet-name>
            <url-pattern>/</url-pattern>
</servlet-mapping>

Spring JavaConfig

public class SpringSprungConfig extends DelegatingWebMvcConfiguration {

    // Delegate resource requests to default servlet
    @Bean
    protected DefaultServletHttpRequestHandler defaultServletHttpRequestHandler() {
        DefaultServletHttpRequestHandler dsrh = new DefaultServletHttpRequestHandler();
        return dsrh;
    }

    //map static resources by extension
    @Bean
    public SimpleUrlHandlerMapping resourceServletMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();

        //make sure static resources are mapped first since we are using
        //a slightly different approach
        mapping.setOrder(0);
        Properties urlProperties = new Properties();
        urlProperties.put("/**/*.css", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.js", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.png", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.html", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.woff", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.ico", "defaultServletHttpRequestHandler");
        mapping.setMappings(urlProperties);
        return mapping;
    }

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();

        //controller mappings must be evaluated after the static resource requests
        handlerMapping.setOrder(1);
        handlerMapping.setInterceptors(this.getInterceptors());
        handlerMapping.setPathMatcher(this.getPathMatchConfigurer().getPathMatcher());
        handlerMapping.setRemoveSemicolonContent(false);
        handlerMapping.setUseSuffixPatternMatch(false);
        //set other options here
        return handlerMapping;
    }
}

Additional Considerations

  • Hide .html extension - This is outside the scope of Spring if you are delegating the static resource requests. Look into a URL rewriting filter.
  • Templating - You don't want to duplicate markup in every single HTML page for common elements. This likely can't be done on the server if serving HTML as a static resource. Look into a client-side *VC framework. I'm fan of YUI which has numerous templating mechanisms including Handlebars.

How to count number of files in each directory?

You could arrange to find all the files, remove the file names, leaving you a line containing just the directory name for each file, and then count the number of times each directory appears:

find . -type f |
sed 's%/[^/]*$%%' |
sort |
uniq -c

The only gotcha in this is if you have any file names or directory names containing a newline character, which is fairly unlikely. If you really have to worry about newlines in file names or directory names, I suggest you find them, and fix them so they don't contain newlines (and quietly persuade the guilty party of the error of their ways).


If you're interested in the count of the files in each sub-directory of the current directory, counting any files in any sub-directories along with the files in the immediate sub-directory, then I'd adapt the sed command to print only the top-level directory:

find . -type f |
sed -e 's%^\(\./[^/]*/\).*$%\1%' -e 's%^\.\/[^/]*$%./%' |
sort |
uniq -c

The first pattern captures the start of the name, the dot, the slash, the name up to the next slash and the slash, and replaces the line with just the first part, so:

./dir1/dir2/file1

is replaced by

./dir1/

The second replace captures the files directly in the current directory; they don't have a slash at the end, and those are replace by ./. The sort and count then works on just the number of names.

Making a request to a RESTful API using python

Using requests and json makes it simple.

  1. Call the API
  2. Assuming the API returns a JSON, parse the JSON object into a Python dict using json.loads function
  3. Loop through the dict to extract information.

Requests module provides you useful function to loop for success and failure.

if(Response.ok): will help help you determine if your API call is successful (Response code - 200)

Response.raise_for_status() will help you fetch the http code that is returned from the API.

Below is a sample code for making such API calls. Also can be found in github. The code assumes that the API makes use of digest authentication. You can either skip this or use other appropriate authentication modules to authenticate the client invoking the API.

#Python 2.7.6
#RestfulClient.py

import requests
from requests.auth import HTTPDigestAuth
import json

# Replace with the correct URL
url = "http://api_url"

# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)

# For successful API call, response code will be 200 (OK)
if(myResponse.ok):

    # Loading the response data into a dict variable
    # json.loads takes in only binary or string variables so using content to fetch binary content
    # Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
    jData = json.loads(myResponse.content)

    print("The response contains {0} properties".format(len(jData)))
    print("\n")
    for key in jData:
        print key + " : " + jData[key]
else:
  # If response code is not ok (200), print the resulting http error code with description
    myResponse.raise_for_status()

Add regression line equation and R^2 on graph

really love @Ramnath solution. To allow use to customize the regression formula (instead of fixed as y and x as literal variable names), and added the p-value into the printout as well (as @Jerry T commented), here is the mod:

lm_eqn <- function(df, y, x){
    formula = as.formula(sprintf('%s ~ %s', y, x))
    m <- lm(formula, data=df);
    # formating the values into a summary string to print out
    # ~ give some space, but equal size and comma need to be quoted
    eq <- substitute(italic(target) == a + b %.% italic(input)*","~~italic(r)^2~"="~r2*","~~p~"="~italic(pvalue), 
         list(target = y,
              input = x,
              a = format(as.vector(coef(m)[1]), digits = 2), 
              b = format(as.vector(coef(m)[2]), digits = 2), 
             r2 = format(summary(m)$r.squared, digits = 3),
             # getting the pvalue is painful
             pvalue = format(summary(m)$coefficients[2,'Pr(>|t|)'], digits=1)
            )
          )
    as.character(as.expression(eq));                 
}

geom_point() +
  ggrepel::geom_text_repel(label=rownames(mtcars)) +
  geom_text(x=3,y=300,label=lm_eqn(mtcars, 'hp','wt'),color='red',parse=T) +
  geom_smooth(method='lm')

enter image description here Unfortunately, this doesn't work with facet_wrap or facet_grid.

Difference between java HH:mm and hh:mm on SimpleDateFormat

kk: (01-24) will look like 01, 02..24.

HH:(00-23) will look like 00, 01..23.

hh:(01-12 in AM/PM) will look like 01, 02..12.

so the last printout (working2) is a bit weird. It should say 12:00:00 (edit: if you were setting the working2 timezone and format, which (as kdagli pointed out) you are not)

Undefined index with $_POST

Related question: What is the best way to access unknown array elements without generating PHP notice?

Using the answer from the question above, you can safely get a value from $_POST without generating PHP notice if the key does not exists.

echo _arr($_POST, 'username', 'no username supplied');  
// will print $_POST['username'] or 'no username supplied'

Angular 2 How to redirect to 404 or other path if the path does not exist

My preferred option on 2.0.0 and up is to create a 404 route and also allow a ** route path to resolve to the same component. This allows you to log and display more information about the invalid route rather than a plain redirect which can act to hide the error.

Simple 404 example:

{ path '/', component: HomeComponent },
// All your other routes should come first    
{ path: '404', component: NotFoundComponent },
{ path: '**', component: NotFoundComponent }

To display the incorrect route information add in import to router within NotFoundComponent:

import { Router } from '@angular/router';

Add it to the constructior of NotFoundComponent:

constructor(public router: Router) { }

Then you're ready to reference it from your HTML template e.g.

The page <span style="font-style: italic">{{router.url}}</span> was not found.

How can I create a temp file with a specific extension with .NET?

Why not checking if the file exists?

string fileName;
do
{
    fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";
} while (System.IO.File.Exists(fileName));

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

Because your update uses PUT method, {entryId: $scope.entryId} is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '@entryId'} when you define your update, which means

return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
  query: {method:'GET', params:{entryId:''}, isArray:true},
  post: {method:'POST'},
  update: {method:'PUT', params: {entryId: '@entryId'}},
  remove: {method:'DELETE'}
});

Fix: Was missing a closing curly brace on the update line.

how to find seconds since 1970 in java

The answer you want, "1317427200", is achieved if your reference months are January and October. If so, the dates you are looking for are 1970-JAN-01 and 2011-OCT-01, correct?

Then the problem are these numbers you are using for your months.

See, if you check the Calendar API documentation or even the constants provided in there ("Calendar.JANUARY", "Calendar.FEBRUARY" and so on), you'll discover that months start at 0 (being January).

So checking your code, you are passing february and november, which would result in "1317510000".

Best regards.

C++ vector of char array

You cannot store arrays in vectors (or in any other standard library container). The things that standard library containers store must be copyable and assignable, and arrays are neither of these.

If you really need to put an array in a vector (and you probably don't - using a vector of vectors or a vector of strings is more likely what you need), then you can wrap the array in a struct:

struct S {
  char a[10];
};

and then create a vector of structs:

vector <S> v;
S s;
s.a[0] = 'x';
v.push_back( s );

Difference between MEAN.js and MEAN.io

Here is a side-by-side comparison of several application starters/generators and other technologies including MEAN.js, MEAN.io, and cleverstack. I keep adding alternatives as I find time and as that happens, the list of potentially provided benefits keeps growing too. Today it's up to around 1600. If anyone wants to help improve its accuracy or completeness, click the next link and do a questionnaire about something you know.

Compare app technologies project

From this database, the system generates reports like the following:

MeanJS vs MeanIO trade-off report

Jquery href click - how can I fire up an event?

You are binding the click event to anchors with an href attribute with value sign_new.

Either bind anchors with class sign_new or bind anchors with href value #sign_up. I would prefer the former.

Reverse engineering from an APK file to a project

If you are looking for a professional alternative, have a look at JEB Decompiler from PNF Software.

There is a demo version that will let you decompile most code.

Getting char from string at specified index

Getting one char from string at specified index

Dim pos As Integer
Dim outStr As String
pos = 2 
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)

outStr="b"

How to monitor Java memory usage?

About System.gc()… I just read in Oracle's documentation the following sentence here

The performance effect of explicit garbage collections can be measured by disabling them using the flag -XX:+DisableExplicitGC, which causes the VM to ignore calls to System.gc().

If your VM vendor and version supports that flag you can run your code with and without it and compare Performance.

Also note the previous quoted sentence is preceded by this one:

This can force a major collection to be done when it may not be necessary (for example, when a minor collection would suffice), and so in general should be avoided.

How can I check if PostgreSQL is installed or not via Linux script?

What about trying the which command?

If you were to run which psql and Postgres is not installed there appears to be no output. You just get the terminal prompt ready to accept another command:

> which psql
>

But if Postgres is installed you'll get a response with the path to the location of the Postgres install:

> which psql
/opt/boxen/homebrew/bin/psql

Looking at man which there also appears to be an option that could help you out:

-s      No output, just return 0 if any of the executables are found, or
        1 if none are found.

So it seems like as long as whatever scripting language you're using can can execute a terminal command you could send which -s psql and use the return value to determine if Postgres is installed. From there you can print that result however you like.

I do have postgres installed on my machine so I run the following

> which -s psql
> echo $?
0

which tells me that the command returned 0, indicating that the Postgres executable was found on my machine.

Here's the information about using echo $?

How to check if a string contains text from an array of substrings in JavaScript?

If the array is not large, you could just loop and check the string against each substring individually using indexOf(). Alternatively you could construct a regular expression with substrings as alternatives, which may or may not be more efficient.

Memcache Vs. Memcached

(PartlyStolen from ServerFault)

I think that both are functionally the same, but they simply have different authors, and the one is simply named more appropriately than the other.


Here is a quick backgrounder in naming conventions (for those unfamiliar), which explains the frustration by the question asker: For many *nix applications, the piece that does the backend work is called a "daemon" (think "service" in Windows-land), while the interface or client application is what you use to control or access the daemon. The daemon is most often named the same as the client, with the letter "d" appended to it. For example "imap" would be a client that connects to the "imapd" daemon.

This naming convention is clearly being adhered to by memcache when you read the introduction to the memcache module (notice the distinction between memcache and memcached in this excerpt):

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.danga.com/memcached/.

The frustration here is caused by the author of the PHP extension which was badly named memcached, since it shares the same name as the actual daemon called memcached. Notice also that in the introduction to memcached (the php module), it makes mention of libmemcached, which is the shared library (or API) that is used by the module to access the memcached daemon:

memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).

Information about libmemcached can be found at » http://tangent.org/552/libmemcached.html.

How to insert a file in MySQL database?

You need to use BLOB, there's TINY, MEDIUM, LONG, and just BLOB, as with other types, choose one according to your size needs.

TINYBLOB 255
BLOB 65535
MEDIUMBLOB 16777215
LONGBLOB 4294967295
(in bytes)

The insert statement would be fairly normal. You need to read the file using fread and then addslashes to it.

Singletons vs. Application Context in Android?

They're actually the same. There's one difference I can see. With Application class you can initialize your variables in Application.onCreate() and destroy them in Application.onTerminate(). With singleton you have to rely VM initializing and destroying statics.

What is the difference between a data flow diagram and a flow chart?

Other answers have gone over the basics of what each thing is. At the higher level, a flowchart is a design level tool, while DFDs are more analysis.

DFDs have some nice features. Since they show the flow of data, some things become more obvious when charted this way: some data is only used by a few routines, some routines use only some bits of data, some routines touch everything. Seeing that up front helps organize, restructuring, and planning.

A follow-on worth exploring is the Event-Response Diagram, which is basically a DFD only showing process and data needed to process an "event", meaning something triggered externally (customer makes payment, etc.).

OR, AND Operator

many answers above, i will try a different way:

if you are looking for bitwise operations use only one of the marks like:

3 & 1 //==1 - and 4 | 1 //==5 - or

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

You get this warning message when the servlet api jar file has already been loaded in the container and you try to load it once again from lib directory.

The Servlet specs say you are not allowed to have servlet.jar in your webapps lib directory.

  • Get rid of the warning message by simply removing servlet.jar from your lib directory.
  • If you don't find the jar in the lib directory scan for your build path and remove the jar.

C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\project\WEB-INF\lib

If you are running a maven project, change the javax.servlet-api dependency to scope provided in you pom.xml since the container already provided the servlet jar in itself.

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

I had the same issue. In my case I was using digitalocean and nginx.
I have first setup a domain example.app and a subdomain dev.exemple.app in digitalocean. Second,I purchased two ssl certificat from godaddy. And finaly, I configured two domain in nginx to use those two ssl certificat with the following snipet

My example.app domain config

    server {
    listen 7000 default_server;
    listen [::]:7000 default_server;

     listen 443 ssl default_server;
     listen [::]:443 ssl default_server;

    root /srv/nodejs/echantillonnage1;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name echantillonnage.app;
    ssl_certificate /srv/nodejs/certificatSsl/widcardcertificate/echantillonnage.app.chained.crt;
    ssl_certificate_key /srv/nodejs/certificatSsl/widcardcertificate/echantillonnage.app.key;

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            proxy_pass http://127.0.0.1:8090;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    #try_files $uri $uri/ =404;
    }
 }

My dev.example.app

   server {
    listen 7000 default_server;
    listen [::]:7000 default_server;

     listen 444 ssl default_server;
     listen [::]:444 ssl default_server;

    root /srv/nodejs/echantillonnage1;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name dev.echantillonnage.app;
    ssl_certificate /srv/nodejs/certificatSsl/dev/dev.echantillonnage.app.chained.crt;
    ssl_certificate_key /srv/nodejs/certificatSsl/dev/dev.echantillonnage.app.key;

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            proxy_pass http://127.0.0.1:8091;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    #try_files $uri $uri/ =404;
    }
 }

When I was launching https://dev.echantillonnage.app , I was getting

    Fix CURL (51) SSL error: no alternative certificate subject name matches

My mistake was the two lines bellow

    listen 444 ssl default_server;
     listen [::]:444 ssl default_server;

I had to change this to:

     listen 443 ssl;
     listen [::]:443 ssl;

What's the best way to calculate the size of a directory in .NET?

More faster! Add COM reference "Windows Script Host Object..."

public double GetWSHFolderSize(string Fldr)
    {
        //Reference "Windows Script Host Object Model" on the COM tab.
        IWshRuntimeLibrary.FileSystemObject FSO = new     IWshRuntimeLibrary.FileSystemObject();
        double FldrSize = (double)FSO.GetFolder(Fldr).Size;
        Marshal.FinalReleaseComObject(FSO);
        return FldrSize;
    }
private void button1_Click(object sender, EventArgs e)
        {
            string folderPath = @"C:\Windows";
        Stopwatch sWatch = new Stopwatch();

        sWatch.Start();
        double sizeOfDir = GetWSHFolderSize(folderPath);
        sWatch.Stop();
        MessageBox.Show("Directory size in Bytes : " + sizeOfDir + ", Time: " + sWatch.ElapsedMilliseconds.ToString());
          }

How to return a PNG image from Jersey REST service method to the browser

I built a general method for that with following features:

  • returning "not modified" if the file hasn't been modified locally, a Status.NOT_MODIFIED is sent to the caller. Uses Apache Commons Lang
  • using a file stream object instead of reading the file itself

Here the code:

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private static final Logger logger = LoggerFactory.getLogger(Utils.class);

@GET
@Path("16x16")
@Produces("image/png")
public Response get16x16PNG(@HeaderParam("If-Modified-Since") String modified) {
    File repositoryFile = new File("c:/temp/myfile.png");
    return returnFile(repositoryFile, modified);
}

/**
 * 
 * Sends the file if modified and "not modified" if not modified
 * future work may put each file with a unique id in a separate folder in tomcat
 *   * use that static URL for each file
 *   * if file is modified, URL of file changes
 *   * -> client always fetches correct file 
 * 
 *     method header for calling method public Response getXY(@HeaderParam("If-Modified-Since") String modified) {
 * 
 * @param file to send
 * @param modified - HeaderField "If-Modified-Since" - may be "null"
 * @return Response to be sent to the client
 */
public static Response returnFile(File file, String modified) {
    if (!file.exists()) {
        return Response.status(Status.NOT_FOUND).build();
    }

    // do we really need to send the file or can send "not modified"?
    if (modified != null) {
        Date modifiedDate = null;

        // we have to switch the locale to ENGLISH as parseDate parses in the default locale
        Locale old = Locale.getDefault();
        Locale.setDefault(Locale.ENGLISH);
        try {
            modifiedDate = DateUtils.parseDate(modified, org.apache.http.impl.cookie.DateUtils.DEFAULT_PATTERNS);
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        Locale.setDefault(old);

        if (modifiedDate != null) {
            // modifiedDate does not carry milliseconds, but fileDate does
            // therefore we have to do a range-based comparison
            // 1000 milliseconds = 1 second
            if (file.lastModified()-modifiedDate.getTime() < DateUtils.MILLIS_PER_SECOND) {
                return Response.status(Status.NOT_MODIFIED).build();
            }
        }
    }        
    // we really need to send the file

    try {
        Date fileDate = new Date(file.lastModified());
        return Response.ok(new FileInputStream(file)).lastModified(fileDate).build();
    } catch (FileNotFoundException e) {
        return Response.status(Status.NOT_FOUND).build();
    }
}

/*** copied from org.apache.http.impl.cookie.DateUtils, Apache 2.0 License ***/

/**
 * Date format pattern used to parse HTTP date headers in RFC 1123 format.
 */
public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";

/**
 * Date format pattern used to parse HTTP date headers in RFC 1036 format.
 */
public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";

/**
 * Date format pattern used to parse HTTP date headers in ANSI C
 * <code>asctime()</code> format.
 */
public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";

public static final String[] DEFAULT_PATTERNS = new String[] {
    PATTERN_RFC1036,
    PATTERN_RFC1123,
    PATTERN_ASCTIME
};

Note that the Locale switching does not seem to be thread-safe. I think, it's better to switch the locale globally. I am not sure about the side-effects though...

Converting integer to string in Python

There are several ways to convert an integer to string in python. You can use [ str(integer here) ] function, the f-string [ f'{integer here}'], the .format()function [ '{}'.format(integer here) and even the '%s'% keyword [ '%s'% integer here]. All this method can convert an integer to string.

See below example

#Examples of converting an intger to string

#Using the str() function
number = 1
convert_to_string = str(number)
print(type(convert_to_string)) # output (<class 'str'>)

#Using the f-string
number = 1
convert_to_string = f'{number}'
print(type(convert_to_string)) # output (<class 'str'>)

#Using the  {}'.format() function
number = 1
convert_to_string = '{}'.format(number)
print(type(convert_to_string)) # output (<class 'str'>)

#Using the  '% s '% keyword
number = 1
convert_to_string = '% s '% number
print(type(convert_to_string)) # output (<class 'str'>)


Java: How to stop thread?

JavaSun recomendation is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread to terminate.

You can that way kill the other process, and the current one afterwards.

Rails: How do I create a default value for attributes in Rails activerecord's model?

When I need default values its usually for new records before the new action's view is rendered. The following method will set the default values for only new records so that they are available when rendering forms. before_save and before_create are too late and will not work if you want default values to show up in input fields.

after_initialize do
  if self.new_record?
    # values will be available for new record forms.
    self.status = 'P'
    self.featured = true
  end
end

How to get the Mongo database specified in connection string in C#

The answer below is apparently obsolete now, but works with older drivers. See comments.

If you have the connection string you could also use MongoDatabase directly:

var db =  MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");

Kotlin unresolved reference in IntelliJ

Another thing I would like to add is that you need to select View -> Tool Windows -> Gradle before you can run the project using the Gradle.

If using the Gradle the project builds and runs normally but using the IntelliJ it doesn't, then this can solve the matter.

Finding duplicate rows in SQL Server

I use two methods to find duplicate rows. 1st method is the most famous one using group by and having. 2nd method is using CTE - Common Table Expression.

As mentioned by @RedFilter this way is also right. Many times I find CTE method is also useful for me.

WITH TempOrg (orgName,RepeatCount)
AS
(
SELECT orgName,ROW_NUMBER() OVER(PARTITION by orgName ORDER BY orgName) 
AS RepeatCount
FROM dbo.organizations
)
select t.*,e.id from organizations   e
inner join TempOrg t on t.orgName= e.orgName
where t.RepeatCount>1

In the example above we collected the result by finding repeat occurrence using ROW_NUMBER and PARTITION BY. Then we applied where clause to select only rows which are on repeat count more than 1. All the result is collected CTE table and joined with Organizations table.

Source : CodoBee

Git keeps prompting me for a password

Guide to Git on Windows and GitHub using SSH to push/pull: An Illustrated Guide to Git on Windows

  1. Download and install PuTTY
  2. Set environment variable 'GIT_SSH' = 'path\to\plink.exe' (in installed putty folder) - very important!!!
  3. Restart Windows Explorer for environment variables to take effect (cannot only restart command prompt)
  4. Run puttygen.exe to generate new key, copy the public key to the GitHub site
  5. Save this new private key somewhere safe on the disk (preferable not Dropbox)
  6. Run putty.exe and connect SSH to github.co
  7. Quickly get to startup folder by running "shell:startup".
  8. Make your private key startup with Windows via pageant. Create a shortcut in Startup folder with syntax "path\to\pageant.exe" "path\to\privatekey"
  9. We do not need to set the 'puttykeyfile' setting inside .git/config of our repositories
  10. Very important is that the "SSH clone URL" of GitHub is used and not HTTPS.

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

If you are using docker-compose, and in docker-compose.yml have: volumes: - .:/myapp That means you local workspace is mapped to the container's /myapp folder.

Anything in /myapp will not be deleted for the volumes define.

You can delete ./tmp/pids/server.pid in you local machine. Then the container's /myapp will not have this file.

How to find all occurrences of an element in a list

Or Use range (python 3):

l=[i for i in range(len(lst)) if lst[i]=='something...']

For (python 2):

l=[i for i in xrange(len(lst)) if lst[i]=='something...']

And then (both cases):

print(l)

Is as expected.

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln


/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

Bash checking if string does not contain other string

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf 
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"

Where is the WPF Numeric UpDown control?

Simply use the IntegerUpDown control in the Extended.Wpf.Toolkit You can use it like this:

  1. Add to your XAML the following namespace:

    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"

  2. In your XAML where you want the control use:

    <xctk:IntegerUpDown Name="myUpDownControl" />

A full list of all the new/popular databases and their uses?

I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

I too received the same error as quoted below:

The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path.

I followed these steps to resolve the issue:

  1. Right Click on Project
  2. Select Properties
  3. Select Project Facets
  4. Select Apache Tomcat as Runtime server
  5. Click OK

Meaning of delta or epsilon argument of assertEquals for double values

Epsilon is a difference between expected and actual values which you can accept thinking they are equal. You can set .1 for example.

What does <a href="#" class="view"> mean?

I felt like replying as well, explaining the same thing as the others a bit differently. I am sure you know most of this, but it might help someone else.

<a href="#" class="view">

The

href="#"

part is a commonly used way to make sure the link doesn't lead anywhere on it's own. the #-attribute is used to create a link to some other section in the same document. For example clicking a link of this kind:

<a href="#news">Go to news</a>

will take you to wherever you have the

<a name="news"></a>

code. So if you specify # without any name like in your case, the link leads nowhere.

The

class="view"

part gives it an identifier that CSS or javascript can use. Inside the CSS-files (if you have any) you will find specific styling procedures on all the elements tagged with the "view"-class.

To find out where the URL is specified I would look in the javascript code. It is either written directly in the same document or included from another file.

Search your source code for something like:

<script type="text/javascript"> bla bla bla </script>

or

<script> bla bla bla </script>

and then search for any reference to your "view"-class. An included javascript file can look something like this:

<script type="text/javascript" src="include/javascript.js"></script>

In that case, open javascript.js under the "include" folder and search in that file. Most commonly the includes are placed between <head> and </head> or close to the </body>-tag.

A faster way to find the link is to search for the actual link it goes to. For example, if you are directed to http://www.google.com/search?q=html when you click it, search for "google.com" or something in all the files you have in your web project, just remember the included files.

In many text editors you can open all the files at once, and then search in them all for something.

Setting unique Constraint with fluent API?

Here is an extension method for setting unique indexes more fluently:

public static class MappingExtensions
{
    public static PrimitivePropertyConfiguration IsUnique(this PrimitivePropertyConfiguration configuration)
    {
        return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute { IsUnique = true }));
    }
}

Usage:

modelBuilder 
    .Entity<Person>() 
    .Property(t => t.Name)
    .IsUnique();

Will generate migration such as:

public partial class Add_unique_index : DbMigration
{
    public override void Up()
    {
        CreateIndex("dbo.Person", "Name", unique: true);
    }

    public override void Down()
    {
        DropIndex("dbo.Person", new[] { "Name" });
    }
}

Src: Creating Unique Index with Entity Framework 6.1 fluent API

Two submit buttons in one form

I think you should be able to read the name/value in your GET array. I think that the button that wasn't clicked wont appear in that list.

Best algorithm for detecting cycles in a directed graph

https://mathoverflow.net/questions/16393/finding-a-cycle-of-fixed-length I like this solution the best specially for 4 length:)

Also phys wizard says u have to do O(V^2). I believe that we need only O(V)/O(V+E). If the graph is connected then DFS will visit all nodes. If the graph has connected sub graphs then each time we run a DFS on a vertex of this sub graph we will find the connected vertices and wont have to consider these for the next run of the DFS. Therefore the possibility of running for each vertex is incorrect.

Copying and pasting data using VBA code

'So from this discussion i am thinking this should be the code then.

Sub Button1_Click()
    Dim excel As excel.Application
    Dim wb As excel.Workbook
    Dim sht As excel.Worksheet
    Dim f As Object

    Set f = Application.FileDialog(3)
    f.AllowMultiSelect = False
    f.Show

    Set excel = CreateObject("excel.Application")
    Set wb = excel.Workbooks.Open(f.SelectedItems(1))
    Set sht = wb.Worksheets("Data")

    sht.Activate
    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues


    wb.Close
End Sub

'Let me know if this is correct or a step was missed. Thx.

FIX CSS <!--[if lt IE 8]> in IE

If you want this to work in IE 8 and below, use

<!--[if lte IE 8]>

lte meaning "Less than or equal".

For more on conditional comments, see e.g. the quirksmode.org page.

Renaming a branch in GitHub

Three simple steps

  • git push origin head

  • git branch -m old-branch-name new-branch-name

  • git push origin head

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

Android Paint: .measureText() vs .getTextBounds()

There is another way to measure the text bounds precisely, first you should get the path for the current Paint and text. In your case it should be like this:

p.getTextPath(someText, 0, someText.length(), 0.0f, 0.0f, mPath);

After that you can call:

mPath.computeBounds(mBoundsPath, true);

In my code it always returns correct and expected values. But, not sure if it works faster than your approach.

How to get instance variables in Python?

Use vars()

class Foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2

vars(Foo()) #==> {'a': 1, 'b': 2}
vars(Foo()).keys() #==> ['a', 'b']

Adding a directory to PATH in Ubuntu

Actually I would advocate .profile if you need it to work from scripts, and in particular, scripts run by /bin/sh instead of Bash. If this is just for your own private interactive use, .bashrc is fine, though.

Get value from text area

use the val() method:

$(document).ready(function () {
    var j = $("textarea");
    if (j.val().length > 0) {
        alert(j.val());
    }
});

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

Even if fileno(FILE *) may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.

To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)

Should MySQL have its timezone set to UTC?

This is a working example:

jdbc:mysql://localhost:3306/database?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=Europe/Moscow

raw vs. html_safe vs. h to unescape html

The difference is between Rails’ html_safe() and raw(). There is an excellent post by Yehuda Katz on this, and it really boils down to this:

def raw(stringish)

  stringish.to_s.html_safe

end

Yes, raw() is a wrapper around html_safe() that forces the input to String and then calls html_safe() on it. It’s also the case that raw() is a helper in a module whereas html_safe() is a method on the String class which makes a new ActiveSupport::SafeBuffer instance — that has a @dirty flag in it.

Refer to "Rails’ html_safe vs. raw".

jQuery: enabling/disabling datepicker

This works for me on toggling enable and disable datepicker of JQuery:

if (condition) {
          $('#ElementID').datepicker(); //Enable datepicker                   
} else {
         //Disable datepicker without the ability to enter any character on text input
          $('#ElementID').datepicker('destroy');
          $('#ElementID').attr('readonly', true); }

I don't know why but when I use enable/disable in datepicker options, it doesn't behave the way it should be. It only works after you enable and disable it, but once you disable it, it doesn't enable again after, so the code above works perfectly fine for me:

if (condition) {
      $('#ElementID').datepicker('enable'); //Enable datepicker                   
} else {
      //Disable datepicker but I cannot enable it again once it goes through this condition
      $('#ElementID').datepicker('disable');  }

Python vs. Java performance (runtime speed)

If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?

For example:

  • Does it count when Java executes an empty loop faster than Python?
  • Or is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away?
  • Or is that "a language characteristic"?
  • Do you want to know how many bytecodes each language can execute per second?
  • Which ones? Only the fast ones or all of them?
  • How do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime?
  • Do you include code compilation times (which are extra in Java but always included in Python)?

Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.

CentOS: Copy directory to another directory

cp -r /home/server/folder/test /home/server/

How to parse a string in JavaScript?

as amber and sinan have noted above, the javascritp '.split' method will work just fine. Just pass it the string separator(-) and the string that you intend to split('123-abc-itchy-knee') and it will do the rest.

    var coolVar = '123-abc-itchy-knee';
    var coolVarParts = coolVar.split('-'); // this is an array containing the items

    var1=coolVarParts[0]; //this will retrieve 123

To access each item from the array just use the respective index(indices start at zero).

Checking if output of a command contains a certain string in a shell script

Test the return value of grep:

./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
   echo "matched"
fi

which is done idiomatically like so:

if ./somecommand | grep -q 'string'; then
   echo "matched"
fi

and also:

./somecommand | grep -q 'string' && echo 'matched'

How to leave space in HTML

If you are looking for paragraph indent then you can go for 'text-indent' declaration in CSS.

<!DOCTYPE html>   
 <html>
        <head>
            <style>
                p { text-indent: 50px; }
            </style>
        </head>
        <body>
            <p>This paragraph will be indented by 50px. I hope this helps! Only the first line will be indented.</p>
        </body>
    </html>

Hiding an Excel worksheet with VBA

Just wanted to add a little more detail to the answers given. You can also use

sheet.Visible = False

to hide and

sheet.Visible = True

to unhide.

Source

How to uninstall a windows service and delete its files without rebooting

Both Jonathan and Charles are right... you've got to stop the service first, then uninstall/reinstall. Combining their two answers makes the perfect batch file or PowerShell script.

I will make mention of a caution learned the hard way -- Windows 2000 Server (possibly the client OS as well) will require a reboot before the reinstall no matter what. There must be a registry key that is not fully cleared until the box is rebooted. Windows Server 2003, Windows XP and later OS versions do not suffer that pain.

How to set image name in Dockerfile?

How to build an image with custom name without using yml file:

docker build -t image_name .

How to run a container with custom name:

docker run -d --name container_name image_name

Serialize Property as Xml Attribute in Element

Kind of, use the XmlAttribute instead of XmlElement, but it won't look like what you want. It will look like the following:

<SomeModel SomeStringElementName="testData"> 
</SomeModel> 

The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.

// TODO: make the class generic so that an int or string can be used.
[Serializable]  
public class SerializationClass
{
    public SerializationClass(string value)
    {
        this.Value = value;
    }

    [XmlAttribute("value")]
    public string Value { get; }
}


[Serializable]                     
public class SomeModel                     
{                     
    [XmlIgnore]                     
    public string SomeString { get; set; }                     

    [XmlIgnore]                      
    public int SomeInfo { get; set; }  

    [XmlElement]
    public SerializationClass SomeStringElementName
    {
        get { return new SerializationClass(this.SomeString); }
    }               
}

Hide HTML element by id

If you want to do it via javascript rather than CSS you can use:

var link = document.getElementById('nav-ask');
link.style.display = 'none'; //or
link.style.visibility = 'hidden';

depending on what you want to do.

Remove '\' char from string c#

         while ((line = stringReader.ReadLine()) != null)
         {
             // split the lines
             for (int c = 0; c < line.Length; c++)
             {
                 line = line.Replace("\\", "");
                 lineBreakOne = line.Substring(1, c - 2);
                 lineBreakTwo = line.Substring(c + 2, line.Length - 2);
             }
         }

How to import popper.js?

IN bootstrap 4 you need to add popper js for tooltip, I also don`t understand why bootstrap 4 includes external popper.js, It means bootstrap makes more complicated instead of easy when upgrading to the latest versions.

You can import popper js before bootstrap on angular or a simple html, Angular import would be like this

npm install popper.js --save

then go to .angular-cli.json and change the order like below.

 "scripts": [
        "../node_modules/jquery/dist/jquery.slim.min.js",
        "../node_modules/tether/dist/js/tether.min.js", 
        "../node_modules/popper.js/dist/umd/popper.js",              
        "../node_modules/bootstrap/dist/js/bootstrap.min.js"
      ],

you can also use CDN direct call popper js into your any project.

https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.js https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.min.js

How can I create a dynamic button click event on a dynamic button?

Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);

//protected void button_Click (object sender, EventArgs e) { }

How can I send an email through the UNIX mailx command?

mail [-s subject] [-c ccaddress] [-b bccaddress] toaddress

-c and -b are optional.

-s : Specify subject;if subject contains spaces, use quotes.

-c : Send carbon copies to list of users seperated by comma.

-b : Send blind carbon copies to list of users seperated by comma.

Hope my answer clarifies your doubt.

Build Error - missing required architecture i386 in file

I just wanted to mention that in XCode if you go to "Edit Project Settings" and find "Search Paths" There is a field for "Framework Search Paths". Updating this should fix the problem, without having to hack the project file!

Cheers!

Jesse

How to disable Paste (Ctrl+V) with jQuery?

jQuery('input.disablePaste').keydown(function(event) {
    var forbiddenKeys = new Array('c', 'x', 'v');
    var keyCode = (event.keyCode) ? event.keyCode : event.which;
    var isCtrl;
    isCtrl = event.ctrlKey
    if (isCtrl) {
        for (i = 0; i < forbiddenKeys.length; i++) {
            if (forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
                 return false;
            }
        }
    }
    return true;
});

List supported SSL/TLS versions for a specific OpenSSL build

Try the following command:

openssl ciphers

This should produce a list of all of the ciphers supported in your version of openssl.

To see just a particular set of ciphers (e.g. just sslv3 ciphers) try:

openssl ciphers -ssl3

See https://www.openssl.org/docs/apps/ciphers.html for more info.

How to horizontally align ul to center of div?

ul {
      text-align: center;
      list-style: inside;
    }

C# Public Enums in Classes

Just declare the enum outside the bounds of the class. Like this:

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
    ...
}

Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)

How to select a record and update it, with a single queryset in Django?

This answer compares the above two approaches. If you want to update many objects in a single line, go for:

# Approach 1
MyModel.objects.filter(field1='Computer').update(field2='cool')

Otherwise you would have to iterate over the query set and update individual objects:

#Approach 2    
objects = MyModel.objects.filter(field1='Computer')
for obj in objects:
    obj.field2 = 'cool'
    obj.save()
  1. Approach 1 is faster because, it makes only one database query, compared to approach 2 which makes 'n+1' database queries. (For n items in the query set)

  2. Fist approach makes one db query ie UPDATE, the second one makes two: SELECT and then UPDATE.

  3. The tradeoff is that, suppose you have any triggers, like updating updated_on or any such related fields, it will not be triggered on direct update ie approach 1.

  4. Approach 1 is used on a queryset, so it is possible to update multiple objects at once, not in the case of approach 2.

How do I abort/cancel TPL Tasks?

You should not try to do this directly. Design your tasks to work with a CancellationToken, and cancel them this way.

In addition, I would recommend changing your main thread to function via a CancellationToken as well. Calling Thread.Abort() is a bad idea - it can lead to various problems that are very difficult to diagnose. Instead, that thread can use the same Cancellation that your tasks use - and the same CancellationTokenSource can be used to trigger the cancellation of all of your tasks and your main thread.

This will lead to a far simpler, and safer, design.

How to read a file in other directory in python

Looks like you are trying to open a directory for reading as if it's a regular file. Many OSs won't let you do that. You don't need to anyway, because what you want (judging from your description) is

x_file = open(os.path.join(direct, "5_1.txt"), "r")  

or simply

x_file = open(direct+"/5_1.txt", "r")

excel vba getting the row,cell value from selection.address

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

Angular 2 declaring an array of objects

First, generate an Interface

Assuming you are using TypeScript & Angular CLI, you can generate one by using the following command

ng g interface car

After that set the data types of its properties

// car.interface.ts
export interface car {
  id: number;
  eco: boolean;
  wheels: number;
  name: string;
}

You can now import your interface in the class that you want.

import {car} from "app/interfaces/car.interface";

And update the collection/array of car objects by pushing items in the array.

this.car.push({
  id: 12345,
  eco: true,
  wheels: 4,
  name: 'Tesla Model S',
});

More on interfaces:

An interface is a TypeScript artifact, it is not part of ECMAScript. An interface is a way to define a contract on a function with respect to the arguments and their type. Along with functions, an interface can also be used with a Class as well to define custom types. An interface is an abstract type, it does not contain any code as a class does. It only defines the 'signature' or shape of an API. During transpilation, an interface will not generate any code, it is only used by Typescript for type checking during development. - https://angular-2-training-book.rangle.io/handout/features/interfaces.html

How to Update Date and Time of Raspberry Pi With out Internet

You will need to configure your Win7 PC as a Time Server, and then configure the RasPi to connect to it for NTP services.

Configure Win7 as authoritative time server. Configure RasPi time server lookup.

How to change a particular element of a C++ STL vector

Even though @JamesMcNellis answer is a valid one I would like to explain something about error handling and also the fact that there is another way of doing what you want.

You have four ways of accessing a specific item in a vector:

  • Using the [] operator
  • Using the member function at(...)
  • Using an iterator in combination with a given offset
  • Using std::for_each from the algorithm header of the standard C++ library. This is another way which I can recommend (it uses internally an iterator). You can read more about it for example here.

In the following examples I will be using the following vector as a lab rat and explaining the first three methods:

static const int arr[] = {1, 2, 3, 4};
std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0]));

This creates a vector as seen below:

1 2 3 4

First let's look at the [] way of doing things. It works in pretty much the same way as you expect when working with a normal array. You give an index and possibly you access the item you want. I say possibly because the [] operator doesn't check whether the vector actually has that many items. This leads to a silent invalid memory access. Example:

v[10] = 9;

This may or may not lead to an instant crash. Worst case is of course is if it doesn't and you actually get what seems to be a valid value. Similar to arrays this may lead to wasted time in trying to find the reason why for example 1000 lines of code later you get a value of 100 instead of 234, which is somewhat connected to that very location where you retrieve an item from you vector.

A much better way is to use at(...). This will automatically check for out of bounds behaviour and break throwing an std::out_of_range. So in the case when we have

v.at(10) = 9;

We will get:

terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 4)

The third way is similar to the [] operator in the sense you can screw things up. A vector just like an array is a sequence of continuous memory blocks containing data of the same type. This means that you can use your starting address by assigning it to an iterator and then just add an offset to this iterator. The offset simply stands for how many items after the first item you want to traverse:

std::vector<int>::iterator it = v.begin(); // First element of your vector
*(it+0) = 9;  // offest = 0 basically means accessing v.begin()
// Now we have 9 2 3 4 instead of 1 2 3 4
*(it+1) = -1; // offset = 1 means first item of v plus an additional one
// Now we have 9 -1 3 4 instead of 9 2 3 4
// ...

As you can see we can also do

*(it+10) = 9;

which is again an invalid memory access. This is basically the same as using at(0 + offset) but without the out of bounds error checking.

I would advice using at(...) whenever possible not only because it's more readable compared to the iterator access but because of the error checking for invalid index that I have mentioned above for both the iterator with offset combination and the [] operator.

How to clear or stop timeInterval in angularjs?

When you want to create interval store promise to variable:

var p = $interval(function() { ... },1000);

And when you want to stop / clear the interval simply use:

$interval.cancel(p);

Converting double to integer in Java

For the datatype Double to int, you can use the following:

Double double = 5.00;

int integer = double.intValue();

How to calculate date difference in JavaScript?

this should work just fine if you just need to show what time left, since JavaScript uses frames for its time you'll have get your End Time - The Time RN after that we can divide it by 1000 since apparently 1000 frames = 1 seconds, after that you can use the basic math of time, but there's still a problem to this code, since the calculation is static, it can't compensate for the different day total in a year (360/365/366), the bunch of IF after the calculation is to make it null if the time is lower than 0, hope this helps even though it's not exactly what you're asking :)

var now = new Date();
var end = new Date("End Time");
var total = (end - now) ;
var totalD =  Math.abs(Math.floor(total/1000));

var years = Math.floor(totalD / (365*60*60*24));
var months = Math.floor((totalD - years*365*60*60*24) / (30*60*60*24));
var days = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24)/ (60*60*24));
var hours = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24)/ (60*60));
var minutes = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60)/ (60));
var seconds = Math.floor(totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60 - minutes*60);

var Y = years < 1 ? "" : years + " Years ";
var M = months < 1 ? "" : months + " Months ";
var D = days < 1 ? "" : days + " Days ";
var H = hours < 1 ? "" : hours + " Hours ";
var I = minutes < 1 ? "" : minutes + " Minutes ";
var S = seconds < 1 ? "" : seconds + " Seconds ";
var A = years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? "Sending" : " Remaining";

document.getElementById('txt').innerHTML = Y + M + D + H + I + S + A;

Datatables: Cannot read property 'mData' of undefined

In my case, and using ASP.NET GridView, UpdatePanel and with DropDownList (with Chosen plugin where I reset value to zero using a Javascript line), I got this error and tried everything with no hope for days. The problem was that the code of my dropdown in code behind was as follows and when I select a value twice to apply its action to selected grid rows I get that error. I thought for days it's a Javascript issue (again, in my case) and finally the fix was giving zero for the drowpdown value with the update process:

  private void ddlTasks_SelectedIndexChanged(object sender, System.EventArgs e)
  {
     if (ddlTasks.SelectedValue != 0) {
        ChangeStatus(ddlTasks.SelectedValue);
        ddlTasks.SelectedValue = "0"; //// **This fixed my issue**
     }

     dvItemsGrid.DataSource = CreateDatasource();
     dvItemsGrid.DataBind();
     dvItemsGrid.UseAccessibleHeader = true;
     dvItemsGrid.HeaderRow.TableSection = TableRowSection.TableHeader;

  }

This was my fault:

     $('#<%= DropDownList.ClientID%>').val('0').trigger("chosen:updated").chosen();

How can I put strings in an array, split by new line?

An alternative to Davids answer which is faster (way faster) is to use str_replace and explode.

$arrayOfLines = explode("\n",
                    str_replace(["\r\n","\n\r","\r"],"\n",$str)
            );

What's happening is:
Since line breaks can come in different forms, I str_replace \r\n, \n\r, and \r with \n instead (and original \n are preserved).
Then explode on \n and you have all the lines in an array.

I did a benchmark on the src of this page and split the lines 1000 times in a for loop and:
preg_replace took an avg of 11 seconds
str_replace & explode took an avg of about 1 second

More detail and bencmark info on my forum

jQuery loop over JSON result from AJAX Success?

Try jQuery.map function, works pretty well with maps.

_x000D_
_x000D_
var mapArray = {_x000D_
  "lastName": "Last Name cannot be null!",_x000D_
  "email": "Email cannot be null!",_x000D_
  "firstName": "First Name cannot be null!"_x000D_
};_x000D_
_x000D_
$.map(mapArray, function(val, key) {_x000D_
  alert("Value is :" + val);_x000D_
  alert("key is :" + key);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Is it still valid to use IE=edge,chrome=1?

It's still valid to use IE=edge,chrome=1.

But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.

I use the following for correctness nowadays

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

Box shadow for bottom side only

Try using online generator css3.me Change the value and get the code, pretty simple.

Populating spinner directly in the layout xml

Define this in your String.xml file and name the array what you want, such as "Weight"

<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>

and this code in your layout.xml

<Spinner 
        android:id="@+id/fromspin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:entries="@array/Weight"
 />

In your java file, getActivity is used in fragment; if you write that code in activity, then remove getActivity.

a = (Spinner) findViewById(R.id.fromspin);

 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
                R.array.weight, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        a.setAdapter(adapter);
        a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
                    if (!b.getText().toString().isEmpty()) {
                        float value1 = Float.parseFloat(b.getText().toString());
                        float kg = value1;
                        c.setText(Float.toString(kg));
                        float gram = value1 * 1000;
                        d.setText(Float.toString(gram));
                        float carat = value1 * 5000;
                        e.setText(Float.toString(carat));
                        float ton = value1 / 908;
                        f.setText(Float.toString(ton));
                    }

                }



            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
        // Inflate the layout for this fragment
        return v;
    }

docker unauthorized: authentication required - upon push with successful login

OK! never mind; I found the solution. with 403 Suspected that the HTTP is not going to the right URL.

Change the file which has the login credentials stored the ~/.docker/config.json from the default generated of

{
        "auths": {
                "docker.io": {
                        "auth": "XXXXXXXXXXXXX",
                        "email": "[email protected]"
                }
        }
}

to - Note the change from docker.io -> index.docker.io/v1. That is the change.

{
        "auths": {
                "https://index.docker.io/v1/": {
                        "auth": "XXXXXXXXXXXXX",
                        "email": "[email protected]"
                }
        }
}

Hope that helps.

Note that the auth field should be 'username:password" base64 encoded. for example: "username:password" base64 encoded is "dXNlcm5hbWU6cGFzc3dvcmQ="

so your file would contain:

"auth": "dXNlcm5hbWU6cGFzc3dvcmQ="

Algorithm to find Largest prime factor of a number

It seems to me that step #2 of the algorithm given isn't going to be all that efficient an approach. You have no reasonable expectation that it is prime.

Also, the previous answer suggesting the Sieve of Eratosthenes is utterly wrong. I just wrote two programs to factor 123456789. One was based on the Sieve, one was based on the following:

1)  Test = 2 
2)  Current = Number to test 
3)  If Current Mod Test = 0 then  
3a)     Current = Current Div Test 
3b)     Largest = Test
3c)     Goto 3. 
4)  Inc(Test) 
5)  If Current < Test goto 4
6)  Return Largest

This version was 90x faster than the Sieve.

The thing is, on modern processors the type of operation matters far less than the number of operations, not to mention that the algorithm above can run in cache, the Sieve can't. The Sieve uses a lot of operations striking out all the composite numbers.

Note, also, that my dividing out factors as they are identified reduces the space that must be tested.

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

Something like

select *
  from foo
 where regexp_like( col1, '[^[:alpha:]]' ) ;

should work

SQL> create table foo( col1 varchar2(100) );

Table created.

SQL> insert into foo values( 'abc' );

1 row created.

SQL> insert into foo values( 'abc123' );

1 row created.

SQL> insert into foo values( 'def' );

1 row created.

SQL> select *
  2    from foo
  3   where regexp_like( col1, '[^[:alpha:]]' ) ;

COL1
--------------------------------------------------------------------------------
abc123

Check if element exists in jQuery

How do I check if an element exists

if ($("#mydiv").length){  }

If it is 0, it will evaluate to false, anything more than that true.

There is no need for a greater than, less than comparison.

How do I remove background-image in css?

div#a {
  background-image: url('../images/spacer.png');
  background-image: none !important;
}

I use a transparent spacer image in addition to the rule to remove the background image because IE6 seems to ignore the background-image: none even though it is marked !important.

HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

How to specify preference of library path?

As an alternative, you can use the environment variables LIBRARY_PATH and CPLUS_INCLUDE_PATH, which respectively indicate where to look for libraries and where to look for headers (CPATH will also do the job), without specifying the -L and -I options.

Edit: CPATH includes header with -I and CPLUS_INCLUDE_PATH with -isystem.

Best way to parse command-line parameters?

I based my approach on the top answer (from dave4420), and tried to improve it by making it more general-purpose.

It returns a Map[String,String] of all command line parameters You can query this for the specific parameters you want (eg using .contains) or convert the values into the types you want (eg using toInt).

def argsToOptionMap(args:Array[String]):Map[String,String]= {
  def nextOption(
      argList:List[String], 
      map:Map[String, String]
    ) : Map[String, String] = {
    val pattern       = "--(\\w+)".r // Selects Arg from --Arg
    val patternSwitch = "-(\\w+)".r  // Selects Arg from -Arg
    argList match {
      case Nil => map
      case pattern(opt)       :: value  :: tail => nextOption( tail, map ++ Map(opt->value) )
      case patternSwitch(opt) :: tail => nextOption( tail, map ++ Map(opt->null) )
      case string             :: Nil  => map ++ Map(string->null)
      case option             :: tail => {
        println("Unknown option:"+option) 
        sys.exit(1)
      }
    }
  }
  nextOption(args.toList,Map())
}

Example:

val args=Array("--testing1","testing1","-a","-b","--c","d","test2")
argsToOptionMap( args  )

Gives:

res0: Map[String,String] = Map(testing1 -> testing1, a -> null, b -> null, c -> d, test2 -> null)

Replacing blank values (white space) with NaN in pandas

This is not an elegant solution, but what does seem to work is saving to XLSX and then importing it back. The other solutions on this page did not work for me, unsure why.

data.to_excel(filepath, index=False)
data = pd.read_excel(filepath)

How to fire an event on class change using jQuery?

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:

$someElement.on('event', function() {
    $('#myDiv').addClass('submission-ok').trigger('classChange');
});

// in another js file, far, far away
$('#myDiv').on('classChange', function() {
     // do stuff
});

UPDATE

This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver:

_x000D_
_x000D_
var $div = $("#foo");_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  mutations.forEach(function(mutation) {_x000D_
    if (mutation.attributeName === "class") {_x000D_
      var attributeValue = $(mutation.target).prop(mutation.attributeName);_x000D_
      console.log("Class attribute changed to:", attributeValue);_x000D_
    }_x000D_
  });_x000D_
});_x000D_
observer.observe($div[0], {_x000D_
  attributes: true_x000D_
});_x000D_
_x000D_
$div.addClass('red');
_x000D_
.red { color: #C00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo" class="bar">#foo.bar</div>
_x000D_
_x000D_
_x000D_

Be aware that the MutationObserver is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.

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

You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

Set up DNS based URL forwarding in Amazon Route53

Update

While my original answer below is still valid and might be helpful to understand the cause for DNS based URL forwarding not being available via Amazon Route 53 out of the box, I highly recommend checking out Vivek M. Chawla's utterly smart indirect solution via the meanwhile introduced Amazon S3 Support for Website Redirects and achieving a self contained server less and thus free solution within AWS only like so.

  • Implementing an automated solution to generate such redirects is left as an exercise for the reader, but please pay tribute to Vivek's epic answer by publishing your solution ;)

Original Answer

Nettica must be running a custom redirection solution for this, here is the problem:

You could create a CNAME alias like aws.example.com for myaccount.signin.aws.amazon.com, however, DNS provides no official support for aliasing a subdirectory like console in this example.

  • It's a pity that AWS doesn't appear to simply do this by default when hitting https://myaccount.signin.aws.amazon.com/ (I just tried), because it would solve you problem right away and make a lot of sense in the first place; besides, it should be pretty easy to configure on their end.

For that reason a few DNS providers have apparently implemented a custom solution to allow redirects to subdirectories; I venture the guess that they are basically facilitating a CNAME alias for a domain of their own and are redirecting again from there to the final destination via an immediate HTTP 3xx Redirection.

So to achieve the same result, you'd need to have a HTTP service running performing these redirects, which is not the simple solution one would hope for of course. Maybe/Hopefully someone can come up with a smarter approach still though.

How to add click event to a iframe with JQuery

I was trying to find a better answer that was more standalone, so I started to think about how JQuery does events and custom events. Since click (from JQuery) is just any event, I thought that all I had to do was trigger the event given that the iframe's content has been clicked on. Thus, this was my solution

$(document).ready(function () {
    $("iframe").each(function () {
        //Using closures to capture each one
        var iframe = $(this);
        iframe.on("load", function () { //Make sure it is fully loaded
            iframe.contents().click(function (event) {
                iframe.trigger("click");
            });
        });

        iframe.click(function () {
            //Handle what you need it to do
        });
    });
});

Javascript Regular Expression Remove Spaces

In production and works across line breaks

This is used in several apps to clean user-generated content removing extra spacing/returns etc but retains the meaning of spaces.

text.replace(/[\n\r\s\t]+/g, ' ')

Syntax error near unexpected token 'fi'

"Then" is a command in bash, thus it needs a ";" or a newline before it.

#!/bin/bash
echo "start\n"
for f in *.jpg
do
  fname=$(basename "$f")
  echo "fname is $fname\n"
  fname="${filename%.*}"
  echo "fname is $fname\n"
  if [$[fname%2] -eq 1 ]
  then
    echo "removing $fname\n"
    rm $f
  fi
done

FileSystemWatcher Changed event is raised twice

if you register to the OnChanged event, then by deleting the monitored file before changing it might work, as long as you only need to monitor the OnChange event..

ssh : Permission denied (publickey,gssapi-with-mic)

Maybe you should assign the public key to the authorized_keys, the simple way to do this is using ssh-copy-id -i your-pub-key-file user@dest.

The opposite of Intersect()

I think you might be looking for Except:

The Except operator produces the set difference between two sequences. It will only return elements in the first sequence that don't appear in the second. You can optionally provide your own equality comparison function.

Check out this link, this link, or Google, for more information.

ORA-01652 Unable to extend temp segment by in tablespace

Create a new datafile by running the following command:

alter tablespace TABLE_SPACE_NAME add datafile 'D:\oracle\Oradata\TEMP04.dbf'            
   size 2000M autoextend on;

Switch statement for string matching in JavaScript

You can't do it in a switch unless you're doing full string matching; that's doing substring matching. (This isn't quite true, as Sean points out in the comments. See note at the end.)

If you're happy that your regex at the top is stripping away everything that you don't want to compare in your match, you don't need a substring match, and could do:

switch (base_url_string) {
    case "xxx.local":
        // Blah
        break;
    case "xxx.dev.yyy.com":
        // Blah
        break;
}

...but again, that only works if that's the complete string you're matching. It would fail if base_url_string were, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.


Update: Okay, so technically you can use a switch for substring matching, but I wouldn't recommend it in most situations. Here's how (live example):

function test(str) {
    switch (true) {
      case /xyz/.test(str):
        display("• Matched 'xyz' test");
        break;
      case /test/.test(str):
        display("• Matched 'test' test");
        break;
      case /ing/.test(str):
        display("• Matched 'ing' test");
        break;
      default:
        display("• Didn't match any test");
        break;
    }
}

That works because of the way JavaScript switch statements work, in particular two key aspects: First, that the cases are considered in source text order, and second that the selector expressions (the bits after the keyword case) are expressions that are evaluated as that case is evaluated (not constants as in some other languages). So since our test expression is true, the first case expression that results in true will be the one that gets used.

Squaring all elements in a list

def square(a):
    squares = []
    for i in a:
        squares.append(i**2)
    return squares

so how would i do the square of numbers from 1-20 using the above function

How to create an array containing 1...N

Array.prototype.fill()

a = Object.keys( [].fill.call({length:7}, '' ) ).map(Number)
a.pop();
console.debug(a)

[0, 1, 2, 3, 4, 5, 6]

Use dynamic (variable) string as regex pattern in JavaScript

Much easier way: use template literals.

var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false

How to connect to a secure website using SSL in Java with a pkcs12 file?

I realise that this article may be outdated but still I would like to ask smithsv to correct his source code, it contains many mistakes, I managed to correct most of them but still don't know what kind of object x509 could be.Here is the source code as I think is should be:

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Enumeration;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

public class Connection2 {
    public void connect() {
        /*
         * This is an example to use ONLY p12 file it's not optimazed but it
         * work. The pkcs12 file where generated by OpenSSL by me. Example how
         * to load p12 file and build Trust zone from it... It outputs
         * certificates from p12 file and add good certs to TrustStore
         */
        KeyStore ks = KeyStore.getInstance( "pkcs12" );
        ks.load( new FileInputStream( cert.pfx ), "passwrd".toCharArray() );

        KeyStore jks = KeyStore.getInstance( "JKS" );
        jks.load( null );

        for( Enumeration t = ks.aliases(); t.hasMoreElements(); ) {
            String alias = (String )t.nextElement();
            System.out.println( "@:" + alias );
            if( ks.isKeyEntry( alias ) ) {
                Certificate[] a = ks.getCertificateChain( alias );
                for( int i = 0; i == 0; )
                    jks.setCertificateEntry( x509Cert.getSubjectDN().toString(), x509 );

                System.out.println( ks.getCertificateAlias( x509 ) );
                System.out.println( "ok" );
            }
        }

        System.out.println( "init Stores..." );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
        kmf.init( ks, "c1".toCharArray() );

        TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" );
        tmf.init( jks );

        SSLContext ctx = SSLContext.getInstance( "TLS" );
        ctx.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null );
    }
}

Is it possible to preview stash contents in git?

I use this to see all my stashes with colour diff highlighting (on Fedora 21):

git stash list | 
  awk -F: '{ print "\n\n\n\n"; print $0; print "\n\n"; 
  system("git -c color.ui=always stash show -p " $1); }' | 
  less -R

(Adapted from Git: see what's in a stash without applying stash)

How to change default format at created_at and updated_at value laravel

In laravel 6 the latest one can easily add in the "APP/user.php" model:

/**
 * The storage format of the model's date columns.
 *
 * @var string
 */
protected $dateFormat = 'U';

And in schema one can add

    $table->integer('created_at')->nullable();
    $table->integer('updated_at')->nullable();

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

How to use store and use session variables across pages?

Reasoning from the comments to this question, it appears a lack of an adjusted session.save_path causes this misbehavior of PHP’s session handler. Just specify a directory (outside your document root directory) that exists and is both readable and writeable by PHP to fix this.