Programs & Examples On #Automaton

An automaton is a mathematical object describing an abstract machine with a finite set of states and transitions between these that runs on sequences of inputs consisting of letters (or symbols) picked from an alphabet.

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

MATLAB's FOR loop is static in nature; you cannot modify the loop variable between iterations, unlike the for(initialization;condition;increment) loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.

A = 1:5;

for i = A
    A = B;
    disp(i);
end

If you want to be able to respond to changes in the data structure during iterations, a WHILE loop may be more appropriate --- you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:

n = 10;
f = n;
while n > 1
    n = n-1;
    f = f*n;
end
disp(['n! = ' num2str(f)])

Btw, the for-each loop in Java (and possibly other languages) produces unspecified behavior when the data structure is modified during iteration. If you need to modify the data structure, you should use an appropriate Iterator instance which allows the addition and removal of elements in the collection you are iterating. The good news is that MATLAB supports Java objects, so you can do something like this:

A = java.util.ArrayList();
A.add(1);
A.add(2);
A.add(3);
A.add(4);
A.add(5);

itr = A.listIterator();

while itr.hasNext()

    k = itr.next();
    disp(k);

    % modify data structure while iterating
    itr.remove();
    itr.add(k);

end

How can you determine a point is between two other points on a line segment?

how about just ensuring that the slope is the same and the point is between the others?

given points (x1, y1) and (x2, y2) ( with x2 > x1) and candidate point (a,b)

if (b-y1) / (a-x1) = (y2-y2) / (x2-x1) And x1 < a < x2

Then (a,b) must be on line between (x1,y1) and (x2, y2)

C# Reflection: How to get class reference from string?

We can use

Type.GetType()

to get class name and can also create object of it using Activator.CreateInstance(type);

using System;
using System.Reflection;

namespace MyApplication
{
    class Application
    {
        static void Main()
        {
            Type type = Type.GetType("MyApplication.Action");
            if (type == null)
            {
                throw new Exception("Type not found.");
            }
            var instance = Activator.CreateInstance(type);
            //or
            var newClass = System.Reflection.Assembly.GetAssembly(type).CreateInstance("MyApplication.Action");
        }
    }

    public class Action
    {
        public string key { get; set; }
        public string Value { get; set; }
    }
}

CSS: transition opacity on mouse-out?

I managed to find a solution using css/jQuery that I'm comfortable with. The original issue: I had to force the visibility to be shown while animating as I have elements hanging outside the area. Doing so, made large blocks of text now hang outside the content area during animation as well.

The solution was to start the main text elements with an opacity of 0 and use addClass to inject and transition to an opacity of 1. Then removeClass when clicked on again.

I'm sure there's an all jQquery way to do this. I'm just not the guy to do it. :)

So in it's most basic form...

.slideDown().addClass("load");
.slideUp().removeClass("load");

Thanks for the help everyone.

Showing empty view when ListView is empty

When you extend FragmentActivity or Activity and not ListActivity, you'll want to take a look at:

ListView.setEmptyView()

ReportViewer Client Print Control "Unable to load client print control"?

I got this working with out removing any patches. The above patch was not working too. Finally what I did was on the IIS server install the following patch and reset / restart the IIS server. This is not for report manager application. This is for any ASP.NET Web application developed in .net3.5 using VS2008 http://www.microsoft.com/downloads/details.aspx?familyid=6AE0AA19-3E6C-474C-9D57-05B2347456B1&displaylang=en

jQuery - What are differences between $(document).ready and $(window).load?

From the jQuery API Document

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.


Answer to the second question -

No, they are identical as long as you are not using jQuery in no conflict mode.

Javascript for "Add to Home Screen" on iPhone?

This is also another good Home Screen script that support iphone/ipad, Mobile Safari, Android, Blackberry touch smartphones and Playbook .

https://github.com/h5bp/mobile-boilerplate/wiki/Mobile-Bookmark-Bubble

How do you discover model attributes in Rails?

There is a rails plugin called Annotate models, that will generate your model attributes on the top of your model files here is the link:

https://github.com/ctran/annotate_models

to keep the annotation in sync, you can write a task to re-generate annotate models after each deploy.

EventListener Enter Key

Here is a version of the currently accepted answer (from @Trevor) with key instead of keyCode:

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

How to change the default charset of a MySQL table?

Change table's default charset:

ALTER TABLE etape_prospection
  CHARACTER SET utf8,
  COLLATE utf8_general_ci;

To change string column charset exceute this query:

ALTER TABLE etape_prospection
  CHANGE COLUMN etape_prosp_comment etape_prosp_comment TEXT CHARACTER SET utf8 COLLATE utf8_general_ci;

How to change credentials for SVN repository in Eclipse?

Go to c:\Documents and Settings[username]\Application Data\subversion\auth\svn.simple

and delete the hexadecimal file. Normally each file is associated with one repository

Very simple C# CSV reader

My solution handles quotes, overriding field and string separators, etc. It is short and sweet.

    public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')
    {
        bool bolQuote = false;
        StringBuilder bld = new StringBuilder();
        List<string> retAry = new List<string>();

        foreach (char c in r.ToCharArray())
            if ((c == fieldSep && !bolQuote))
            {
                retAry.Add(bld.ToString());
                bld.Clear();
            }
            else
                if (c == stringSep)
                    bolQuote = !bolQuote;
                else
                    bld.Append(c);

        return retAry.ToArray();
    }

Change remote repository credentials (authentication) on Intellij IDEA 14

For Mac users this could also be helpful:

Credentials are stored in Keychain Access.app. You can just change them there.

Finding all cycles in a directed graph

I found this page in my search and since cycles are not same as strongly connected components, I kept on searching and finally, I found an efficient algorithm which lists all (elementary) cycles of a directed graph. It is from Donald B. Johnson and the paper can be found in the following link:

http://www.cs.tufts.edu/comp/150GA/homeworks/hw1/Johnson%2075.PDF

A java implementation can be found in:

http://normalisiert.de/code/java/elementaryCycles.zip

A Mathematica demonstration of Johnson's algorithm can be found here, implementation can be downloaded from the right ("Download author code").

Note: Actually, there are many algorithms for this problem. Some of them are listed in this article:

http://dx.doi.org/10.1137/0205007

According to the article, Johnson's algorithm is the fastest one.

Difference between WebStorm and PHPStorm

There is actually a comparison of the two in the official WebStorm FAQ. However, the version history of that page shows it was last updated December 13, so I'm not sure if it's maintained.

This is an extract from the FAQs for reference:

What is WebStorm & PhpStorm?

WebStorm & PhpStorm are IDEs (Integrated Development Environment) built on top of JetBrains IntelliJ platform and narrowed for web development.

Which IDE do I need?

PhpStorm is designed to cover all needs of PHP developer including full JavaScript, CSS and HTML support. WebStorm is for hardcore JavaScript developers. It includes features PHP developer normally doesn’t need like Node.JS or JSUnit. However corresponding plugins can be installed into PhpStorm for free.

How often new vesions (sic) are going to be released?

Preliminarily, WebStorm and PhpStorm major updates will be available twice in a year. Minor (bugfix) updates are issued periodically as required.

snip

IntelliJ IDEA vs WebStorm features

IntelliJ IDEA remains JetBrains' flagship product and IntelliJ IDEA provides full JavaScript support along with all other features of WebStorm via bundled or downloadable plugins. The only thing missing is the simplified project setup.

Regular expressions inside SQL Server

In order to match a digit, you can use [0-9].

So you could use 5[0-9][0-9][0-9][0-9][0-9][0-9] and [0-9][0-9][0-9][0-9]7[0-9][0-9][0-9]. I do this a lot for zip codes.

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

On Windows 7 64-bit, I added the registry entry using the following script:

@echo off
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Description" /t REG_SZ /d "Oracle Next Generation Java Plug-In"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "GeckoVersion" /t REG_SZ /d "1.9"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Path" /t REG_SZ /d "C:\Oracle\jdev11123\jdk160_24\jre\bin\new_plugin\npjp2.dll"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "ProductName" /t REG_SZ /d "Oracle Java Plug-In"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Vendor" /t REG_SZ /d "Oracle Corp."
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Version" /t REG_SZ /d "10.3.1"

Note that you will have to change the Path.

How do you clear a slice in Go?

I was looking into this issue a bit for my own purposes; I had a slice of structs (including some pointers) and I wanted to make sure I got it right; ended up on this thread, and wanted to share my results.

To practice, I did a little go playground: https://play.golang.org/p/9i4gPx3lnY

which evals to this:

package main

import "fmt"

type Blah struct {
    babyKitten int
    kittenSays *string
}

func main() {
    meow := "meow"
    Blahs := []Blah{}
    fmt.Printf("Blahs: %v\n", Blahs)
    Blahs = append(Blahs, Blah{1, &meow})
    fmt.Printf("Blahs: %v\n", Blahs)
    Blahs = append(Blahs, Blah{2, &meow})
    fmt.Printf("Blahs: %v\n", Blahs)
    //fmt.Printf("kittenSays: %v\n", *Blahs[0].kittenSays)
    Blahs = nil
    meow2 := "nyan"
    fmt.Printf("Blahs: %v\n", Blahs)
    Blahs = append(Blahs, Blah{1, &meow2})
    fmt.Printf("Blahs: %v\n", Blahs)
    fmt.Printf("kittenSays: %v\n", *Blahs[0].kittenSays)
}

Running that code as-is will show the same memory address for both "meow" and "meow2" variables as being the same:

Blahs: []
Blahs: [{1 0x1030e0c0}]
Blahs: [{1 0x1030e0c0} {2 0x1030e0c0}]
Blahs: []
Blahs: [{1 0x1030e0f0}]
kittenSays: nyan

which I think confirms that the struct is garbage collected. Oddly enough, uncommenting the commented print line, will yield different memory addresses for the meows:

Blahs: []
Blahs: [{1 0x1030e0c0}]
Blahs: [{1 0x1030e0c0} {2 0x1030e0c0}]
kittenSays: meow
Blahs: []
Blahs: [{1 0x1030e0f8}]
kittenSays: nyan

I think this may be due to the print being deferred in some way (?), but interesting illustration of some memory mgmt behavior, and one more vote for:

[]MyStruct = nil

How to display pie chart data values of each slice in chart.js

From what I know I don't believe that Chart.JS has any functionality to help for drawing text on a pie chart. But that doesn't mean you can't do it yourself in native JavaScript. I will give you an example on how to do that, below is the code for drawing text for each segment in the pie chart:

function drawSegmentValues()
{
    for(var i=0; i<myPieChart.segments.length; i++) 
    {
        // Default properties for text (size is scaled)
        ctx.fillStyle="white";
        var textSize = canvas.width/10;
        ctx.font= textSize+"px Verdana";

        // Get needed variables
        var value = myPieChart.segments[i].value;
        var startAngle = myPieChart.segments[i].startAngle;
        var endAngle = myPieChart.segments[i].endAngle;
        var middleAngle = startAngle + ((endAngle - startAngle)/2);

        // Compute text location
        var posX = (radius/2) * Math.cos(middleAngle) + midX;
        var posY = (radius/2) * Math.sin(middleAngle) + midY;

        // Text offside to middle of text
        var w_offset = ctx.measureText(value).width/2;
        var h_offset = textSize/4;

        ctx.fillText(value, posX - w_offset, posY + h_offset);
    }
}

A Pie Chart has an array of segments stored in PieChart.segments, we can look at the startAngle and endAngle of these segments to determine the angle in between where the text would be middleAngle. Then we would move in that direction by Radius/2 to be in the middle point of the chart in radians.

In the example above some other clean-up operations are done, due to the position of text drawn in fillText() being the top right corner, we need to get some offset values to correct for that. And finally textSize is determined based on the size of the chart itself, the larger the chart the larger the text.

Fiddle Example


With some slight modification you can change the discrete number values for a dataset into the percentile numbers in a graph. To do this get the total value of the items in your dataset, call this totalValue. Then on each segment you can find the percent by doing:

Math.round(myPieChart.segments[i].value/totalValue*100)+'%';

The section here myPieChart.segments[i].value/totalValue is what calculates the percent that the segment takes up in the chart. For example if the current segment had a value of 50 and the totalValue was 200. Then the percent that the segment took up would be: 50/200 => 0.25. The rest is to make this look nice. 0.25*100 => 25, then we add a % at the end. For whole number percent tiles I rounded to the nearest integer, although can can lead to problems with accuracy. If we need more accuracy you can use .toFixed(n) to save decimal places. For example we could do this to save a single decimal place when needed:

var value = myPieChart.segments[i].value/totalValue*100;
if(Math.round(value) !== value)
    value = (myPieChart.segments[i].value/totalValue*100).toFixed(1);
value = value + '%';

Fiddle Example of percentile with decimals

Fiddle Example of percentile with integers

Round a floating-point number down to the nearest integer?

Just make round(x-0.5) this will always return the next rounded down Integer value of your Float. You can also easily round up by do round(x+0.5)

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

Bitbucket supports a REST API you can use to programmatically create Bitbucket repositories.

Documentation and cURL sample available here: https://confluence.atlassian.com/bitbucket/repository-resource-423626331.html#repositoryResource-POSTanewrepository

$ curl -X POST -v -u username:password -H "Content-Type: application/json" \
   https://api.bitbucket.org/2.0/repositories/teamsinspace/new-repository4 \
   -d '{"scm": "git", "is_private": "true", "fork_policy": "no_public_forks" }'

Under Windows, curl is available from the Git Bash shell.

Using this method you could easily create a script to import many repos from a local git server to Bitbucket.

How to convert UTF-8 byte[] to string?

Converting a byte[] to a string seems simple but any kind of encoding is likely to mess up the output string. This little function just works without any unexpected results:

private string ToString(byte[] bytes)
{
    string response = string.Empty;

    foreach (byte b in bytes)
        response += (Char)b;

    return response;
}

How to run multiple sites on one apache instance

Yes with Virtual Host you can have as many parallel programs as you want:

Open

/etc/httpd/conf/httpd.conf

Listen 81
Listen 82
Listen 83

<VirtualHost *:81>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site1/html
    ServerName site1.com
    ErrorLog logs/site1-error_log
    CustomLog logs/site1-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>

<VirtualHost *:82>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site2/html
    ServerName site2.com
    ErrorLog logs/site2-error_log
    CustomLog logs/site2-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>

<VirtualHost *:83>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site3/html
    ServerName site3.com
    ErrorLog logs/site3-error_log
    CustomLog logs/site3-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>

Restart apache

service httpd restart

You can now refer Site1 :

http://<ip-address>:81/ 
http://<ip-address>:81/cgi-bin/

Site2 :

http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/

Site3 :

http://<ip-address>:83/ 
http://<ip-address>:83/cgi-bin/

If path is not hardcoded in any script then your websites should work seamlessly.

Trim a string in C

Not the best way but it works

char* Trim(char* str)
{
    int len = strlen(str);
    char* buff = new char[len];
    int i = 0;
    memset(buff,0,len*sizeof(char));
    do{
        if(isspace(*str)) continue;
        buff[i] = *str; ++i;
    } while(*(++str) != '\0');
    return buff;
}

ORA-12170: TNS:Connect timeout occurred

It is because of conflicting SID. For example, in your Oracle12cBase\app\product\12.1.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora file, connection description for ORCL is this:

ORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

And, you are trying to connect using the connection string using same SID but different IP, username/password, like this:

sqlplus username/[email protected]:1521/orcl

To resolve this, make changes in the tnsnames.ora file:

ORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.130.52)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

How get all values in a column using PHP?

Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.


This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php

$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row['names'];  
}
// now $storeArray will have all the names.

PHP GuzzleHttp. How to make a post request with params?

Note in Guzzle V6.0+, another source of getting the following error may be incorrect use of JSON as an array:

Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.

Incorrect:

$response = $client->post('http://example.com/api', [
    'body' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'json' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode([
        'name' => 'Example name',
    ])
])

Exploitable PHP functions

There was some discussion of this on security.stackexchange.com recently

functions that can be used for arbitrary code execution

Well that reduces the scope a little - but since 'print' can be used to inject javascript (and therefore steal sessions etc) its still somewhat arbitrary.

isn't to list functions that should be blacklisted or otherwise disallowed. Rather, I'd like to have a grep-able list

That's a sensible approach.

Do consider writing your own parser though - very soon you're going to find a grep based approach getting out of control (awk would be a bit better). Pretty soon you're also going to start wishing you'd implemented a whitelist too!

In addition to the obvious ones, I'd recommend flagging up anything which does an include with an argument of anything other than a string literal. Watch out for __autoload() too.

jQuery UI - Draggable is not a function?

  1. Install jquery-ui-dist

    use npm

    npm install --save jquery-ui-dist

    or yarn

    yarn add jquery-ui-dist

  2. Import it inside your app code

    import 'jquery-ui-dist/jquery-ui';

    or

    require('jquery-ui-dist/jquery-ui');

Conveniently map between enum and int / String

I needed something different because I wanted to use a generic approach. I'm reading the enum to and from byte arrays. This is where I come up with:

public interface EnumConverter {
    public Number convert();
}



public class ByteArrayConverter {
@SuppressWarnings("unchecked")
public static Enum<?> convertToEnum(byte[] values, Class<?> fieldType, NumberSystem numberSystem) throws InvalidDataException {
    if (values == null || values.length == 0) {
        final String message = "The values parameter must contain the value";
        throw new IllegalArgumentException(message);
    }

    if (!dtoFieldType.isEnum()) {
        final String message = "dtoFieldType must be an Enum.";
        throw new IllegalArgumentException(message);
    }

    if (!EnumConverter.class.isAssignableFrom(fieldType)) {
        final String message = "fieldType must implement the EnumConverter interface.";
        throw new IllegalArgumentException(message);
    }

    Enum<?> result = null;
    Integer enumValue = (Integer) convertToType(values, Integer.class, numberSystem); // Our enum's use Integer or Byte for the value field.

    for (Object enumConstant : fieldType.getEnumConstants()) {
        Number ev = ((EnumConverter) enumConstant).convert();

        if (enumValue.equals(ev)) {
            result = (Enum<?>) enumConstant;
            break;
        }
    }

    if (result == null) {
        throw new EnumConstantNotPresentException((Class<? extends Enum>) fieldType, enumValue.toString());
    }

    return result;
}

public static byte[] convertEnumToBytes(Enum<?> value, int requiredLength, NumberSystem numberSystem) throws InvalidDataException {
    if (!(value instanceof EnumConverter)) {
        final String message = "dtoFieldType must implement the EnumConverter interface.";
        throw new IllegalArgumentException(message);
    }

    Number enumValue = ((EnumConverter) value).convert();
    byte[] result = convertToBytes(enumValue, requiredLength, numberSystem);
    return result;
}

public static Object convertToType(byte[] values, Class<?> type, NumberSystem numberSystem) throws InvalidDataException {
    // some logic to convert the byte array supplied by the values param to an Object.
}

public static byte[] convertToBytes(Object value, int requiredLength, NumberSystem numberSystem) throws InvalidDataException {
    // some logic to convert the Object supplied by the'value' param to a byte array.
}
}

Example of enum's:

public enum EnumIntegerMock implements EnumConverter {
    VALUE0(0), VALUE1(1), VALUE2(2);

    private final int value;

    private EnumIntegerMock(int value) {
        this.value = value;
    }

public Integer convert() {
    return value;
}

}

public enum EnumByteMock implements EnumConverter {
    VALUE0(0), VALUE1(1), VALUE2(2);

    private final byte value;

    private EnumByteMock(int value) {
        this.value = (byte) value;
    }

    public Byte convert() {
        return value;
    }
}

How to encode a string in JavaScript for displaying in HTML?

If you want to use a library rather than doing it yourself:

The most commonly used way is using jQuery for this purpose:

var safestring = $('<div>').text(unsafestring).html();

If you want to to encode all the HTML entities you will have to use a library or write it yourself.

You can use a more compact library than jQuery, like HTML Encoder and Decode

Get current domain

Everybody is using the parse_url function, but sometimes user may pass the argumet in different format.

So as to fix that, I have created the function. Check this out:

function fixDomainName($url='')
{
    $strToLower = strtolower(trim($url));
    $httpPregReplace = preg_replace('/^http:\/\//i', '', $strToLower);
    $httpsPregReplace = preg_replace('/^https:\/\//i', '', $httpPregReplace);
    $wwwPregReplace = preg_replace('/^www\./i', '', $httpsPregReplace);
    $explodeToArray = explode('/', $wwwPregReplace);
    $finalDomainName = trim($explodeToArray[0]);
    return $finalDomainName;
}

Just pass the URL and get the domain.

For example,

echo fixDomainName('https://stackoverflow.com');

will return the result will be

stackoverflow.com

And in some situation:

echo fixDomainName('stackoverflow.com/questions/id/slug');

And it will also return stackoverflow.com.

HttpClient not supporting PostAsJsonAsync method C#

Just expanding Jeroen's answer with the tips in comments:

var content = new StringContent(
    JsonConvert.SerializeObject(user), 
    Encoding.UTF8, 
    MediaTypeNames.Application.Json);

var response = await client.PostAsync("api/AgentCollection", content);

Convert JSON String to JSON Object c#

This does't work in case of the JObject this works for the simple json format data. I have tried my data of the below json format data to deserialize in the type but didn't get the response.

For this Json

{
  "Customer": {
    "id": "Shell",
    "Installations": [
      {
        "id": "Shell.Bangalore",
        "Stations": [
          {
            "id": "Shell.Bangalore.BTM",
            "Pumps": [
              {
                "id": "Shell.Bangalore.BTM.pump1"
              },
              {
                "id": "Shell.Bangalore.BTM.pump2"
              },
              {
                "id": "Shell.Bangalore.BTM.pump3"
              }
            ]
          },
          {
            "id": "Shell.Bangalore.Madiwala",
            "Pumps": [
              {
                "id": "Shell.Bangalore.Madiwala.pump4"
              },
              {
                "id": "Shell.Bangalore.Madiwala.pump5"
              }
            ]
          }
        ]
      }
    ]
  }
}

How to parse a CSV file using PHP

Handy one liner to parse a CSV file into an array

$csv = array_map('str_getcsv', file('data.csv'));

How to change the status bar background color and text color on iOS 7?

You can set background color for status bar during application launch or during viewDidLoad of your view controller.

extension UIApplication {

    var statusBarView: UIView? {
        return value(forKey: "statusBar") as? UIView
    }

}

// Set upon application launch, if you've application based status bar
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
        return true
    }
}


or 
// Set it from your view controller if you've view controller based statusbar
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
    }

}



Here is result:

enter image description here


Here is Apple Guidelines/Instruction about status bar change. Only Dark & light (while & black) are allowed in status bar.

Here is - How to change status bar style:

If you want to set status bar style, application level then set UIViewControllerBasedStatusBarAppearance to NO in your `.plist' file.

if you wan to set status bar style, at view controller level then follow these steps:

  1. Set the UIViewControllerBasedStatusBarAppearance to YES in the .plist file, if you need to set status bar style at UIViewController level only.
  2. In the viewDidLoad add function - setNeedsStatusBarAppearanceUpdate

  3. override preferredStatusBarStyle in your view controller.

-

override func viewDidLoad() {
    super.viewDidLoad()
    self.setNeedsStatusBarAppearanceUpdate()
}

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

Batch file to map a drive when the folder name contains spaces

I just created some directories, shared them and mapped using:

net use y: "\\mycomputername\folder with spaces"

So this solution gets "works on my machine" certificate. What error code do you get?

How to embed HTML into IPython output?

Related: While constructing a class, def _repr_html_(self): ... can be used to create a custom HTML representation of its instances:

class Foo:
    def _repr_html_(self):
        return "Hello <b>World</b>!"

o = Foo()
o

will render as:

Hello World!

For more info refer to IPython's docs.

An advanced example:

from html import escape # Python 3 only :-)

class Todo:
    def __init__(self):
        self.items = []

    def add(self, text, completed):
        self.items.append({'text': text, 'completed': completed})

    def _repr_html_(self):
        return "<ol>{}</ol>".format("".join("<li>{} {}</li>".format(
            "?" if item['completed'] else "?",
            escape(item['text'])
        ) for item in self.items))

my_todo = Todo()
my_todo.add("Buy milk", False)
my_todo.add("Do homework", False)
my_todo.add("Play video games", True)

my_todo

Will render:

  1. ? Buy milk
  2. ? Do homework
  3. ? Play video games

Finding partial text in range, return an index

You can use "wildcards" with MATCH so assuming "ASDFGHJK" in H1 as per Peter's reply you can use this regular formula

=INDEX(G:G,MATCH("*"&H1&"*",G:G,0)+3)

MATCH can only reference a single column or row so if you want to search 6 columns you either have to set up a formula with 6 MATCH functions or change to another approach - try this "array formula", assuming search data in A2:G100

=INDIRECT("R"&REPLACE(TEXT(MIN(IF(ISNUMBER(SEARCH(H1,A2:G100)),(ROW(A2:G100)+3)*1000+COLUMN(A2:G100))),"000000"),4,0,"C"),FALSE)

confirmed with Ctrl-Shift-Enter

Box shadow in IE7 and IE8

use this for fixing issue with shadow box

filter: progid:DXImageTransform.Microsoft.dropShadow (OffX='2', OffY='2', Color='#F13434', Positive='true');

How to determine if string contains specific substring within the first X characters

Or if you need to set the value of found:

found = Value1.StartsWith("abc")

Edit: Given your edit, I would do something like:

found = Value1.Substring(0, 5).Contains("abc")

Vim for Windows - What do I type to save and exit from a file?

:q! will force an unconditional no-save exit

Iterating each character in a string using Python

Well you can also do something interesting like this and do your job by using for loop

#suppose you have variable name
name = "Mr.Suryaa"
for index in range ( len ( name ) ):
    print ( name[index] ) #just like c and c++ 

Answer is

M r . S u r y a a

However since range() create a list of the values which is sequence thus you can directly use the name

for e in name:
    print(e)

This also produces the same result and also looks better and works with any sequence like list, tuple, and dictionary.

We have used tow Built in Functions ( BIFs in Python Community )

1) range() - range() BIF is used to create indexes Example

for i in range ( 5 ) :
can produce 0 , 1 , 2 , 3 , 4

2) len() - len() BIF is used to find out the length of given string

javascript password generator

I would probably use something like this:

function generatePassword() {
    var length = 8,
        charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
        retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }
    return retVal;
}

That can then be extended to have the length and charset passed by a parameter.

Format date and Subtract days using Moment.js

In angularjs moment="^1.3.0"

moment('15-01-1979', 'DD-MM-YYYY').subtract(1,'days').format(); //14-01-1979
or
moment('15-01-1979', 'DD-MM-YYYY').add(1,'days').format(); //16-01-1979
``



Search in lists of lists by given index

What about:

list =[ ['a','b'], ['a','c'], ['b','d'] ]
search = 'b'

filter(lambda x:x[1]==search,list)

This will return each list in the list of lists with the second element being equal to search.

How to wrap text in textview in Android

Just was working on a TextView inside a layout inside a RecyclerView. I had text getting cut off, ex, for Read this message, I saw: Read this. I tried setting android:maxLines="2" on the TextView, but nothing changed. However, android:lines="2" resulted in Read this on first line and message on the 2nd.

Convert comma separated string to array in PL/SQL

here is another easier option

select to_number(column_value) as IDs from xmltable('1,2,3,4,5');

Any difference between await Promise.all() and multiple await?

Generally, using Promise.all() runs requests "async" in parallel. Using await can run in parallel OR be "sync" blocking.

test1 and test2 functions below show how await can run async or sync.

test3 shows Promise.all() that is async.

jsfiddle with timed results - open browser console to see test results

Sync behavior. Does NOT run in parallel, takes ~1800ms:

const test1 = async () => {
  const delay1 = await Promise.delay(600); //runs 1st
  const delay2 = await Promise.delay(600); //waits 600 for delay1 to run
  const delay3 = await Promise.delay(600); //waits 600 more for delay2 to run
};

Async behavior. Runs in paralel, takes ~600ms:

const test2 = async () => {
  const delay1 = Promise.delay(600);
  const delay2 = Promise.delay(600);
  const delay3 = Promise.delay(600);
  const data1 = await delay1;
  const data2 = await delay2;
  const data3 = await delay3; //runs all delays simultaneously
}

Async behavior. Runs in parallel, takes ~600ms:

const test3 = async () => {
  await Promise.all([
  Promise.delay(600), 
  Promise.delay(600), 
  Promise.delay(600)]); //runs all delays simultaneously
};

TLDR; If you are using Promise.all() it will also "fast-fail" - stop running at the time of the first failure of any of the included functions.

How to convert an object to a byte array in C#

This worked for me:

byte[] bfoo = (byte[])foo;

foo is an Object that I'm 100% certain that is a byte array.

How to access the local Django webserver from outside world

I had to add this line to settings.py in order to make it work (otherwise it showed an error when accessed from another computer)

ALLOWED_HOSTS = ['*']

then ran the server with:

python manage.py runserver 0.0.0.0:9595

Also ensure that the firewall allows connections to that port

How to create a POJO?

import java.io.Serializable;

public class Course implements Serializable {

    protected int courseId;
    protected String courseName;
    protected String courseType;

    public Course() {
        courseName = new String();
        courseType = new String();
    }

    public Course(String courseName, String courseType) {
        this.courseName = courseName;
        this.courseType = courseType;
    }

    public Course(int courseId, String courseName, String courseType) {
        this.courseId = courseId;
        this.courseName = courseName;
        this.courseType = courseType;
    }

    public int getCourseId() {
        return courseId;
    }

    public void setCourseId(int courseId) {
        this.courseId = courseId;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public String getCourseType() {
        return courseType;
    }

    public void setCourseType(String courseType) {
        this.courseType = courseType;
    }

    @Override
    public int hashCode() {
        return courseId;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj != null || obj instanceof Course) {
            Course c = (Course) obj;
            if (courseId == c.courseId && courseName.equals(c.courseName)
                    && courseType.equals(c.courseType))
                return true;
        }
        return false;
    }

    @Override
    public String toString() {
        return "Course[" + courseId + "," + courseName + "," + courseType + "]";
    }
}

Type safety: Unchecked cast

What did I do wrong? How do I resolve the issue?

Here :

Map<String,String> someMap = (Map<String,String>)getApplicationContext().getBean("someMap");

You use a legacy method that we generally don't want to use since that returns Object:

Object getBean(String name) throws BeansException;

The method to favor to get (for singleton) / create (for prototype) a bean from a bean factory is :

<T> T getBean(String name, Class<T> requiredType) throws BeansException;

Using it such as :

Map<String,String> someMap = app.getBean(Map.class,"someMap");

will compile but still with a unchecked conversion warning since all Map objects are not necessarily Map<String, String> objects.

But <T> T getBean(String name, Class<T> requiredType) throws BeansException; is not enough in bean generic classes such as generic collections since that requires to specify more than one class as parameter : the collection type and its generic type(s).

In this kind of scenario and in general, a better approach is not to use directly BeanFactory methods but let the framework to inject the bean.

The bean declaration :

@Configuration
public class MyConfiguration{

    @Bean
    public Map<String, String> someMap() {
        Map<String, String> someMap = new HashMap();
        someMap.put("some_key", "some value");
        someMap.put("some_key_2", "some value");
        return someMap;
    }
}

The bean injection :

@Autowired
@Qualifier("someMap")
Map<String, String> someMap;

How to get a list of installed Jenkins plugins with name and version pair

Behe's answer with sorting plugins did not work on my Jenkins machine. I received the error java.lang.UnsupportedOperationException due to trying to sort an immutable collection i.e. Jenkins.instance.pluginManager.plugins. Simple fix for the code:

List<String> jenkinsPlugins = new ArrayList<String>(Jenkins.instance.pluginManager.plugins);
jenkinsPlugins.sort { it.displayName }
              .each { plugin ->
                   println ("${plugin.shortName}:${plugin.version}")
              }

Use the http://<jenkins-url>/script URL to run the code.

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

On Linux, add this to the end of your .bashrc, .profile or appropriate file for your shell:

export ANDROID_HOME=/home/youruser/whatever/adt-bundle-linux-x86_64-20140702/sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platforms-tools

Please notice that these environment variables will be available for newly created shells, not the already open.

How can you use optional parameters in C#?

Instead of default parameters, why not just construct a dictionary class from the querystring passed .. an implementation that is almost identical to the way asp.net forms work with querystrings.

i.e. Request.QueryString["a"]

This will decouple the leaf class from the factory / boilerplate code.


You also might want to check out Web Services with ASP.NET. Web services are a web api generated automatically via attributes on C# classes.

SQL Server - Return value after INSERT

This is how I use OUTPUT INSERTED, when inserting to a table that uses ID as identity column in SQL Server:

'myConn is the ADO connection, RS a recordset and ID an integer
Set RS=myConn.Execute("INSERT INTO M2_VOTELIST(PRODUCER_ID,TITLE,TIMEU) OUTPUT INSERTED.ID VALUES ('Gator','Test',GETDATE())")
ID=RS(0)

How to get info on sent PHP curl request

curl_getinfo() must be added before closing the curl handler

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info['request_header']);
curl_close($ch);

Which Radio button in the group is checked?

Yet another try - Using event lambda expressions

As form initializes a single event handler can be assigned to all controls of type RadioButton in a group box, and use .tabIndex or .tag property to identify what option is checked when it changes.

This way you can subscribe to any of the events of each radio button in one go

int priceOption = 0;
foreach (RadioButton rbtn in grp_PriceOpt.Controls.OfType<RadioButton>())
{
    rbtn.CheckedChanged += (o, e) =>
    {
        var button = (RadioButton)o;
        if (button.Checked)
        {
            priceOption = button.TabIndex;
        }
    };
}

As events are assigned to radio buttons only, no type checking of sender is implemented.

Also notice as we loop all buttons this could be a perfect moment to assign data properties, change text etc.

What are enums and why are they useful?

You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: "permanent", "temp", "apprentice"), or flags ("execute now", "defer execution").

If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.

BTW, overuse of enums might mean that your methods do too much (it's often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go.

As an example, which is better?

/** Counts number of foobangs.
 * @param type Type of foobangs to count. Can be 1=green foobangs,
 * 2=wrinkled foobangs, 3=sweet foobangs, 0=all types.
 * @return number of foobangs of type
 */
public int countFoobangs(int type)

versus

/** Types of foobangs. */
public enum FB_TYPE {
 GREEN, WRINKLED, SWEET, 
 /** special type for all types combined */
 ALL;
}

/** Counts number of foobangs.
 * @param type Type of foobangs to count
 * @return number of foobangs of type
 */
public int countFoobangs(FB_TYPE type)

A method call like:

int sweetFoobangCount = countFoobangs(3);

then becomes:

int sweetFoobangCount = countFoobangs(FB_TYPE.SWEET);

In the second example, it's immediately clear which types are allowed, docs and implementation cannot go out of sync, and the compiler can enforce this. Also, an invalid call like

int sweetFoobangCount = countFoobangs(99);

is no longer possible.

How to set a default value in react-select

To auto-select the value of in select.

enter image description here

<div className="form-group">
    <label htmlFor="contactmethod">Contact Method</label>
    <select id="contactmethod" className="form-control"  value={this.state.contactmethod || ''} onChange={this.handleChange} name="contactmethod">
    <option value='Email'>URL</option>
    <option value='Phone'>Phone</option>
    <option value="SMS">SMS</option>
    </select>
</div>

Use the value attribute in the select tag

value={this.state.contactmethod || ''}

the solution is working for me.

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

The -Wno-unused-variable switch usually does the trick. However, that is a very useful warning indeed if you care about these things in your project. It becomes annoying when GCC starts to warn you about things not in your code though.

I would recommend you keeping the warning on, but use -isystem instead of -I for include directories of third-party projects. That flag tells GCC not to warn you about the stuff you have no control over.

For example, instead of -IC:\\boost_1_52_0, say -isystem C:\\boost_1_52_0.

Hope it helps. Good Luck!

How to select the rows with maximum values in each group with dplyr?

More generally, I think you might want to get "top" of the rows that are sorted within a given group.

For the case of where a single value is max'd out, you have essentially sorted by only one column. However, it's often useful to hierarchically sort by multiple columns (for example: a date column and a time-of-day column).

# Answering the question of getting row with max "value".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in descending order by "value" column.
  arrange( desc(value) ) %>% 
  # Pick the top 1 value
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

# Answering an extension of the question of 
# getting row with the max value of the lowest "C".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in ascending order by C, and then within that by 
  # descending order by "value" column.
  arrange( C, desc(value) ) %>% 
  # Pick the one top row based on the sort
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

How to check if input date is equal to today's date?

There is a simpler solution

if (inputDate.getDate() === todayDate.getDate()) {
   // do stuff
}

like that you don't loose the time attached to inputDate if any

"Too many characters in character literal error"

A char can hold a single character only, a character literal is a single character in single quote, i.e. '&' - if you have more characters than one you want to use a string, for that you have to use double quotes:

case "&&": 

Case insensitive 'in'

str.casefold is recommended for case-insensitive string matching. @nmichaels's solution can trivially be adapted.

Use either:

if 'MICHAEL89'.casefold() in (name.casefold() for name in USERNAMES):

Or:

if 'MICHAEL89'.casefold() in map(str.casefold, USERNAMES):

As per the docs:

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

Sort a List of Object in VB.NET

try..

Dim sortedList = From entry In mylist Order By entry.name Ascending Select entry

mylist = sortedList.ToList

Multiple controllers with AngularJS in single page app

We can simply declare more than one Controller in the same module. Here's an example:

  <!DOCTYPE html>
    <html>

    <head>
       <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
       </script>
      <title> New Page </title>


    </head> 
    <body ng-app="mainApp"> <!-- if we remove ng-app the add book button [show/hide] will has no effect --> 
      <h2> Books </h2>

    <!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->
    <input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
     <div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
             Enter book name: <input type = "text" ng-model = "book.name"><br>
             Enter book category: <input type = "text" ng-model = "book.category"><br>
             Enter book price: <input type = "text" ng-model = "book.price"><br>
             Enter book author: <input type = "text" ng-model = "book.author"><br>


             You are entering book: {{book.bookDetails()}}
     </div>

    <script>
             var mainApp = angular.module("mainApp", []);

             mainApp.controller('bookController', function($scope) {
                $scope.book = {
                   name: "",
                   category: "",
                   price:"",
                   author: "",


                   bookDetails: function() {
                      var bookObject;
                      bookObject = $scope.book;
                      return "Book name: " + bookObject.name +  '\n' + "Book category: " + bookObject.category + "  \n" + "Book price: " + bookObject.price + "  \n" + "Book Author: " + bookObject.author;
                   }

                };
             });
    </script>

    <h2> Albums </h2>
    <input type = "button" value = "Add Album"ng-click="hideShow2=(hideShow2 ? false : true)"> </input>
     <div ng-app = "mainApp" ng-controller = "albumController" ng-if="hideShow2">
             Enter Album name: <input type = "text" ng-model = "album.name"><br>
             Enter Album category: <input type = "text" ng-model = "album.category"><br>
             Enter Album price: <input type = "text" ng-model = "album.price"><br>
             Enter Album singer: <input type = "text" ng-model = "album.singer"><br>


             You are entering Album: {{album.albumDetails()}}
     </div>

    <script>
             //no need to declare this again ;)
             //var mainApp = angular.module("mainApp", []);

             mainApp.controller('albumController', function($scope) {
                $scope.album = {
                   name: "",
                   category: "",
                   price:"",
                   singer: "",

                   albumDetails: function() {
                      var albumObject;
                      albumObject = $scope.album;
                      return "Album name: " + albumObject.name +  '\n' + "album category: " + albumObject.category + "\n" + "Book price: " + albumObject.price + "\n" + "Album Singer: " + albumObject.singer;
                   }
                };
             });
    </script>

    </body>
    </html>

Merge DLL into EXE?

I Found The Solution Below are the Stpes:-

  1. Download ILMerge.msi and Install it on your Machine.
  2. Open Command Prompt
  3. type cd C:\Program Files (x86)\Microsoft\ILMerge Preess Enter
  4. C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /out:NewExeName.exe SourceExeName.exe DllName.dll

For Multiple Dll :-

C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /out:NewExeName.exe SourceExeName.exe DllName1.dll DllName2.dll DllName3.dll

jQuery exclude elements with certain class in selector

use this..

$(".content_box a:not('.button')")

Running Python from Atom

The script package does exactly what you're looking for: https://atom.io/packages/script

The package's documentation also contains the key mappings, which you can easily customize.

How would you do a "not in" query with LINQ?

var secondEmails = (from item in list2
                    select new { Email = item.Email }
                   ).ToList();

var matches = from item in list1
              where !secondEmails.Contains(item.Email)
              select new {Email = item.Email};

how to zip a folder itself using java

Java 7+, commons.io

public final class ZipUtils {

    public static void zipFolder(final File folder, final File zipFile) throws IOException {
        zipFolder(folder, new FileOutputStream(zipFile));
    }

    public static void zipFolder(final File folder, final OutputStream outputStream) throws IOException {
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
            processFolder(folder, zipOutputStream, folder.getPath().length() + 1);
        }
    }

    private static void processFolder(final File folder, final ZipOutputStream zipOutputStream, final int prefixLength)
            throws IOException {
        for (final File file : folder.listFiles()) {
            if (file.isFile()) {
                final ZipEntry zipEntry = new ZipEntry(file.getPath().substring(prefixLength));
                zipOutputStream.putNextEntry(zipEntry);
                try (FileInputStream inputStream = new FileInputStream(file)) {
                    IOUtils.copy(inputStream, zipOutputStream);
                }
                zipOutputStream.closeEntry();
            } else if (file.isDirectory()) {
                processFolder(file, zipOutputStream, prefixLength);
            }
        }
    }
}

WPF Add a Border to a TextBlock

No, you need to wrap your TextBlock in a Border. Example:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />
</Border>

Of course, you can set these properties (BorderThickness, BorderBrush) through styles as well:

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />
</Border>

Calling a JavaScript function named in a variable

Definitely avoid using eval to do something like this, or you will open yourself to XSS (Cross-Site Scripting) vulnerabilities.

For example, if you were to use the eval solutions proposed here, a nefarious user could send a link to their victim that looked like this:

http://yoursite.com/foo.html?func=function(){alert('Im%20In%20Teh%20Codez');}

And their javascript, not yours, would get executed. This code could do something far worse than just pop up an alert of course; it could steal cookies, send requests to your application, etc.

So, make sure you never eval untrusted code that comes in from user input (and anything on the query string id considered user input). You could take user input as a key that will point to your function, but make sure that you don't execute anything if the string given doesn't match a key in your object. For example:

// set up the possible functions:
var myFuncs = {
  func1: function () { alert('Function 1'); },
  func2: function () { alert('Function 2'); },
  func3: function () { alert('Function 3'); },
  func4: function () { alert('Function 4'); },
  func5: function () { alert('Function 5'); }
};
// execute the one specified in the 'funcToRun' variable:
myFuncs[funcToRun]();

This will fail if the funcToRun variable doesn't point to anything in the myFuncs object, but it won't execute any code.

What does the "undefined reference to varName" in C mean?

An initial reaction to this would be to ask and ensure that the two object files are being linked together. This is done at the compile stage by compiling both files at the same time:

gcc -o programName a.c b.c

Or if you want to compile separately, it would be:

gcc -c a.c
gcc -c b.c
gcc -o programName a.o b.o

Adding custom HTTP headers using JavaScript

The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method.

Using this with "GET" request will download the resource. The trick then is to access the resource in the intended way. Ostensibly you should be able to allow the GET response to be cacheable for a short period, hence navigation to a new URL or the creation of an IMG tag with a src url should use the cached response from the previous "GET". However that is quite likely to fail especially in IE which can be a bit of a law unto itself where the cache is concerned.

Ultimately I agree with Mehrdad, use of query string is easiest and most reliable method.

Another quirky alternative is use an XHR to make a request to a URL that indicates your intent to access a resource. It could respond with a session cookie which will be carried by the subsequent request for the image or link.

How to get input text length and validate user in javascript

JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.

var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
    //red
    textBox.style.backgroundColor = "#FF0000";
}
else
{
    //green
    textBox.style.backgroundColor = "#00FF00";
}

How can I make a div not larger than its contents?

width:1px;
white-space: nowrap;

works fine for me :)

Element count of an array in C++

It seems that if you know the type of elements in the array you can also use that to your advantage with sizeof.

int numList[] = { 0, 1, 2, 3, 4 };

cout << sizeof(numList) / sizeof(int);

// => 5

How to draw circle by canvas in Android?

If you are using your own CustomView extending View class, you need to call canvas.invalidate() method which will internally call onDraw method. You can use default API for canvas to draw a circle. The x, y cordinate define the center of the circle. You can also define color and styling in paint & pass the paint object.

public class CustomView extends View {

    public CustomView(Context context,  AttributeSet attrs) {
        super(context, attrs);
        setupPaint();
    }
}

Define default paint settings and canvas (Initialise paint in constructor so that you can reuse the same object everywhere and change only specific settings wherever required)

private Paint drawPaint;

// Setup paint with color and stroke styles
private void setupPaint() {
    drawPaint = new Paint();
    drawPaint.setColor(Color.BLUE);
    drawPaint.setAntiAlias(true);
    drawPaint.setStrokeWidth(5);
    drawPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    drawPaint.setStrokeJoin(Paint.Join.ROUND);
    drawPaint.setStrokeCap(Paint.Cap.ROUND);
}

And initialise canvas object

private Canvas canvas;

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    this.canvas = canvas;
    canvas.drawCircle(xCordinate, yCordinate, RADIUS, drawPaint);
}

And finally, for every view refresh or new draw on the screen, you need to call invalidate method. Remember your entire view is redrawn, hence this is an expensive call. Make sure you do only the necessary operations in onDraw

canvas.invalidate();

For more details on canvas drawing refer https://medium.com/@mayuri.k18/android-canvas-for-drawing-and-custom-views-e1a3e90d468b

Select entries between dates in doctrine 2


    EDIT: See the other answers for better solutions

The original newbie approaches that I offered were (opt1):

$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");

And (opt2):

$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");

That was quick and easy and got the original poster going immediately.

Hence the accepted answer.

As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"

How to declare a type as nullable in TypeScript?

All fields in JavaScript (and in TypeScript) can have the value null or undefined.

You can make the field optional which is different from nullable.

interface Employee1 {
    name: string;
    salary: number;
}

var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK

// OK
class SomeEmployeeA implements Employee1 {
    public name = 'Bob';
    public salary = 40000;
}

// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
    public name: string;
}

Compare with:

interface Employee2 {
    name: string;
    salary?: number;
}

var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number

// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
    public name = 'Bob';
}

Which is the preferred way to concatenate a string in Python?

The best way of appending a string to a string variable is to use + or +=. This is because it's readable and fast. They are also just as fast, which one you choose is a matter of taste, the latter one is the most common. Here are timings with the timeit module:

a = a + b:
0.11338996887207031
a += b:
0.11040496826171875

However, those who recommend having lists and appending to them and then joining those lists, do so because appending a string to a list is presumably very fast compared to extending a string. And this can be true, in some cases. Here, for example, is one million appends of a one-character string, first to a string, then to a list:

a += b:
0.10780501365661621
a.append(b):
0.1123361587524414

OK, turns out that even when the resulting string is a million characters long, appending was still faster.

Now let's try with appending a thousand character long string a hundred thousand times:

a += b:
0.41823482513427734
a.append(b):
0.010656118392944336

The end string, therefore, ends up being about 100MB long. That was pretty slow, appending to a list was much faster. That that timing doesn't include the final a.join(). So how long would that take?

a.join(a):
0.43739795684814453

Oups. Turns out even in this case, append/join is slower.

So where does this recommendation come from? Python 2?

a += b:
0.165287017822
a.append(b):
0.0132720470428
a.join(a):
0.114929914474

Well, append/join is marginally faster there if you are using extremely long strings (which you usually aren't, what would you have a string that's 100MB in memory?)

But the real clincher is Python 2.3. Where I won't even show you the timings, because it's so slow that it hasn't finished yet. These tests suddenly take minutes. Except for the append/join, which is just as fast as under later Pythons.

Yup. String concatenation was very slow in Python back in the stone age. But on 2.4 it isn't anymore (or at least Python 2.4.7), so the recommendation to use append/join became outdated in 2008, when Python 2.3 stopped being updated, and you should have stopped using it. :-)

(Update: Turns out when I did the testing more carefully that using + and += is faster for two strings on Python 2.3 as well. The recommendation to use ''.join() must be a misunderstanding)

However, this is CPython. Other implementations may have other concerns. And this is just yet another reason why premature optimization is the root of all evil. Don't use a technique that's supposed "faster" unless you first measure it.

Therefore the "best" version to do string concatenation is to use + or +=. And if that turns out to be slow for you, which is pretty unlikely, then do something else.

So why do I use a lot of append/join in my code? Because sometimes it's actually clearer. Especially when whatever you should concatenate together should be separated by spaces or commas or newlines.

How to convert an Instant to a date format?

try Parsing and Formatting

Take an example Parsing

String input = ...;
try {
    DateTimeFormatter formatter =
                      DateTimeFormatter.ofPattern("MMM d yyyy");
    LocalDate date = LocalDate.parse(input, formatter);
    System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
    System.out.printf("%s is not parsable!%n", input);
    throw exc;      // Rethrow the exception.
}

Formatting

ZoneId leavingZone = ...;
ZonedDateTime departure = ...;

try {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
    String out = departure.format(format);
    System.out.printf("LEAVING:  %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
    System.out.printf("%s can't be formatted!%n", departure);
    throw exc;
}

The output for this example, which prints both the arrival and departure time, is as follows:

LEAVING:  Jul 20 2013  07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013  10:20 PM (Asia/Tokyo)

For more details check this page- https://docs.oracle.com/javase/tutorial/datetime/iso/format.html

How to detect internet speed in JavaScript?

The image trick is cool but in my tests it was loading before some ajax calls I wanted to be complete.

The proper solution in 2017 is to use a worker (http://caniuse.com/#feat=webworkers).

The worker will look like:

/**
 * This function performs a synchronous request
 * and returns an object contain informations about the download
 * time and size
 */
function measure(filename) {
  var xhr = new XMLHttpRequest();
  var measure = {};
  xhr.open("GET", filename + '?' + (new Date()).getTime(), false);
  measure.start = (new Date()).getTime();
  xhr.send(null);
  measure.end = (new Date()).getTime();
  measure.len = parseInt(xhr.getResponseHeader('Content-Length') || 0);
  measure.delta = measure.end - measure.start;
  return measure;
}

/**
 * Requires that we pass a base url to the worker
 * The worker will measure the download time needed to get
 * a ~0KB and a 100KB.
 * It will return a string that serializes this informations as
 * pipe separated values
 */
onmessage = function(e) {
  measure0 = measure(e.data.base_url + '/test/0.bz2');
  measure100 = measure(e.data.base_url + '/test/100K.bz2');
  postMessage(
    measure0.delta + '|' +
    measure0.len + '|' +
    measure100.delta + '|' +
    measure100.len
  );
};

The js file that will invoke the Worker:

var base_url = PORTAL_URL + '/++plone++experimental.bwtools';
if (typeof(Worker) === 'undefined') {
  return; // unsupported
}
w = new Worker(base_url + "/scripts/worker.js");
w.postMessage({
  base_url: base_url
});
w.onmessage = function(event) {
  if (event.data) {
    set_cookie(event.data);
  }
};

Code taken from a Plone package I wrote:

How can I create a carriage return in my C# string

myString += Environment.NewLine;

myString = myString + Environment.NewLine;

HashMap with multiple values under the same key

Yes and no. The solution is to build a Wrapper clas for your values that contains the 2 (3, or more) values that correspond to your key.

Remove local git tags that are no longer on the remote repository

Looks like recentish versions of Git (I'm on git v2.20) allow one to simply say

git fetch --prune --prune-tags

Much cleaner!

https://git-scm.com/docs/git-fetch#_pruning

You can also configure git to always prune tags when fetching:

git config fetch.pruneTags true

If you only want to prune tags when fetching from a specific remote, you can use the remote.<remote>.pruneTags option. For example, to always prune tags when fetching from origin but not other remotes,

git config remote.origin.pruneTags true

Detect touch press vs long press vs movement?

I was looking for a similar solution and this is what I would suggest. In the OnTouch method, record the time for MotionEvent.ACTION_DOWN event and then for MotionEvent.ACTION_UP, record the time again. This way you can set your own threshold also. After experimenting few times you will know the max time in millis it would need to record a simple touch and you can use this in move or other method as you like.

Hope this helped. Please comment if you used a different method and solved your problem.

Laravel: Validation unique on update

If i understand what you want:

'email' => 'required|email|unique:users,email_address,'. $id .''

In model update method, for exemple, should receive the $id with parameter.

Sorry my bad english.

How to build and fill pandas dataframe from for loop?

The simplest answer is what Paul H said:

d = []
for p in game.players.passing():
    d.append(
        {
            'Player': p,
            'Team': p.team,
            'Passer Rating':  p.passer_rating()
        }
    )

pd.DataFrame(d)

But if you really want to "build and fill a dataframe from a loop", (which, btw, I wouldn't recommend), here's how you'd do it.

d = pd.DataFrame()

for p in game.players.passing():
    temp = pd.DataFrame(
        {
            'Player': p,
            'Team': p.team,
            'Passer Rating': p.passer_rating()
        }
    )

    d = pd.concat([d, temp])

Convert UTC Epoch to local date

Considering, you have epoch_time available,

// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB');  // 24 hour format

Regular expression to allow spaces between words

It was my regex: @"^(?=.{3,15}$)(?:(?:\p{L}|\p{N})[._()\[\]-]?)*$"

I just added ([\w ]+) at the end of my regex before *

@"^(?=.{3,15}$)(?:(?:\p{L}|\p{N})[._()\[\]-]?)([\w ]+)*$"

Now string is allowed to have spaces.

How do relative file paths work in Eclipse?

You need "src/Hankees.txt"

Your file is in the source folder which is not counted as the working directory.\

Or you can move the file up to the root directory of your project and just use "Hankees.txt"

How to set background color of HTML element using css properties in JavaScript

$("body").css("background","green"); //jQuery

document.body.style.backgroundColor = "green"; //javascript

so many ways are there I think it is very easy and simple

Demo On Plunker

How to empty/destroy a session in rails?

add this code to your ApplicationController

def reset_session
  @_request.reset_session
end

( Dont know why no one above just mention this code as it fixed my problem ) http://apidock.com/rails/ActionController/RackDelegation/reset_session

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

Sending emails through SMTP with PHPMailer

Yes, you need OpenSSL to work correctly. My backup testing site worked, my live server didn't. Difference? Live server didn't have OpenSSL within PHP configuration.

How to make a radio button unchecked by clicking it?

Here's an example of where it is arguably appropriate to uncheck radio buttons other than by making a new selection. I have a dictionary whose entries can be selected using a variety of indices. Which index to use is selected by means of a set of radio buttons. However, there is also a "random entry" button that the user can use if he or she just wants to browse. Leaving an index in place when the entry has been selected by means of the random entry button would be misleading, so when this button is pressed, I uncheck all of the index selection radio buttons and replace the contents of the index frame with an empty page.

Swift - How to convert String to Double

You can use StringEx. It extends String with string-to-number conversions including toDouble().

extension String {
    func toDouble() -> Double?
}

It verifies the string and fails if it can't be converted to double.

Example:

import StringEx

let str = "123.45678"
if let num = str.toDouble() {
    println("Number: \(num)")
} else {
    println("Invalid string")
}

How to efficiently count the number of keys/properties of an object in JavaScript?

I try to make it available to all object like this:

Object.defineProperty(Object.prototype, "length", {
get() {
    if (!Object.keys) {
        Object.keys = function (obj) {
            var keys = [],k;
            for (k in obj) {
                if (Object.prototype.hasOwnProperty.call(obj, k)) {
                    keys.push(k);
                }
            }
            return keys;
        };
    }
    return Object.keys(this).length;
},});

console.log({"Name":"Joe","Age":26}.length) //returns 2

What's the difference between display:inline-flex and display:flex?

Using two-value display syntax instead, for clarity

The display CSS property in fact sets two things at once: the outer display type, and the inner display type. The outer display type affects how the element (which acts as a container) is displayed in its context. The inner display type affects how the children of the element (or the children of the container) are laid out.

If you use the two-value display syntax, which is only supported in some browsers like Firefox, the difference between the two is much more obvious:

  • display: block is equivalent to display: block flow
  • display: inline is equivalent to display: inline flow
  • display: flex is equivalent to display: block flex
  • display: inline-flex is equivalent to display: inline flex
  • display: grid is equivalent to display: block grid
  • display: inline-grid is equivalent to display: inline grid

Outer display type: block or inline:

An element with the outer display type of block will take up the whole width available to it, like <div> does. An element with the outer display type of inline will only take up the width that it needs, with wrapping, like <span> does.

Inner display type: flow, flex or grid:

The inner display type flow is the default inner display type when flex or grid is not specified. It is the way of laying out children elements that we are used to in a <p> for instance. flex and grid are new ways of laying out children that each deserve their own post.

Conclusion:

The difference between display: flex and display: inline-flex is the outer display type, the first's outer display type is block, and the second's outer display type is inline. Both of them have the inner display type of flex.

References:

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Of course:

curl http://example.com:11740
curl https://example.com:11740

Port 80 and 443 are just default port numbers.

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;

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

Set the charset at after you made the connection to db like

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if (!$conn->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $conn->error);
    exit();
} else {
    printf("Current character set: %s\n", $conn->character_set_name());
}

Extract string between two strings in java

I have answered this question here: https://stackoverflow.com/a/38238785/1773972

Basically use

StringUtils.substringBetween(str, "<%=", "%>");

This requirs using "Apache commons lang" library: https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4

This library has a lot of useful methods for working with string, you will really benefit from exploring this library in other areas of your java code !!!

How to set JAVA_HOME in Mac permanently?

Installing Java on macOS 11 Big Sur:

  • the easiest way is to select OpenJDK 11 (LTS), the HotSpot JVM, and macOS x64 is to get the latest release here: adoptopenjdk.net
  • Select macOS and x64 and download the JDK (about 190 MB), which will put the OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.pkg file into your ~/Downloads folder
  • Clicking on pkg file, will install into this location: /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk enter image description here
  • Almost done. After opening a terminal, the successful installation of the JDK can be confirmed like so: java --version
    • output:
openjdk 11.0.9.1 2020-11-04
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.9.1+1)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.9.1+1, mixed mode)
  • JAVA_HOME is an important environment variable and it’s important to get it right. Here is a trick that allows me to keep the environment variable current, even after a Java Update was installed. In ~/.zshrc, I set the variable like so: export JAVA_HOME=$(/usr/libexec/java_home)
  • In previous macOS versions, this was done in ~/.bash_profile. Anyway, open a new terminal and verify: echo $JAVA_HOME
    • output: /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home

TEST: Compile and Run your Java Program

  • Open a text editor, copy the code from below and save the file as HelloStackoverflow.java.
public class HelloStackoverflow {
  public static void main(String[] args){
    System.out.println("Hello Stackoverflow !");
  }//End of main
}//End of HelloStackoverflow Class
  • From a terminal set the working directory to the directory containing HelloStackoverflow.java, then type the command:
javac HelloStackoverflow.java
  • If you're lucky, nothing will happen

  • Actually, a lot happened. javac is the name of the Java compiler. It translates Java into Java Bytecode, an assembly language for the Java Virtual Machine (JVM). The Java Bytecode is stored in a file called HelloStackoverflow.class.

  • Running: type the command:

java HelloStackoverflow

# output:
# Hello Stackoverflow !

enter image description here

How to manually include external aar package using new Gradle Android Build System

Just to simplify the answer

If .aar file is locally present then include
compile project(':project_directory') in dependencies of build.gradle of your project.

If .aar file present at remote then include compile 'com.*********.sdk:project_directory:0.0.1@aar' in dependencies of build.gradle of your project.

react-native :app:installDebug FAILED

Just lock and unlock the android solved my issue then

adb reverse tcp:8081 tcp:8081

Should I use Python 32bit or Python 64bit

I had trouble running python app (running large dataframes) in 32 - got MemoryError message, while on 64 it worked fine.

html5 input for money/currency

Using javascript's Number.prototype.toLocaleString:

_x000D_
_x000D_
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'GBP' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml

 // format inital value
onBlur({target:currencyInput})

// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)


function localStringToNumber( s ){
  return Number(String(s).replace(/[^0-9.-]+/g,""))
}

function onFocus(e){
  var value = e.target.value;
  e.target.value = value ? localStringToNumber(value) : ''
}

function onBlur(e){
  var value = e.target.value

  var options = {
      maximumFractionDigits : 2,
      currency              : currency,
      style                 : "currency",
      currencyDisplay       : "symbol"
  }
  
  e.target.value = (value || value === 0) 
    ? localStringToNumber(value).toLocaleString(undefined, options)
    : ''
}
_x000D_
input{
  padding: 10px;
  font: 20px Arial;
  width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
_x000D_
_x000D_

Here's a very simple demo illustrating the above method (HTML-only)


I've made a tiny React component if anyone's interested

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

From the Official documentation,

For example, to set the background color to orange:

<meta name="theme-color" content="#db5945">

In addition, Chrome will show beautiful high-res favicons when they’re provided. Chrome for Android picks the highest res icon that you provide, and we recommend providing a 192×192px PNG file. For example:

<link rel="icon" sizes="192x192" href="nice-highres.png">

C++ sorting and keeping track of indexes

You could sort std::pair instead of just ints - first int is original data, second int is original index. Then supply a comparator that only sorts on the first int. Example:

Your problem instance: v = [5 7 8]
New problem instance: v_prime = [<5,0>, <8,1>, <7,2>]

Sort the new problem instance using a comparator like:

typedef std::pair<int,int> mypair;
bool comparator ( const mypair& l, const mypair& r)
   { return l.first < r.first; }
// forgetting the syntax here but intent is clear enough

The result of std::sort on v_prime, using that comparator, should be:

v_prime = [<5,0>, <7,2>, <8,1>]

You can peel out the indices by walking the vector, grabbing .second from each std::pair.

Are duplicate keys allowed in the definition of binary search trees?

I just want to add some more information to what @Robert Paulson answered.

Let's assume that node contains key & data. So nodes with the same key might contain different data.
(So the search must find all nodes with the same key)

  1. left <= cur < right
  1. left < cur <= right
  1. left <= cur <= right
  1. left < cur < right && cur contain sibling nodes with the same key.
  1. left < cur < right, such that no duplicate keys exist.

1 & 2. works fine if the tree does not have any rotation-related functions to prevent skewness.
But this form doesn't work with AVL tree or Red-Black tree, because rotation will break the principal.
And even if search() finds the node with the key, it must traverse down to the leaf node for the nodes with duplicate key.
Making time complexity for search = theta(logN)

3. will work well with any form of BST with rotation-related functions.
But the search will take O(n), ruining the purpose of using BST.
Say we have the tree as below, with 3) principal.

         12
       /    \
     10     20
    /  \    /
   9   11  12 
      /      \
    10       12

If we do search(12) on this tree, even tho we found 12 at the root, we must keep search both left & right child to seek for the duplicate key.
This takes O(n) time as I've told.

4. is my personal favorite. Let's say sibling means the node with the same key.
We can change above tree into below.

         12 - 12 - 12
       /    \
10 - 10     20
    /  \
   9   11

Now any search will take O(logN) because we don't have to traverse children for the duplicate key.
And this principal also works well with AVL or RB tree.

ValueError: object too deep for desired array while using convolution

You could try using scipy.ndimage.convolve it allows convolution of multidimensional images. here is the docs

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

Please note that there's a naming convention. Your lib needs to be called libexample.so .

LoadLibrary("example") will look for libexample.so.

The .so library needs to be inside the apk under the lib folder (since you are developing for Android, it needs to be under the lib/armeabi and lib/armeabi-v7a folders - why both folders ? some versions of Android look under lib/armeabi and some look under lib/armeabi-v7a ... se what works for you ).

Other things to look for :

  • make sure you compile for the correct architecture (if you compile for armeabi v5 it won't work on armeabiv7 or armeabiv7s ).

  • make sure your exported prototypes are used in the correct class (check the hello jni example. Your exposed functions need to look something like Java_mypackagename_myjavabridgeclass_myfunction).

For example the function Java_com_example_sample_hello will translate in the java class com.example.sample , function hello.

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Remove:

<facet type="android" name="Android">
    <configuration />
</facet>

in your iml file. That works for me.

https://plus.google.com/+AlexRuiz/posts/49hP3V9GSGe

Date in to UTC format Java

SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// or SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy KK:mm:ss a Z" );
sdf.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
System.out.println( sdf.format( new Date() ) );

c++ custom compare function for std::sort()

Look here: http://en.cppreference.com/w/cpp/algorithm/sort.

It says:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
  • comp - comparison function which returns ?true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b);

Also, here's an example of how you can use std::sort using a custom C++14 polymorphic lambda:

std::sort(std::begin(container), std::end(container),
          [] (const auto& lhs, const auto& rhs) {
    return lhs.first < rhs.first;
});

Need to list all triggers in SQL Server database with table name and table's schema

And what do you think about this: Very short and neat :)

SELECT OBJECT_NAME(parent_id) Table_or_ViewNM,
      name TriggerNM,
      is_instead_of_trigger,
      is_disabled
FROM sys.triggers
WHERE parent_class_desc = 'OBJECT_OR_COLUMN'
ORDER BY OBJECT_NAME(parent_id),
Name ;

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

It turns out that the solution is to stop all the related services and solve the “Another daemon is already running” issue.

The commands i used to solve the issue are as follows:

sudo /opt/lampp/lampp stop              
sudo /etc/init.d/apache2 stop    
sudo /etc/init.d/mysql stop

Or, you can also type instead:

sudo service apache2 stop
sudo service mysql stop

After that, we again start the lampp services:

sudo /opt/lampp/lampp start

Now, there must be no problems while opening:

http://localhost                  
http://localhost/phpmyadmin

How to ping multiple servers and return IP address and Hostnames using batch script?

the problem with ping is if the host is not alive often your local machine will return an answer that the pinged host is not available, thus the errorcode of ping will be 0 and your code will run in error because not recognizing the down state.

better do it this way

ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)

this way you look for a typical string ttl which is always in the well done ping result and check error on this findstr instead of irritating ping

overall this looks like this:

@echo off
SetLocal


set log=path/to/logfile.txt
set check=path/to/checkfile.txt

:start
echo. some echo date >>%log%

:check
for /f %%r in (%check%) do (call :ping %%r)
goto :eof

:ping
ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)

:error
echo. some errormessage to >>%log%
echo. some blat to mail?

:eof
echo. some good message to >>%log%

Server cannot set status after HTTP headers have been sent IIS7.5

I remember the part from this exception : "Cannot modify header information - headers already sent by" occurring in PHP. It occurred when the headers were already sent in the redirection phase and any other output was generated e.g.:

echo "hello"; header("Location:http://stackoverflow.com");

Pardon me and do correct me if I am wrong but I am still learning MS Technologies and I was trying to help.

Hide div if screen is smaller than a certain width

Is your logic not round the wrong way in that example, you have it hiding when the screen is bigger than 1024. Reverse the cases, make the none in to a block and vice versa.

Plotting multiple lines, in different colors, with pandas dataframe

You can use this code to get your desire output

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'color': ['red','red','red','blue','blue','blue'], 'x': [0,1,2,3,4,5],'y': [0,1,2,9,16,25]})
print df

  color  x   y
0   red  0   0
1   red  1   1
2   red  2   2
3  blue  3   9
4  blue  4  16
5  blue  5  25

To plot graph

a = df.iloc[[i for i in xrange(0,len(df)) if df['x'][i]==df['y'][i]]].plot(x='x',y='y',color = 'red')
df.iloc[[i for i in xrange(0,len(df)) if df['y'][i]== df['x'][i]**2]].plot(x='x',y='y',color = 'blue',ax=a)

plt.show()

Output The output result will look like this

I need to learn Web Services in Java. What are the different types in it?

If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.

How to read a text file into a string variable and strip newlines?

This is a one line, copy-pasteable solution that also closes the file object:

_ = open('data.txt', 'r'); data = _.read(); _.close()

Switching between GCC and Clang/LLVM using CMake

If the default compiler chosen by cmake is gcc and you have installed clang, you can use the easy way to compile your project with clang:

$ mkdir build && cd build
$ CXX=clang++ CC=clang cmake ..
$ make -j2

I get Access Forbidden (Error 403) when setting up new alias

Apache 2.4 virtual hosts hack

1.In http.conf specify the ports , below “Listen”

Listen 80
Listen 4000
Listen 7000
Listen 9000
  1. In httpd-vhosts.conf

    <VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"  
    ServerName hitesh_web.dev
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
    
    <Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
    Allow from all
    Require all granted
    </Directory>
    
    </VirtualHost>
    

    this is 2nd virtual host

    <VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "E:/dabkick_git/DabKickWebsite"
    ServerName  www.my_mobile.dev
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
    
    <Directory "E:/dabkick_git/DabKickWebsite">
     Allow from all
     Require all granted
     </Directory>
    </VirtualHost>
    
  2. In hosts.ics file of windows os “C:\Windows\System32\drivers\etc\host.ics”

    127.0.0.1             localhost
    127.0.0.1             hitesh_web.dev
    127.0.0.1             www.my_mobile.dev
    127.0.0.1             demo.multisite.dev
    

4.now type your “domain names” in the browser it will ping the particular folder specified in the documentRoot path

5.if you want to access those files in a particular port then replace 80 in httpd-vhosts.conf with port numbers like below and restart apache

   <VirtualHost *:4000>
ServerAdmin [email protected]
DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"
ServerName hitesh_web.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common

<Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
Allow from all
Require all granted
</Directory>

</VirtualHost>

this is the 2nd vhost

<VirtualHost *:7000>
ServerAdmin [email protected]
DocumentRoot "E:/dabkick_git/DabKickWebsite"
ServerName  www.dabkick_mobile.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common

<Directory "E:/dabkick_git/DabKickWebsite">
Allow from all
Require all granted
</Directory>
</VirtualHost>

Note: for port number given virtual hosts you have to ping in browser like “http://hitesh_web.dev:4000/” or “http://www.dabkick_mobile.dev:7000/

6.After doing all those changes you have to save the files and restart apache respectively.

PHP - Merging two arrays into one array (also Remove Duplicates)

The best solution above faces a problem when using the same associative keys, array_merge() will merge array elements together when they have the same NON-NUMBER key, so it is not suitable for the following case

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("c"=>"red","d"=>"black","e"=>"green");

If you are able output your value to the keys of your arrays instead (e.g ->pluck('name', 'id')->toArray() in Eloquent), you can use the following merge method instead

array_keys(array_merge($a1, $a2))

Basically what the code does is it utilized the behavior of array_merge() to get rid of duplicated keys and return you a new array with keys as array elements, hope it helps

Are there any style options for the HTML5 Date picker?

Currently, there is no cross browser, script-free way of styling a native date picker.

As for what's going on inside WHATWG/W3C... If this functionality does emerge, it will likely be under the CSS-UI standard or some Shadow DOM-related standard. The CSS4-UI wiki page lists a few appearance-related things that were dropped from CSS3-UI, but to be honest, there doesn't seem to be a great deal of interest in the CSS-UI module.

I think your best bet for cross browser development right now, is to implement pretty controls with JavaScript based interface, and then disable the HTML5 native UI and replace it. I think in the future, maybe there will be better native control styling, but perhaps more likely will be the ability to swap out a native control for your own Shadow DOM "widget".

It is annoying that this isn't available, and petitioning for standard support is always worthwhile. Though it does seem like jQuery UI's lead has tried and was unsuccessful.

While this is all very discouraging, it's also worth considering the advantages of the HTML5 date picker, and also why custom styles are difficult and perhaps should be avoided. On some platforms, the datepicker looks extremely different and I personally can't think of any generic way of styling the native datepicker.

SQL Server : fetching records between two dates?

try to use following query

select * 
from xxx 
where convert(date,dates) >= '2012-10-26' and convert(date,dates) <= '2012-10-27'

Create Elasticsearch curl query for not null and not empty("")

Here's the query example to check the existence of multiple fields:

{
  "query": {
    "bool": {
      "filter": [
        {
          "exists": {
            "field": "field_1"
          }
        },
        {
          "exists": {
            "field": "field_2"
          }
        },
        {
          "exists": {
            "field": "field_n"
          }
        }
      ]
    }
  }
}

How to change Status Bar text color in iOS

Here is a better solution extend Navigation controller and put in storyboard

class NVC: UINavigationController {

    override var preferredStatusBarStyle: UIStatusBarStyle {
              return .lightContent
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    self.navigationBar.isHidden = true
    self.navigationController?.navigationBar.isTranslucent = false
      
     self.navigationBar.barTintColor = UIColor.white
     setStatusBarColor(view : self.view)
    }
    

    func setStatusBarColor(view : UIView){
             if #available(iOS 13.0, *) {
                 let app = UIApplication.shared
                 let statusBarHeight: CGFloat = app.statusBarFrame.size.height
                 
                 let statusbarView = UIView()
              statusbarView.backgroundColor = UIColor.black
                 view.addSubview(statusbarView)
               
                 statusbarView.translatesAutoresizingMaskIntoConstraints = false
                 statusbarView.heightAnchor
                     .constraint(equalToConstant: statusBarHeight).isActive = true
                 statusbarView.widthAnchor
                     .constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
                 statusbarView.topAnchor
                     .constraint(equalTo: view.topAnchor).isActive = true
                 statusbarView.centerXAnchor
                     .constraint(equalTo: view.centerXAnchor).isActive = true
               
             } else {
                 let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
              statusBar?.backgroundColor = UIColor.black
             }
         }
}

status bar color will be black and text will be white

How do I create a new line in Javascript?

\n dosen't work. Use html tags

document.write("<br>");
document.write("?");

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

The problem is that the evaluation of Click() times out on your build env.. you might want to dig into what happens on Click().

Also, try adding Retrys for the Click() because occssionally the evaluations take longer time depending on network speeds, etc

Git clone without .git directory

Use

git clone --depth=1 --branch=master git://someserver/somerepo dirformynewrepo
rm -rf ./dirformynewrepo/.git
  • The depth option will make sure to copy the least bit of history possible to get that repo.
  • The branch option is optional and if not specified would get master.
  • The second line will make your directory dirformynewrepo not a Git repository any more.
  • If you're doing recursive submodule clone, the depth and branch parameter don't apply to the submodules.

Does mobile Google Chrome support browser extensions?

You can use bookmarklets (javascript code in a bookmark) - this also means they sync across devices.

I have loads - I prefix the name with zzz, so they are eazy to type in to the address bar and show in drop down predictions.

To get them to operate on a page you need to go to the page and then in the address bar type the bookmarklet name - this will cause the bookmarklet to execute in the context of the page.

edit

Just to highlight - for this to work, the bookmarklet name must be typed into the address bar while the page you want to operate in is being displayed - if you go off to select the bookmarklet in some other way the page context gets lost, and the bookmarklet operates on a new empty page.

I use zzzpocket - send to pocket. zzztwitter tweet this page zzzmail email this page zzzpressthis send this page to wordpress zzztrello send this page to trello and more...

and it works in chrome whatever platform I am currently logged on to.

SQL: How do I SELECT only the rows with a unique value on certain column?

Sorry old post I know but I had the same issue, couldn't get any of the above to work for me, however I figured it out.

This worked for me:

SELECT DISTINCT [column]As UniqueValues FROM [db].[dbo].[table]

Parameter "stratify" from method "train_test_split" (scikit Learn)

In this context, stratification means that the train_test_split method returns training and test subsets that have the same proportions of class labels as the input dataset.

default value for struct member in C

Structure is a data type. You don't give values to a data type. You give values to instances/objects of data types.
So no this is not possible in C.

Instead you can write a function which does the initialization for structure instance.

Alternatively, You could do:

struct MyStruct_s 
{
    int id;
} MyStruct_default = {3};

typedef struct MyStruct_s MyStruct;

And then always initialize your new instances as:

MyStruct mInstance = MyStruct_default;

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

How to get all elements which name starts with some string?

HTML DOM querySelectorAll() method seems apt here.

W3School Link given here

Syntax (As given in W3School)

document.querySelectorAll(CSS selectors)

So the answer.

document.querySelectorAll("[name^=q1_]")

Fiddle

Edit:

Considering FLX's suggestion adding link to MDN here

Multiple aggregate functions in HAVING clause

select CUSTOMER_CODE,nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) DEBIT,nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) CREDIT,
nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) BALANCE from TRANSACTION   
GROUP BY CUSTOMER_CODE
having nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) > 0
AND (nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0))) > 0

how to sort an ArrayList in ascending order using Collections and Comparator

Here a complete example :

Suppose we have a Person class like :

public class Person
{
    protected String fname;
    protected String lname;

    public Person()
    {

    }

    public Person(String fname, String lname)
    {
        this.fname = fname;
        this.lname = lname;
    }

    public boolean equals(Object objet)
    {
        if(objet instanceof Person)
        {
            Person p = (Person) objet;
            return (p.getFname().equals(this.fname)) && p.getLname().equals(this.lname));
        }
        else return super.equals(objet);
    }

    @Override
    public String toString()
    {
        return "Person(fname : " + getFname + ", lname : " + getLname + ")";
    }

    /** Getters and Setters **/
}

Now we create a comparator :

import java.util.Comparator;

public class ComparePerson implements Comparator<Person>
{
    @Override
    public int compare(Person p1, Person p2)
    {
        if(p1.getFname().equalsIgnoreCase(p2.getFname()))
        {
            return p1.getLname().compareTo(p2.getLname());
        }
        return p1.getFname().compareTo(p2.getFname());
    }
}

Finally suppose we have a group of persons :

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Group
{
    protected List<Person> listPersons;

    public Group()
    {
        this.listPersons = new ArrayList<Person>();
    }

    public Group(List<Person> listPersons)
    {
        this.listPersons = listPersons;
    }

    public void order(boolean asc)
    {
        Comparator<Person> comp = asc ? new ComparePerson() : Collections.reverseOrder(new ComparePerson());
        Collections.sort(this.listPersons, comp);
    }

    public void display()
    {
        for(Person p : this.listPersons)
        {
            System.out.println(p);
        }
    }

    /** Getters and Setters **/
}

Now we try this :

import java.util.ArrayList;
import java.util.List;

public class App
{
    public static void main(String[] args)
    {
        Group g = new Group();
        List listPersons = new ArrayList<Person>();
        g.setListPersons(listPersons);

        Person p;

        p = new Person("A", "B");
        listPersons.add(p);

        p = new Person("C", "D");
        listPersons.add(p);

        /** you can add Person as many as you want **/

        g.display();

        g.order(true);
        g.display();

        g.order(false);
        g.display();
    }
}

Breaking to a new line with inline-block?

You can try with:

    display: inline-table;

For me it works fine.

How do I create a link using javascript?

With JavaScript

  1. var a = document.createElement('a');
    a.setAttribute('href',desiredLink);
    a.innerHTML = desiredText;
    // apend the anchor to the body
    // of course you can append it almost to any other dom element
    document.getElementsByTagName('body')[0].appendChild(a);
    
  2. document.getElementsByTagName('body')[0].innerHTML += '<a href="'+desiredLink+'">'+desiredText+'</a>';
    

    or, as suggested by @travis :

    document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
    
  3. <script type="text/javascript">
    //note that this case can be used only inside the "body" element
    document.write('<a href="'+desiredLink+'">'+desiredText+'</a>');
    </script>
    

With JQuery

  1. $('<a href="'+desiredLink+'">'+desiredText+'</a>').appendTo($('body'));
    
  2. $('body').append($('<a href="'+desiredLink+'">'+desiredText+'</a>'));
    
  3. var a = $('<a />');
    a.attr('href',desiredLink);
    a.text(desiredText);
    $('body').append(a);
    

In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink is a variable that holds the address that your anchor element points to, and desiredText is a variable that holds the text that will be displayed in the anchor element.

Generate PDF from HTML using pdfMake in Angularjs

this is what it worked for me I'm using html2pdf from an Angular2 app, so I made a reference to this function in the controller

var html2pdf = (function(html2canvas, jsPDF) {

declared in html2pdf.js.

So I added just after the import declarations in my angular-controller this declaration:

declare function html2pdf(html2canvas, jsPDF): any;

then, from a method of my angular controller I'm calling this function:

generate_pdf(){
    this.someService.loadContent().subscribe(
      pdfContent => {
        html2pdf(pdfContent, {
          margin:       1,
          filename:     'myfile.pdf',
          image:        { type: 'jpeg', quality: 0.98 },
          html2canvas:  { dpi: 192, letterRendering: true },
          jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
        });
      }
    );
  }

Hope it helps

Add JVM options in Tomcat

After checking catalina.sh (for windows use the .bat versions of everything mentioned below)

#   Do not set the variables in this script. Instead put them into a script
#   setenv.sh in CATALINA_BASE/bin to keep your customizations separate.

Also this

#   CATALINA_OPTS   (Optional) Java runtime options used when the "start",
#                   "run" or "debug" command is executed.
#                   Include here and not in JAVA_OPTS all options, that should
#                   only be used by Tomcat itself, not by the stop process,
#                   the version command etc.
#                   Examples are heap size, GC logging, JMX ports etc

So create a setenv.sh under CATALINA_BASE/bin (same dir where the catalina.sh resides). Edit the file and set the arguments to CATALINA_OPTS

For e.g. the file would look like this if you wanted to change the heap size

CATALINA_OPTS=-Xmx512m

Or in your case since you're using windows setenv.bat would be

set CATALINA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5

To clear the added options later just delete setenv.bat/sh

How to convert password into md5 in jquery?

Get the field value through the id and send with ajax

var field = $("#field").val();
$.ajax({
    type: "POST",
    url: "db.php",
    data: {variable_name:field},
    async:false,
    dataType:"json",
    success: function(response) {
       alert(response);
    }
 });

At db.php file get the variable name

$variable_name = $_GET['variable_name'];
mysql_query("SELECT password FROM table_name WHERE password='".md5($variable_name)."'");

Sending HTTP Post request with SOAP action using org.apache.http

The soapAction must passed as a http-header parameter - when used, it's not part of the http-body/payload.

Look here for an example with apache httpclient: http://svn.apache.org/repos/asf/httpcomponents/oac.hc3x/trunk/src/examples/PostSOAP.java

Matplotlib (pyplot) savefig outputs blank image

Calling savefig before show() worked for me.

fig ,ax = plt.subplots(figsize = (4,4))
sns.barplot(x='sex', y='tip', color='g', ax=ax,data=tips)
sns.barplot(x='sex', y='tip', color='b', ax=ax,data=tips)
ax.legend(['Male','Female'], facecolor='w')

plt.savefig('figure.png')
plt.show()

avrdude: stk500v2_ReceiveMessage(): timeout

I've connected to USB port directly in my laptop and timeout issue has been resolved.

Previously tried by port replicator, but it did not even recognized arduino, thus I chosen wrong port - resulting in timeout message.

So make sure that it is visible by your OS.

How do you append to a file?

If multiple processes are writing to the file, you must use append mode or the data will be scrambled. Append mode will make the operating system put every write, at the end of the file irrespective of where the writer thinks his position in the file is. This is a common issue for multi-process services like nginx or apache where multiple instances of the same process, are writing to the same log file. Consider what happens if you try to seek, then write:

Example does not work well with multiple processes: 

f = open("logfile", "w"); f.seek(0, os.SEEK_END); f.write("data to write");

writer1: seek to end of file.           position 1000 (for example)
writer2: seek to end of file.           position 1000
writer2: write data at position 1000    end of file is now 1000 + length of data.
writer1: write data at position 1000    writer1's data overwrites writer2's data.

By using append mode, the operating system will place any write at the end of the file.

f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");

Append most does not mean, "open file, go to end of the file once after opening it". It means, "open file, every write I do will be at the end of the file".

WARNING: For this to work you must write all your record in one shot, in one write call. If you split the data between multiple writes, other writers can and will get their writes in between yours and mangle your data.

How can I change Eclipse theme?

enter image description here My Theme plugin provide full featured customization for Eclipse 4. Try it. Visit Plugin Page

Get type of all variables

You need to use get to obtain the value rather than the character name of the object as returned by ls:

x <- 1L
typeof(ls())
[1] "character"
typeof(get(ls()))
[1] "integer"

Alternatively, for the problem as presented you might want to use eapply:

eapply(.GlobalEnv,typeof)
$x
[1] "integer"

$a
[1] "double"

$b
[1] "character"

$c
[1] "list"

Match two strings in one line with grep

The | operator in a regular expression means or. That is to say either string1 or string2 will match. You could do:

grep 'string1' filename | grep 'string2'

which will pipe the results from the first command into the second grep. That should give you only lines that match both.

Getting all request parameters in Symfony 2

With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;

    class SampleController extends Controller
    {


        public function indexAction(Request $request) {

           var_dump($request->request->all());
        }

    }

Add ripple effect to my button with button background color?

Here is another drawable xml for those who want to add all together gradient background, corner radius and ripple effect:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/colorPrimaryDark">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimaryDark" />
            <corners android:radius="@dimen/button_radius_large" />
        </shape>
    </item>

    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <gradient
                android:angle="90"
                android:endColor="@color/colorPrimaryLight"
                android:startColor="@color/colorPrimary"
                android:type="linear" />
            <corners android:radius="@dimen/button_radius_large" />
        </shape>
    </item>
</ripple>

Add this to the background of your button.

<Button
    ...
    android:background="@drawable/button_background" />

PS: this answer works for android api 21 and above.

random number generator between 0 - 1000 in c#

Have you tried this

Random integer between 0 and 1000(1000 not included):

Random random = new Random();
int randomNumber = random.Next(0, 1000);

Loop it as many times you want

Import Script from a Parent Directory

You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).

In general it is preferable to use absolute imports rather than relative imports.

toplevel_package/
+-- __init__.py
+-- moduleA.py
+-- subpackage
    +-- __init__.py
    +-- moduleB.py

In moduleB:

from toplevel_package import moduleA

If you'd like to run moduleB.py as a script then make sure that parent directory for toplevel_package is in your sys.path.

What is the color code for transparency in CSS?

jus add two zeroes (00) before your color code you will get the transparent of that color

gson throws MalformedJsonException

I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing } character. What's the length of result1 versus result2? I'll note that result2 as you've quoted it has 169 characters.

GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t, \n, \r, and space count as whitespace. In particular, note that trailing NUL (\0) characters do not count as whitespace and will cause this error.

If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:

Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);

How to delete the top 1000 rows from a table using Sql Server 2008?

SET ROWCOUNT 1000;

DELETE FROM [MyTable] WHERE .....

Loop Through Each HTML Table Column and Get the Data using jQuery

You can try with textContent.

var productId = val[key].textContent;

Is there a JSON equivalent of XQuery/XPath?

@Naftule - with "defiant.js", it is possible to query a JSON structure with XPath expressions. Check out this evaluator to get an idea of how it works:

http://www.defiantjs.com/#xpath_evaluator

Unlike JSONPath, "defiant.js" delivers the full-scale support of the query syntax - of XPath on JSON structures.

The source code of defiant.js can be found here:
https://github.com/hbi99/defiant.js

Java - Convert image to Base64

 byte[] byteArray = new byte[102400];
 base64String = Base64.encode(byteArray);

That code will encode 102400 bytes, no matter how much data you actually use in the array.

while ((bytesRead = fis.read(byteArray)) != -1)

You need to use the value of bytesRead somewhere.

Also, this may not read the whole file into the array in one go (it only reads as much as is in the I/O buffer), so your loop will probably not work, you may end up with half an image in your array.

I'd use Apache Commons IOUtils here:

 Base64.encode(FileUtils.readFileToByteArray(file));

What range of values can integer types store in C++

For unsigned data type there is no sign bit and all bits are for data ; whereas for signed data type MSB is indicated sign bit and remaining bits are for data.

To find the range do following things :

Step:1 -> Find out no of bytes for the give data type.

Step:2 -> Apply following calculations.

      Let n = no of bits in data type  

      For signed data type ::
            Lower Range = -(2^(n-1)) 
            Upper Range = (2^(n-1)) - 1)  

      For unsigned data type ::
            Lower Range = 0 
            Upper Range = (2^(n)) - 1 

For e.g.

For unsigned int size = 4 bytes (32 bits) --> Range [0 , (2^(32)) - 1]

For signed int size = 4 bytes (32 bits) --> Range [-(2^(32-1)) , (2^(32-1)) - 1]

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

getOutputStream() has already been called for this response

Add the following inside the end of the try/catch to avoid the error that appears when the JSP engine flushes the response via getWriter()

out.clear(); // where out is a JspWriter
out = pageContext.pushBody();

As has been noted, this isn't best practice, but it avoids the errors in your logs.

Java Regex Capturing Groups

This is totally OK.

  1. The first group (m.group(0)) always captures the whole area that is covered by your regular expression. In this case, it's the whole string.
  2. Regular expressions are greedy by default, meaning that the first group captures as much as possible without violating the regex. The (.*)(\\d+) (the first part of your regex) covers the ...QT300 int the first group and the 0 in the second.
  3. You can quickly fix this by making the first group non-greedy: change (.*) to (.*?).

For more info on greedy vs. lazy, check this site.

Find duplicate values in R

You could use table, i.e.

n_occur <- data.frame(table(vocabulary$id))

gives you a data frame with a list of ids and the number of times they occurred.

n_occur[n_occur$Freq > 1,]

tells you which ids occurred more than once.

vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]

returns the records with more than one occurrence.

How to use the addr2line command in Linux?

You can also use gdb instead of addr2line to examine memory address. Load executable file in gdb and print the name of a symbol which is stored at the address. 16 Examining the Symbol Table.

(gdb) info symbol 0x4005BDC 

Why use Redux over Facebook Flux?

Redux author here!

Redux is not that different from Flux. Overall it has same architecture, but Redux is able to cut some complexity corners by using functional composition where Flux uses callback registration.

There is not a fundamental difference in Redux, but I find it makes certain abstractions easier, or at least possible to implement, that would be hard or impossible to implement in Flux.

Reducer Composition

Take, for example, pagination. My Flux + React Router example handles pagination, but the code for that is awful. One of the reasons it's awful is that Flux makes it unnatural to reuse functionality across stores. If two stores need to handle pagination in response to different actions, they either need to inherit from a common base store (bad! you're locking yourself into a particular design when you use inheritance), or call an externally defined function from within the event handler, which will need to somehow operate on the Flux store's private state. The whole thing is messy (although definitely in the realm of possible).

On the other hand, with Redux pagination is natural thanks to reducer composition. It's reducers all the way down, so you can write a reducer factory that generates pagination reducers and then use it in your reducer tree. The key to why it's so easy is because in Flux, stores are flat, but in Redux, reducers can be nested via functional composition, just like React components can be nested.

This pattern also enables wonderful features like no-user-code undo/redo. Can you imagine plugging Undo/Redo into a Flux app being two lines of code? Hardly. With Redux, it is—again, thanks to reducer composition pattern. I need to highlight there's nothing new about it—this is the pattern pioneered and described in detail in Elm Architecture which was itself influenced by Flux.

Server Rendering

People have been rendering on the server fine with Flux, but seeing that we have 20 Flux libraries each attempting to make server rendering “easier”, perhaps Flux has some rough edges on the server. The truth is Facebook doesn't do much server rendering, so they haven't been very concerned about it, and rely on the ecosystem to make it easier.

In traditional Flux, stores are singletons. This means it's hard to separate the data for different requests on the server. Not impossible, but hard. This is why most Flux libraries (as well as the new Flux Utils) now suggest you use classes instead of singletons, so you can instantiate stores per request.

There are still the following problems that you need to solve in Flux (either yourself or with the help of your favorite Flux library such as Flummox or Alt):

  • If stores are classes, how do I create and destroy them with dispatcher per request? When do I register stores?
  • How do I hydrate the data from the stores and later rehydrate it on the client? Do I need to implement special methods for this?

Admittedly Flux frameworks (not vanilla Flux) have solutions to these problems, but I find them overcomplicated. For example, Flummox asks you to implement serialize() and deserialize() in your stores. Alt solves this nicer by providing takeSnapshot() that automatically serializes your state in a JSON tree.

Redux just goes further: since there is just a single store (managed by many reducers), you don't need any special API to manage the (re)hydration. You don't need to “flush” or “hydrate” stores—there's just a single store, and you can read its current state, or create a new store with a new state. Each request gets a separate store instance. Read more about server rendering with Redux.

Again, this is a case of something possible both in Flux and Redux, but Flux libraries solve this problem by introducing a ton of API and conventions, and Redux doesn't even have to solve it because it doesn't have that problem in the first place thanks to conceptual simplicity.

Developer Experience

I didn't actually intend Redux to become a popular Flux library—I wrote it as I was working on my ReactEurope talk on hot reloading with time travel. I had one main objective: make it possible to change reducer code on the fly or even “change the past” by crossing out actions, and see the state being recalculated.

I haven't seen a single Flux library that is able to do this. React Hot Loader also doesn't let you do this—in fact it breaks if you edit Flux stores because it doesn't know what to do with them.

When Redux needs to reload the reducer code, it calls replaceReducer(), and the app runs with the new code. In Flux, data and functions are entangled in Flux stores, so you can't “just replace the functions”. Moreover, you'd have to somehow re-register the new versions with the Dispatcher—something Redux doesn't even have.

Ecosystem

Redux has a rich and fast-growing ecosystem. This is because it provides a few extension points such as middleware. It was designed with use cases such as logging, support for Promises, Observables, routing, immutability dev checks, persistence, etc, in mind. Not all of these will turn out to be useful, but it's nice to have access to a set of tools that can be easily combined to work together.

Simplicity

Redux preserves all the benefits of Flux (recording and replaying of actions, unidirectional data flow, dependent mutations) and adds new benefits (easy undo-redo, hot reloading) without introducing Dispatcher and store registration.

Keeping it simple is important because it keeps you sane while you implement higher-level abstractions.

Unlike most Flux libraries, Redux API surface is tiny. If you remove the developer warnings, comments, and sanity checks, it's 99 lines. There is no tricky async code to debug.

You can actually read it and understand all of Redux.


See also my answer on downsides of using Redux compared to Flux.

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.

How to make System.out.println() shorter

package some.useful.methods;

public class B {

    public static void p(Object s){
        System.out.println(s);
    }
}
package first.java.lesson;

import static some.useful.methods.B.*;

public class A {

    public static void main(String[] args) {

        p("Hello!");

    }
}

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

When you click on the image you'll get the alert:

<img src="logo1.jpg" onClick='alert("Hello World!")'/>

if this is what you want.

Change the color of a checked menu item in a navigation drawer

One need to set NavigateItem checked true whenever item in NavigateView is clicked

//listen for navigation events
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
// select the correct nav menu item
navigationView.getMenu().findItem(mNavItemId).setChecked(true);

Add NavigationItemSelectedListener on NavigationView

  @Override
  public boolean onNavigationItemSelected(final MenuItem menuItem) {
    // update highlighted item in the navigation menu
    menuItem.setChecked(true);
    mNavItemId = menuItem.getItemId();

    // allow some time after closing the drawer before performing real navigation
    // so the user can see what is happening
    mDrawerLayout.closeDrawer(GravityCompat.START);
    mDrawerActionHandler.postDelayed(new Runnable() {
      @Override
      public void run() {
        navigate(menuItem.getItemId());
      }
    }, DRAWER_CLOSE_DELAY_MS);
    return true;
  }

How to return a value from try, catch, and finally?

The problem is what happens when you get NumberFormatexception thrown? You print it and return nothing.

Note: You don't need to catch and throw an Exception back. Usually it is done to wrap it or print stack trace and ignore for example.

catch(RangeException e) {
     throw e;
}

Check/Uncheck all the checkboxes in a table

This solution is better because it is shorter and doesn't use a loop.

id="checkAll" is the header column

$('#checkAll').on('click', function() {
        if (this.checked == true)
            $('#userTable').find('input[name="checkboxRow"]').prop('checked', true);
        else
            $('#userTable').find('input[name="checkboxRow"]').prop('checked', false);
    });

How to create a temporary directory and get the path / file name in Python

Use the mkdtemp() function from the tempfile module:

import tempfile
import shutil

dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)

HTML if image is not found

This one worked for me. using the srcset. I have just learnt about it so i dont know if browsers support it but it has worked for me. Try it and later give me your feed back.

 <img src="smiley.gif" srcset="alternatve.gif" width="32" height="32" />

How to configure nginx to enable kinda 'file browser' mode?

1. List content of all directories

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default ) should be like this

location /{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

2. List content of only some specific directory

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default )
should be like this.
change path_of_your_directory to your directory path

location /path_of_your_directory{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

Hope it helps..

Setting environment variables on OS X

Another, free, opensource, Mac OS X v10.8 (Mountain Lion) Preference pane/environment.plist solution is EnvPane.

EnvPane's source code available on GitHub. EnvPane looks like it has comparable features to RCEnvironment, however, it seems it can update its stored variables instantly, i.e. without the need for a restart or login, which is welcome.

As stated by the developer:

EnvPane is a preference pane for Mac OS X 10.8 (Mountain Lion) that lets you set environment variables for all programs in both graphical and terminal sessions. Not only does it restore support for ~/.MacOSX/environment.plist in Mountain Lion, it also publishes your changes to the environment immediately, without the need to log out and back in. <SNIP> EnvPane includes (and automatically installs) a launchd agent that runs 1) early after login and 2) whenever the ~/.MacOSX/environment.plist changes. The agent reads ~/.MacOSX/environment.plist and exports the environment variables from that file to the current user's launchd instance via the same API that is used by launchctl setenv and launchctl unsetenv.

Disclaimer: I am in no way related to the developer or his/her project.

P.S. I like the name (sounds like 'Ends Pain').

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

Update: 5/5/2015 For your MVC 5 project you need to set the Version to 5.0.0.0 in your /views/web.config

<system.web.webPages.razor>
     <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</system.web.webPages.razor>

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

In prototypeJS, we have method isJSON. You can try that. Even json might help.

"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();

How do I check if an index exists on a table field in MySQL?

If you need the functionality if a index for a column exists (here at first place in sequence) as a database function you can use/adopt this code. If you want to check if an index exists at all regardless of the position in a multi-column-index, then just delete the part "AND SEQ_IN_INDEX = 1".

DELIMITER $$
CREATE FUNCTION `fct_check_if_index_for_column_exists_at_first_place`(
    `IN_SCHEMA` VARCHAR(255),
    `IN_TABLE` VARCHAR(255),
    `IN_COLUMN` VARCHAR(255)
)
RETURNS tinyint(4)
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Check if index exists at first place in sequence for a given column in a given table in a given schema. Returns -1 if schema does not exist. Returns -2 if table does not exist. Returns -3 if column does not exist. If index exists in first place it returns 1, otherwise 0.'
BEGIN

-- Check if index exists at first place in sequence for a given column in a given table in a given schema. 
-- Returns -1 if schema does not exist. 
-- Returns -2 if table does not exist. 
-- Returns -3 if column does not exist. 
-- If the index exists in first place it returns 1, otherwise 0.
-- Example call: SELECT fct_check_if_index_for_column_exists_at_first_place('schema_name', 'table_name', 'index_name');

-- check if schema exists
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    INFORMATION_SCHEMA.SCHEMATA
WHERE 
    SCHEMA_NAME = IN_SCHEMA
;

IF @COUNT_EXISTS = 0 THEN
    RETURN -1;
END IF;


-- check if table exists
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    INFORMATION_SCHEMA.TABLES
WHERE 
    TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE
;

IF @COUNT_EXISTS = 0 THEN
    RETURN -2;
END IF;


-- check if column exists
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    INFORMATION_SCHEMA.COLUMNS
WHERE 
    TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE
AND COLUMN_NAME = IN_COLUMN
;

IF @COUNT_EXISTS = 0 THEN
    RETURN -3;
END IF;

-- check if index exists at first place in sequence
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    information_schema.statistics 
WHERE 
    TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE AND COLUMN_NAME = IN_COLUMN
AND SEQ_IN_INDEX = 1;


IF @COUNT_EXISTS > 0 THEN
    RETURN 1;
ELSE
    RETURN 0;
END IF;


END$$
DELIMITER ;

How to implement common bash idioms in Python?

Any shell has several sets of features.

  • The Essential Linux/Unix commands. All of these are available through the subprocess library. This isn't always the best first choice for doing all external commands. Look also at shutil for some commands that are separate Linux commands, but you could probably implement directly in your Python scripts. Another huge batch of Linux commands are in the os library; you can do these more simply in Python.

    And -- bonus! -- more quickly. Each separate Linux command in the shell (with a few exceptions) forks a subprocess. By using Python shutil and os modules, you don't fork a subprocess.

  • The shell environment features. This includes stuff that sets a command's environment (current directory and environment variables and what-not). You can easily manage this from Python directly.

  • The shell programming features. This is all the process status code checking, the various logic commands (if, while, for, etc.) the test command and all of it's relatives. The function definition stuff. This is all much, much easier in Python. This is one of the huge victories in getting rid of bash and doing it in Python.

  • Interaction features. This includes command history and what-not. You don't need this for writing shell scripts. This is only for human interaction, and not for script-writing.

  • The shell file management features. This includes redirection and pipelines. This is trickier. Much of this can be done with subprocess. But some things that are easy in the shell are unpleasant in Python. Specifically stuff like (a | b; c ) | something >result. This runs two processes in parallel (with output of a as input to b), followed by a third process. The output from that sequence is run in parallel with something and the output is collected into a file named result. That's just complex to express in any other language.

Specific programs (awk, sed, grep, etc.) can often be rewritten as Python modules. Don't go overboard. Replace what you need and evolve your "grep" module. Don't start out writing a Python module that replaces "grep".

The best thing is that you can do this in steps.

  1. Replace AWK and PERL with Python. Leave everything else alone.
  2. Look at replacing GREP with Python. This can be a bit more complex, but your version of GREP can be tailored to your processing needs.
  3. Look at replacing FIND with Python loops that use os.walk. This is a big win because you don't spawn as many processes.
  4. Look at replacing common shell logic (loops, decisions, etc.) with Python scripts.

Add my custom http header to Spring RestTemplate request / extend RestTemplate

If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer parameter can be used with a RestTemplateBuilder:

 String accessToken= "<the oauth 2 token>";
 RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
        request.getHeaders().add("Authorization", "Bearer "+accessToken);
        return execution.execute(request, body);
    })).build();

What is the difference between signed and unsigned int

Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.

JOIN two SELECT statement results

you can use the UNION ALL keyword for this.

Here is the MSDN doc to do it in T-SQL http://msdn.microsoft.com/en-us/library/ms180026.aspx

UNION ALL - combines the result set

UNION- Does something like a Set Union and doesnt output duplicate values

For the difference with an example: http://sql-plsql.blogspot.in/2010/05/difference-between-union-union-all.html

HTML5 <video> element on Android

Try h.264 in an mp4 container. I've had much success with it on my Droid X. I've been using zencoder.com for format conversions.