Programs & Examples On #Const correctness

How to register multiple implementations of the same interface in Asp.Net Core?

I created my own extension over IServiceCollection used WithName extension:

public static IServiceCollection AddScopedWithName<TService, TImplementation>(this IServiceCollection services, string serviceName)
        where TService : class
        where TImplementation : class, TService
    {
        Type serviceType = typeof(TService);
        Type implementationServiceType = typeof(TImplementation);
        ServiceCollectionTypeMapper.Instance.AddDefinition(serviceType.Name, serviceName, implementationServiceType.AssemblyQualifiedName);
        services.AddScoped<TImplementation>();
        return services;
    }

ServiceCollectionTypeMapper is a singleton instance that maps IService > NameOfService > Implementation where an interface could have many implementations with different names, this allows to register types than we can resolve when wee need and is a different approach than resolve multiple services to select what we want.

 /// <summary>
/// Allows to set the service register mapping.
/// </summary>
public class ServiceCollectionTypeMapper
{
    private ServiceCollectionTypeMapper()
    {
        this.ServiceRegister = new Dictionary<string, Dictionary<string, string>>();
    }

    /// <summary>
    /// Gets the instance of mapper.
    /// </summary>
    public static ServiceCollectionTypeMapper Instance { get; } = new ServiceCollectionTypeMapper();

    private Dictionary<string, Dictionary<string, string>> ServiceRegister { get; set; }

    /// <summary>
    /// Adds new service definition.
    /// </summary>
    /// <param name="typeName">The name of the TService.</param>
    /// <param name="serviceName">The TImplementation name.</param>
    /// <param name="namespaceFullName">The TImplementation AssemblyQualifiedName.</param>
    public void AddDefinition(string typeName, string serviceName, string namespaceFullName)
    {
        if (this.ServiceRegister.TryGetValue(typeName, out Dictionary<string, string> services))
        {
            if (services.TryGetValue(serviceName, out _))
            {
                throw new InvalidOperationException($"Exists an implementation with the same name [{serviceName}] to the type [{typeName}].");
            }
            else
            {
                services.Add(serviceName, namespaceFullName);
            }
        }
        else
        {
            Dictionary<string, string> serviceCollection = new Dictionary<string, string>
            {
                { serviceName, namespaceFullName },
            };
            this.ServiceRegister.Add(typeName, serviceCollection);
        }
    }

    /// <summary>
    /// Get AssemblyQualifiedName of implementation.
    /// </summary>
    /// <typeparam name="TService">The type of the service implementation.</typeparam>
    /// <param name="serviceName">The name of the service.</param>
    /// <returns>The AssemblyQualifiedName of the inplementation service.</returns>
    public string GetService<TService>(string serviceName)
    {
        Type serviceType = typeof(TService);

        if (this.ServiceRegister.TryGetValue(serviceType.Name, out Dictionary<string, string> services))
        {
            if (services.TryGetValue(serviceName, out string serviceImplementation))
            {
                return serviceImplementation;
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

To register a new service:

services.AddScopedWithName<IService, MyService>("Name");

To resolve service we need an extension over IServiceProvider like this.

/// <summary>
    /// Gets the implementation of service by name.
    /// </summary>
    /// <typeparam name="T">The type of service.</typeparam>
    /// <param name="serviceProvider">The service provider.</param>
    /// <param name="serviceName">The service name.</param>
    /// <returns>The implementation of service.</returns>
    public static T GetService<T>(this IServiceProvider serviceProvider, string serviceName)
    {
        string fullnameImplementation = ServiceCollectionTypeMapper.Instance.GetService<T>(serviceName);
        if (fullnameImplementation == null)
        {
            throw new InvalidOperationException($"Unable to resolve service of type [{typeof(T)}] with name [{serviceName}]");
        }
        else
        {
            return (T)serviceProvider.GetService(Type.GetType(fullnameImplementation));
        }
    }

When resolve:

serviceProvider.GetService<IWithdrawalHandler>(serviceName);

Remember that serviceProvider can be injected within a constructor in our application as IServiceProvider.

I hope this helps.

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

If you are using office 365 follow this steps:

  1. check the password expiration time using Azure power shell :Get-MsolUser -All | select DisplayName, LastPasswordChangeTimeStamp
  2. Change the password using a new password (not the old one). You can eventually go back to the old password but you need to change it twice.

Hope it helps!

How to return a resolved promise from an AngularJS Service using $q?

How to simply return a pre-resolved promise in AngularJS

Resolved promise:

return $q.when( someValue );    // angularjs 1.2+
return $q.resolve( someValue ); // angularjs 1.4+, alias to `when` to match ES6

Rejected promise:

return $q.reject( someValue );

How to start activity in another application?

If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

Hope it helps.

How to stop process from .BAT file?

To terminate a process you know the name of, try:

taskkill /IM notepad.exe

This will ask it to close, but it may refuse, offer to "save changes", etc. If you want to forcibly kill it, try:

taskkill /F /IM notepad.exe

Visual Studio SignTool.exe Not Found

Here is a solution for Visual Studio 2017. The installer looks a littlebit different from the VS 2015 version and the name of the installation packages are different.

jquery <a> tag click event

That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid and grab them via:

var uids = $(".uid").map(function() {
    return this.value;
}).get();

Demo: http://jsfiddle.net/karim79/FtcnJ/

EDIT: say your output looks like the following (notice, IDs have changed to classes)

<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>

You can target the 'uid' relative to the clicked anchor like this:

$("a.aaf").click(function() {
    alert($(this).next('.uid').val());
});

Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.

What is the difference between Cloud, Grid and Cluster?

Cloud is a marketing term, with the bare minimum feature relating to fast automated provisioning of new servers. HA, utility billing, etc are all features people can lump on top to define it to their own liking.

Grid [Computing] is an extension of clusters where multiple loosely coupled systems are used to solve a single problem. They tend to be multi-tenant, sharing some likeness to Clouds, but tend to rely heavily upon custom frameworks that manage the interop between grid nodes.

Cluster hosting is a specialization of clusters where a load balancer is used to direct incoming traffic to one of many worker nodes. It predates grid computing and doesn't rely on a homogenous abstraction of the underlying nodes as much as Grid computing. A web farm tends to have very specialized machines dedicated to each component type and is far more optimized for that specific task.

For pure hosting, Grid computing is the wrong tool. If you have no idea what your traffic shape is, then a Cloud would be useful. For predictable usage that changes at a reasonable pace, then a traditional cluster is fine and the most efficient.

Location for session files in Apache/PHP

If unsure of compiled default for session.save_path, look at the pertinent php.ini.
Normally, this will show the commented out default value.

Ubuntu/Debian old/new php.ini locations:
Older php5 with Apache: /etc/php5/apache2/php.ini
Older php5 with NGINX+FPM: /etc/php5/fpm/php.ini
Ubuntu 16+ with Apache: /etc/php/*/apache2/php.ini *
Ubuntu 16+ with NGINX+FPM - /etc/php/*/fpm/php.ini *

* /*/ = the current PHP version(s) installed on system.

To show the PHP version in use under Apache:

$ a2query -m | grep "php" | grep -Eo "[0-9]+\.[0-9]+"

7.3

Since PHP 7.3 is the version running for this example, you would use that for the php.ini:

$ grep "session.save_path" /etc/php/7.3/apache2/php.ini

;session.save_path = "/var/lib/php/sessions"

Or, combined one-liner:

$ APACHEPHPVER=$(a2query -m | grep "php" | grep -Eo "[0-9]+\.[0-9]+") \ && grep ";session.save_path" /etc/php/${APACHEPHPVER}/apache2/php.ini

Result:

;session.save_path = "/var/lib/php/sessions"


Or, use PHP itself to grab the value using the "cli" environment (see NOTE below):

$ php -r 'echo session_save_path() . "\n";'
/var/lib/php/sessions
$

These will also work:

php -i | grep session.save_path

php -r 'echo phpinfo();' | grep session.save_path

NOTE:

The 'cli' (command line) version of php.ini normally has the same default values as the Apache2/FPM versions (at least as far as the session.save_path). You could also use a similar command to echo the web server's current PHP module settings to a webpage and use wget/curl to grab the info. There are many posts regarding phpinfo() use in this regard. But, it is quicker to just use the PHP interface or grep for it in the correct php.ini to show it's default value.

EDIT: Per @aesede comment -> Added php -i. Thanks

Create a hexadecimal colour based on a string with JavaScript

I wanted similar richness in colors for HTML elements, I was surprised to find that CSS now supports hsl() colors, so a full solution for me is below:

Also see How to automatically generate N "distinct" colors? for more alternatives more similar to this.

_x000D_
_x000D_
function colorByHashCode(value) {_x000D_
    return "<span style='color:" + value.getHashCode().intToHSL() + "'>" + value + "</span>";_x000D_
}_x000D_
String.prototype.getHashCode = function() {_x000D_
    var hash = 0;_x000D_
    if (this.length == 0) return hash;_x000D_
    for (var i = 0; i < this.length; i++) {_x000D_
        hash = this.charCodeAt(i) + ((hash << 5) - hash);_x000D_
        hash = hash & hash; // Convert to 32bit integer_x000D_
    }_x000D_
    return hash;_x000D_
};_x000D_
Number.prototype.intToHSL = function() {_x000D_
    var shortened = this % 360;_x000D_
    return "hsl(" + shortened + ",100%,30%)";_x000D_
};_x000D_
_x000D_
document.body.innerHTML = [_x000D_
  "javascript",_x000D_
  "is",_x000D_
  "nice",_x000D_
].map(colorByHashCode).join("<br/>");
_x000D_
span {_x000D_
  font-size: 50px;_x000D_
  font-weight: 800;_x000D_
}
_x000D_
_x000D_
_x000D_

In HSL its Hue, Saturation, Lightness. So the hue between 0-359 will get all colors, saturation is how rich you want the color, 100% works for me. And Lightness determines the deepness, 50% is normal, 25% is dark colors, 75% is pastel. I have 30% because it fit with my color scheme best.

Find IP address of directly connected device

To use DHCP, you'd have to run a DHCP server on the primary and a client on the secondary; the primary could then query the server to find out what address it handed out. Probably overkill.

I can't help you with Windows directly. On Unix, the "arp" command will tell you what IP addresses are known to be attached to the local ethernet segment. Windows will have this same information (since it's a core part of the IP/Ethernet interface) but I don't know how you get at it.

Of course, the networking stack will only know about the other host if it has previously seen traffic from it. You may have to first send a broadcast packet on the interface to elicit some sort of response and thus populate the local ARP table.

How do you detect where two line segments intersect?

Here's an improvement to Gavin's answer. marcp's solution is similar also, but neither postpone the division.

This actually turns out to be a practical application of Gareth Rees' answer as well, because the cross-product's equivalent in 2D is the perp-dot-product, which is what this code uses three of. Switching to 3D and using the cross-product, interpolating both s and t at the end, results in the two closest points between the lines in 3D. Anyway, the 2D solution:

int get_line_intersection(float p0_x, float p0_y, float p1_x, float p1_y, 
    float p2_x, float p2_y, float p3_x, float p3_y, float *i_x, float *i_y)
{
    float s02_x, s02_y, s10_x, s10_y, s32_x, s32_y, s_numer, t_numer, denom, t;
    s10_x = p1_x - p0_x;
    s10_y = p1_y - p0_y;
    s32_x = p3_x - p2_x;
    s32_y = p3_y - p2_y;

    denom = s10_x * s32_y - s32_x * s10_y;
    if (denom == 0)
        return 0; // Collinear
    bool denomPositive = denom > 0;

    s02_x = p0_x - p2_x;
    s02_y = p0_y - p2_y;
    s_numer = s10_x * s02_y - s10_y * s02_x;
    if ((s_numer < 0) == denomPositive)
        return 0; // No collision

    t_numer = s32_x * s02_y - s32_y * s02_x;
    if ((t_numer < 0) == denomPositive)
        return 0; // No collision

    if (((s_numer > denom) == denomPositive) || ((t_numer > denom) == denomPositive))
        return 0; // No collision
    // Collision detected
    t = t_numer / denom;
    if (i_x != NULL)
        *i_x = p0_x + (t * s10_x);
    if (i_y != NULL)
        *i_y = p0_y + (t * s10_y);

    return 1;
}

Basically it postpones the division until the last moment, and moves most of the tests until before certain calculations are done, thereby adding early-outs. Finally, it also avoids the division by zero case which occurs when the lines are parallel.

You also might want to consider using an epsilon test rather than comparison against zero. Lines that are extremely close to parallel can produce results that are slightly off. This is not a bug, it is a limitation with floating point math.

Video file formats supported in iPhone

The short answer is the iPhone supports H.264 video, High profile and AAC audio, in container formats .mov, .mp4, or MPEG Segment .ts. MPEG Segment files are used for HTTP Live Streaming.

  • For maximum compatibility with Android and desktop browsers, use H.264 + AAC in an .mp4 container.
  • For extended length videos longer than 10 minutes you must use HTTP Live Streaming, which is H.264 + AAC in a series of small .ts container files (see App Store Review Guidelines rule 2.5.7).

Video

On the iPhone, H.264 is the only game in town. [1]

There are several different feature tiers or "profiles" available in H.264. All modern iPhones (3GS and above) support the High profile. These profiles are basically three different levels of algorithm "tricks" used to compress the video. More tricks give better compression, but require more CPU or dedicated hardware to decode. This is a table that lists the differences between the different profiles.

[1] Interestingly, Apple's own Facetime uses the newer H.265 (HEVC) video codec. However right now (August 2017) there is no Apple-provided library that gives access to a HEVC codec to developers. This is expected to change at some point.

In talking about what video format the iPhone supports, a distinction should be made between what the hardware can support, and what the (much lower) limits are for playback when streaming over a network.

The only data given about hardware video support by Apple about the current generation of iPhones (SE, 6S, 6S Plus, 7, 7 Plus) is that they support

4K [3840x2160] video recording at 30 fps

1080p [1920x1080] HD video recording at 30 fps or 60 fps.

Obviously the phone can play back what it can record, so we can guess that 3840x2160 at 30 fps and 1920x1080 at 60 fps represent design limits of the phone. In addition, the screen size on the 6S Plus and 7 Plus is 1920x1080. So if you're interested in playback on the phone, it doesn't make sense to send over more pixels then the screen can draw.

However, streaming video is a different matter. Since networks are slow and video is huge, it's typical to use lower resolutions, bitrates, and frame rates than the device's theoretical maximum.

The most detailed document giving recommendations for streaming is TN2224 Best Practices for Creating and Deploying HTTP Live Streaming Media for Apple Devices. Figure 3 in that document gives a table of recommended streaming parameters:

Table of Apple recommended video encoding settings This table is from May 2016.

As you can see, Apple recommends the relatively low resolution of 768x432 as the highest recommended resolution for streaming over a cellular network. Of course this is just a recommendation and YMMV.

Audio

The question is about video, but that video generally has one or more audio tracks with it. The iPhone supports a few audio formats, but the most modern and by far most widely used is AAC. The iPhone 7 / 7 Plus, 6S Plus / 6S, SE all support AAC bitrates of 8 to 320 Kbps.

Container

The audio and video tracks go inside a container. The purpose of the container is to combine (interleave) the different tracks together, to store metadata, and to support seeking. The iPhone supports

  1. QuickTime .mov,
  2. MP4, and
  3. MPEG-TS.

The .mov and .mp4 file formats are closely related (.mp4 is in fact based on .mov), however .mp4 is an ISO standard that has much wider support.

As noted above, you have to use MPEG-TS for videos longer than 10 minutes.

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

How to get JSON from URL in JavaScript?

_x000D_
_x000D_
async function fetchDataAsync() {_x000D_
    const response = await fetch('paste URL');_x000D_
    console.log(await response.json())_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
fetchDataAsync();
_x000D_
_x000D_
_x000D_

Get current time in seconds since the Epoch on Linux, Bash

use this bash script (my ~/bin/epoch):

#!/bin/bash

# get seconds since epoch
test "x$1" == x && date +%s && exit 0

# or convert epoch seconds to date format (see "man date" for options)
EPOCH="$1"
shift
date -d @"$EPOCH" "$@"

Jquery select change not firing

For me perfectly fork this code.

$('#dom_object_id').on('change paste keyup', function(){
    console.log($("#dom_object_id").val().length)
});

Key event for .on() function is "paste" to get changes dynamically

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

The main problem is port number used by another application.So you can change the port number to unused one as shown below.

In windows you can view the used port numbers used by different apps in windows task manager.

python manage.py runserver 127.0.0.1:portnumber
Ex: python manage.py runserver 127.0.0.1:8080

How to generate unique IDs for form labels in React?

You could use a library such as node-uuid for this to make sure you get unique ids.

Install using:

npm install node-uuid --save

Then in your react component add the following:

import {default as UUID} from "node-uuid";
import {default as React} from "react";

export default class MyComponent extends React.Component {   
  componentWillMount() {
    this.id = UUID.v4();
  }, 
  render() {
    return (
      <div>
        <label htmlFor={this.id}>My label</label>
        <input id={this.id} type="text"/>
      </div>
    );
  }   
}

How to ignore SSL certificate errors in Apache HttpClient 4.0

Just had to do this with the newer HttpClient 4.5 and it seems like they've deprecated a few things since 4.4 so here's the snippet that works for me and uses the most recent API:

final SSLContext sslContext = new SSLContextBuilder()
        .loadTrustMaterial(null, (x509CertChain, authType) -> true)
        .build();

return HttpClientBuilder.create()
        .setSSLContext(sslContext)
        .setConnectionManager(
                new PoolingHttpClientConnectionManager(
                        RegistryBuilder.<ConnectionSocketFactory>create()
                                .register("http", PlainConnectionSocketFactory.INSTANCE)
                                .register("https", new SSLConnectionSocketFactory(sslContext,
                                        NoopHostnameVerifier.INSTANCE))
                                .build()
                ))
        .build();

Java Constructor Inheritance

When you inherit from Super this is what in reality happens:

public class Son extends Super{

  // If you dont declare a constructor of any type, adefault one will appear.
  public Son(){
    // If you dont call any other constructor in the first line a call to super() will be placed instead.
    super();
  }

}

So, that is the reason, because you have to call your unique constructor, since"Super" doesn't have a default one.

Now, trying to guess why Java doesn't support constructor inheritance, probably because a constructor only makes sense if it's talking about concrete instances, and you shouldn't be able to create an instance of something when you don't know how it's defined (by polymorphism).

Concatenate multiple files but include filename as section headers

When there is more than one input file, the more command concatenates them and also includes each filename as a header.

To concatenate to a file:

more *.txt > out.txt

To concatenate to the terminal:

more *.txt | cat

Example output:

::::::::::::::
file1.txt
::::::::::::::
This is
my first file.
::::::::::::::
file2.txt
::::::::::::::
And this is my
second file.

git reset --hard HEAD leaves untracked files behind

The command you are looking for is git clean

How do I center text horizontally and vertically in a TextView?

Via .xml file gravity can be set to center as follows

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center"
    android:text="In the center"
/>

Via java following is the way you can solve your particular issue

textView1.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

how to run mysql in ubuntu through terminal

If you want to run your scripts, then

mysql -u root -p < yourscript.sql

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

You may be an administrator on the workstation, but that means nothing to SQL Server. Your login has to be a member of the sysadmin role in order to perform the actions in question. By default, the local administrators group is no longer added to the sysadmin role in SQL 2008 R2. You'll need to login with something else (sa for example) in order to grant yourself the permissions.

php static function

Calling non-static methods statically generates an E_STRICT level warning.

How to load a controller from another controller in codeigniter?

I came here because I needed to create a {{ render() }} function in Twig, to simulate Symfony2's behaviour. Rendering controllers from view is really cool to display independant widgets or ajax-reloadable stuffs.

Even if you're not a Twig user, you can still take this helper and use it as you want in your views to render a controller, using <?php echo twig_render('welcome/index', $param1, $param2, $_); ?>. This will echo everything your controller outputted.

Here it is:

helpers/twig_helper.php

<?php

if (!function_exists('twig_render'))
{

    function twig_render()
    {
        $args = func_get_args();
        $route = array_shift($args);
        $controller = APPPATH . 'controllers/' . substr($route, 0, strrpos($route, '/'));

        $explode = explode('/', $route);
        if (count($explode) < 2)
        {
            show_error("twig_render: A twig route is made from format: path/to/controller/action.");
        }

        if (!is_file($controller . '.php'))
        {
            show_error("twig_render: Controller not found: {$controller}");
        }
        if (!is_readable($controller . '.php'))
        {
            show_error("twig_render: Controller not readable: {$controller}");
        }
        require_once($controller . '.php');

        $class = ucfirst(reset(array_slice($explode, count($explode) - 2, 1)));
        if (!class_exists($class))
        {
            show_error("twig_render: Controller file exists, but class not found inside: {$class}");
        }

        $object = new $class();
        if (!($object instanceof CI_Controller))
        {
            show_error("twig_render: Class {$class} is not an instance of CI_Controller");
        }

        $method = $explode[count($explode) - 1];
        if (!method_exists($object, $method))
        {
            show_error("twig_render: Controller method not found: {$method}");
        }

        if (!is_callable(array($object, $method)))
        {
            show_error("twig_render: Controller method not visible: {$method}");
        }

        call_user_func_array(array($object, $method), $args);

        $ci = &get_instance();
        return $ci->output->get_output();
    }

}

Specific for Twig users (adapt this code to your Twig implementation):

libraries/Twig.php

$this->_twig_env->addFunction('render', new Twig_Function_Function('twig_render'));

Usage

{{ render('welcome/index', param1, param2, ...) }}

Java : How to determine the correct charset encoding of a stream

Which library to use?

As of this writing, they are three libraries that emerge:

I don't include Apache Any23 because it uses ICU4j 3.4 under the hood.

How to tell which one has detected the right charset (or as close as possible)?

It's impossible to certify the charset detected by each above libraries. However, it's possible to ask them in turn and score the returned response.

How to score the returned response?

Each response can be assigned one point. The more points a response have, the more confidence the detected charset has. This is a simple scoring method. You can elaborate others.

Is there any sample code?

Here is a full snippet implementing the strategy described in the previous lines.

public static String guessEncoding(InputStream input) throws IOException {
    // Load input data
    long count = 0;
    int n = 0, EOF = -1;
    byte[] buffer = new byte[4096];
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    while ((EOF != (n = input.read(buffer))) && (count <= Integer.MAX_VALUE)) {
        output.write(buffer, 0, n);
        count += n;
    }
    
    if (count > Integer.MAX_VALUE) {
        throw new RuntimeException("Inputstream too large.");
    }

    byte[] data = output.toByteArray();

    // Detect encoding
    Map<String, int[]> encodingsScores = new HashMap<>();

    // * GuessEncoding
    updateEncodingsScores(encodingsScores, new CharsetToolkit(data).guessEncoding().displayName());

    // * ICU4j
    CharsetDetector charsetDetector = new CharsetDetector();
    charsetDetector.setText(data);
    charsetDetector.enableInputFilter(true);
    CharsetMatch cm = charsetDetector.detect();
    if (cm != null) {
        updateEncodingsScores(encodingsScores, cm.getName());
    }

    // * juniversalchardset
    UniversalDetector universalDetector = new UniversalDetector(null);
    universalDetector.handleData(data, 0, data.length);
    universalDetector.dataEnd();
    String encodingName = universalDetector.getDetectedCharset();
    if (encodingName != null) {
        updateEncodingsScores(encodingsScores, encodingName);
    }

    // Find winning encoding
    Map.Entry<String, int[]> maxEntry = null;
    for (Map.Entry<String, int[]> e : encodingsScores.entrySet()) {
        if (maxEntry == null || (e.getValue()[0] > maxEntry.getValue()[0])) {
            maxEntry = e;
        }
    }

    String winningEncoding = maxEntry.getKey();
    //dumpEncodingsScores(encodingsScores);
    return winningEncoding;
}

private static void updateEncodingsScores(Map<String, int[]> encodingsScores, String encoding) {
    String encodingName = encoding.toLowerCase();
    int[] encodingScore = encodingsScores.get(encodingName);

    if (encodingScore == null) {
        encodingsScores.put(encodingName, new int[] { 1 });
    } else {
        encodingScore[0]++;
    }
}    

private static void dumpEncodingsScores(Map<String, int[]> encodingsScores) {
    System.out.println(toString(encodingsScores));
}

private static String toString(Map<String, int[]> encodingsScores) {
    String GLUE = ", ";
    StringBuilder sb = new StringBuilder();

    for (Map.Entry<String, int[]> e : encodingsScores.entrySet()) {
        sb.append(e.getKey() + ":" + e.getValue()[0] + GLUE);
    }
    int len = sb.length();
    sb.delete(len - GLUE.length(), len);

    return "{ " + sb.toString() + " }";
}

Improvements: The guessEncoding method reads the inputstream entirely. For large inputstreams this can be a concern. All these libraries would read the whole inputstream. This would imply a large time consumption for detecting the charset.

It's possible to limit the initial data loading to a few bytes and perform the charset detection on those few bytes only.

How to render a DateTime object in a Twig template

you can render in following way

{{ post.published_at|date("m/d/Y") }}

For more details can visit http://twig.sensiolabs.org/doc/filters/date.html

Reload an iframe with jQuery

with jquery you can use this:

$('#iframeid',window.parent.document).attr('src',$('#iframeid',window.parent.document).attr('src'));

Unable to run Java code with Intellij IDEA

My classes contained a main() method yet I was unable to see the Run option. That option was enabled once I marked a folder containing my class files as a source folder:

  1. Right click the folder containing your source
  2. Select Mark Directory as → Test Source Root

Some of the classes in my folder don't have a main() method, but I still see a Run option for those.

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.


Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

How do I get column datatype in Oracle with PL-SQL with low privileges?

Oracle: Get a list of the full datatype in your table:

select data_type || '(' || data_length || ')' 
from user_tab_columns where TABLE_NAME = 'YourTableName'

How to get the selected item of a combo box to a string variable in c#

Test this

  var selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
  MessageBox.Show(selected);

The real difference between "int" and "unsigned int"

The problem is that you invoked Undefined Behaviour.


When you invoke UB anything can happen.

The assignments are ok; there is an implicit conversion in the first line

int x = 0xFFFFFFFF;
unsigned int y = 0xFFFFFFFF;

However, the call to printf, is not ok

printf("%d, %d, %u, %u", x, y, x, y);

It is UB to mismatch the % specifier and the type of the argument.
In your case you specify 2 ints and 2 unsigned ints in this order by provide 1 int, 1 unsigned int, 1 int, and 1 unsigned int.


Don't do UB!

How can we draw a vertical line in the webpage?

<hr> is not from struts. It is just an HTML tag.

So, take a look here: http://www.microbion.co.uk/web/vertline.htm This link will give you a couple of tips.

How to empty a list in C#?

You can use the clear method

List<string> test = new List<string>();
test.Clear();

How to set or change the default Java (JDK) version on OS X?

This tool will do the work for you:

http://www.guigarage.com/2013/02/change-java-version-on-mac-os/

It's a simple JavaOne that can be used to define the current Java Version. The version can be used in a shell that is opened after a version was selected in the tool.

Rename file with Git

Do a git status to find out if your file is actually in your index or the commit.

It is easy as a beginner to misunderstand the index/staging area.

I view it as a 'progress pinboard'. I therefore have to add the file to the pinboard before I can commit it (i.e. a copy of the complete pinboard), I have to update the pinboard when required, and I also have to deliberately remove files from it when I've finished with them - simply creating, editing or deleting a file doesn't affect the pinboard. It's like 'storyboarding'.

Edit: As others noted, You should do the edits locally and then push the updated repo, rather than attempt to edit directly on github.

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

Microsoft now recommends using an IHttpClientFactory with the following benefits:

  • Provides a central location for naming and configuring logical HttpClient instances. For example, a client named github could be registered and configured to access GitHub. A default client can be registered for general access.
  • Codifies the concept of outgoing middleware via delegating handlers in HttpClient. Provides extensions for Polly-based middleware to take advantage of delegating handlers in HttpClient.
  • Manages the pooling and lifetime of underlying HttpClientMessageHandler instances. Automatic management avoids common DNS (Domain Name System) problems that occur when manually managing HttpClient lifetimes.
  • Adds a configurable logging experience (via ILogger) for all requests sent through clients created by the factory.

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1

Setup:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient();
        // Remaining code deleted for brevity.

POST example:

public class BasicUsageModel : PageModel
{
    private readonly IHttpClientFactory _clientFactory;

    public BasicUsageModel(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
    
    public async Task CreateItemAsync(TodoItem todoItem)
    {
        var todoItemJson = new StringContent(
            JsonSerializer.Serialize(todoItem, _jsonSerializerOptions),
            Encoding.UTF8,
            "application/json");
            
        var httpClient = _clientFactory.CreateClient();
        
        using var httpResponse =
            await httpClient.PostAsync("/api/TodoItems", todoItemJson);
    
        httpResponse.EnsureSuccessStatusCode();
    }

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#make-post-put-and-delete-requests

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I think AutoCAD hijacked mine. The solution which worked for me was to hijack it back. I got this from https://forums.autodesk.com/t5/navisworks-api/could-not-load-file-or-assembly-newtonsoft-json/td-p/7028055?profile.language=en - yeah, the Internet works in mysterious ways.

// in your initilizer ...
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

.....

private Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
    if (args.Name.Contains("Newtonsoft.Json"))
    {
        string assemblyFileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Newtonsoft.Json.dll";
        return Assembly.LoadFrom(assemblyFileName);
    }
    else
        return null;
}

How do I perform query filtering in django templates

For anyone looking for an answer in 2020. This worked for me.

In Views:

 class InstancesView(generic.ListView):
        model = AlarmInstance
        context_object_name = 'settings_context'
        queryset = Group.objects.all()
        template_name = 'insta_list.html'

        @register.filter
        def filter_unknown(self, aVal):
            result = aVal.filter(is_known=False)
            return result

        @register.filter
        def filter_known(self, aVal):
            result = aVal.filter(is_known=True)
            return result

In template:

{% for instance in alarm.qar_alarm_instances|filter_unknown:alarm.qar_alarm_instances %}

In pseudocode:

For each in model.child_object|view_filter:filter_arg

Hope that helps.

jquery - return value using ajax result on success

Although all the approaches regarding the use of async: false are not good because of its deprecation and stuck the page untill the request comes back. Thus here are 2 ways to do it:

1st: Return whole ajax response in a function and then make use of done function to capture the response when the request is completed.(RECOMMENDED, THE BEST WAY)

function getAjax(url, data){
    return $.ajax({
        type: 'POST',
        url : url,              
        data: data,
        dataType: 'JSON',
        //async: true,  //NOT NEEDED
        success: function(response) {
            //Data = response;
        }
    });
 }

CALL THE ABOVE LIKE SO:

getAjax(youUrl, yourData).done(function(response){
    console.log(response);
});

FOR MULTIPLE AJAX CALLS MAKE USE OF $.when :

$.when( getAjax(youUrl, yourData), getAjax2(yourUrl2, yourData2) ).done(function(response){
    console.log(response);
});

2nd: Store the response in a cookie and then outside of the ajax call get that cookie value.(NOT RECOMMENDED)

        $.ajax({
            type: 'POST',
            url : url,              
            data: data,
            //async: false,    // No need to use this
            success: function(response) {
                Cookies.set(name, response);
            }
        });

        // Outside of the ajax call
        var response = Cookies.get(name);

NOTE: In the exmple above jquery cookies library is used.It is quite lightweight and works as snappy. Here is the link https://github.com/js-cookie/js-cookie

Java - Change int to ascii

You can convert a number to ASCII in java. example converting a number 1 (base is 10) to ASCII.

char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));

Output:

Character: 1
Character: 49

What is the difference between smoke testing and sanity testing?

Smoke tests are tests which aim is to check if everything was build correctly. I mean here integration, connections. So you check from technically point of view if you can make wider tests. You have to execute some test cases and check if the results are positive.

Sanity tests in general have the same aim - check if we can make further test. But in sanity test you focus on business value so you execute some test cases but you check the logic.

In general people say smoke tests for both above because they are executed in the same time (sanity after smoke tests) and their aim is similar.

Matching an optional substring in a regex

This ought to work:

^\d+\s?(\([^\)]+\)\s?)?Z$

Haven't tested it though, but let me give you the breakdown, so if there are any bugs left they should be pretty straightforward to find:

First the beginning:

^ = beginning of string
\d+ = one or more decimal characters
\s? = one optional whitespace

Then this part:

(\([^\)]+\)\s?)?

Is actually:

(.............)?

Which makes the following contents optional, only if it exists fully

\([^\)]+\)\s?

\( = an opening bracket
[^\)]+ = a series of at least one character that is not a closing bracket
\) = followed by a closing bracket
\s? = followed by one optional whitespace

And the end is made up of

Z$

Where

Z = your constant string
$ = the end of the string

Remove Backslashes from Json Data in JavaScript

try this

var finalData = str.replace(/\\/g, '');

How do I check for vowels in JavaScript?

This is a rough RegExp function I would have come up with (it's untested)

function isVowel(char) {
    return /^[aeiou]$/.test(char.toLowerCase());
}

Which means, if (char.length == 1 && 'aeiou' is contained in char.toLowerCase()) then return true.

Tomcat request timeout

For anyone who doesn't like none of the solutions posted above like me then you can simply implement a timer yourself and stop the request execution by throwing a runtime exception. Something like below:

                  try 
                 {
                     timer.schedule(new TimerTask() {
                       @Override
                       public void run() {
                         timer.cancel();
                       }
                     }, /* specify time of the requst */ 1000);
                 }
                 catch(Exception e)
                 {
                   throw new RuntimeException("the request is taking longer than usual");
                 }

   

or preferably use the java guava timeLimiter here

javascript create empty array of a given size

If you want to create anonymous array with some values so you can use this syntax.

_x000D_
_x000D_
var arr = new Array(50).fill().map((d,i)=>++i)
console.log(arr)
_x000D_
_x000D_
_x000D_

Turn a single number into single digits Python

Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n first):

>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]

Updating this after many years in response to comments of this not working for powers of 10:

[(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][bool(math.log(n,10)%1):]

The issue is that with powers of 10 (and ONLY with these), an extra step is required. ---So we use the remainder in the log_10 to determine whether to remove the leading 0--- We can't exactly use this because floating-point math errors cause this to fail for some powers of 10. So I've decided to cross the unholy river into sin and call upon regex.

In [32]: n = 43

In [33]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[33]: [4, 3]

In [34]: n = 1000

In [35]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[35]: [1, 0, 0, 0]

What is .Net Framework 4 extended?

Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

* ASP.NET
* Advanced Windows Communication Foundation (WCF) functionality
* .NET Framework Data Provider for Oracle
* MSBuild for compiling

Activate tabpage of TabControl

For Windows Smart device (compact frame work ) (MC75-Motorola devices)

     mytabControl.SelectedIndex = 1

forEach loop Java 8 for Map entry set

HashMap<String,Integer> hm = new HashMap();

 hm.put("A",1);
 hm.put("B",2);
 hm.put("C",3);
 hm.put("D",4);

 hm.forEach((key,value)->{
     System.out.println("Key: "+key + " value: "+value);
 });

Run php script as daemon process

Another option is to use Upstart. It was originally developed for Ubuntu (and comes packaged with it by default), but is intended to be suitable for all Linux distros.

This approach is similar to Supervisord and daemontools, in that it automatically starts the daemon on system boot and respawns on script completion.

How to set it up:

Create a new script file at /etc/init/myphpworker.conf. Here is an example:

# Info
description "My PHP Worker"
author      "Jonathan"

# Events
start on startup
stop on shutdown

# Automatically respawn
respawn
respawn limit 20 5

# Run the script!
# Note, in this example, if your PHP script returns
# the string "ERROR", the daemon will stop itself.
script
    [ $(exec /usr/bin/php -f /path/to/your/script.php) = 'ERROR' ] && ( stop; exit 1; )
end script

Starting & stopping your daemon:

sudo service myphpworker start
sudo service myphpworker stop

Check if your daemon is running:

sudo service myphpworker status

Thanks

A big thanks to Kevin van Zonneveld, where I learned this technique from.

How to read file with space separated values in pandas

you can use regex as the delimiter:

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

'App not Installed' Error on Android

I faced this issue with my latest app release to playstore. The issue is combination of change of MainLauncher and app shortcut .

We have added a splash screen and our entry point is SplashActivity instead of MainActivity. So, people who has previous versions and have app shortcut on their home screen can't open the app. It always says something like App not installed toast. This doesn't happen on every launcher (For us it's more common on Samsungs).

Behind the scenes, App shortcut should be seamlessly update entry point from MainActivity to SplashActivity. But, for some reason many third party launchers are not obeying it. The fix is clear the shortcut and add it again.

If you havn't update your app yet in playstore, go through this article.

Beware when updating the launcher activity.

How do I update a Linq to SQL dbml file?

In the case of stored procedure update, you should delete it from the .dbml file and reinsert it again. But if the stored procedure have two paths (ex: if something; display some columns; else display some other columns), make sure the two paths have the same columns aliases!!! Otherwise only the first path columns will exist.

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

DATE: It is used for values with a date part but no time part. MySQL retrieves and displays DATE values in YYYY-MM-DD format. The supported range is 1000-01-01 to 9999-12-31.

DATETIME: It is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format. The supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59.

TIMESTAMP: It is also used for values that contain both date and time parts, and includes the time zone. TIMESTAMP has a range of 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC.

TIME: Its values are in HH:MM:SS format (or HHH:MM:SS format for large hours values). TIME values may range from -838:59:59 to 838:59:59. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).

create table with sequence.nextval in oracle

In Oracle 12c you can also declare an identity column

CREATE TABLE identity_test_tab (
  id          NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
  description VARCHAR2(30)
);

examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.

get and set in TypeScript

If you are working with TypeScript modules and are trying to add a getter that is exported, you can do something like this:

// dataStore.ts
export const myData: string = undefined;  // just for typing support
let _myData: string;  // for memoizing the getter results

Object.defineProperty(this, "myData", {
    get: (): string => {
        if (_myData === undefined) {
            _myData = "my data";  // pretend this took a long time
        }

        return _myData;
    },
});

Then, in another file you have:

import * as dataStore from "./dataStore"
console.log(dataStore.myData); // "my data"

Default SQL Server Port

The default port for SQL Server Database Engine is 1433.

And as a best practice it should always be changed after the installation. 1433 is widely known which makes it vulnerable to attacks.

Jquery in React is not defined

Isn't easier than doing like :

1- Install jquery in your project:

yarn add jquery

2- Import jquery and start playing with DOM:

import $ from 'jquery';

add item in array list of android

item=sp.getItemAtPosition(i).toString();
list.add(item);
adapter.notifyDataSetChanged () ;

look up ArrayAdapter.notifyDataSetChanged()

Get hours difference between two dates in Moment Js

Or you can do simply:

var a = moment('2016-06-06T21:03:55');//now
var b = moment('2016-05-06T20:03:55');

console.log(a.diff(b, 'minutes')) // 44700
console.log(a.diff(b, 'hours')) // 745
console.log(a.diff(b, 'days')) // 31
console.log(a.diff(b, 'weeks')) // 4

docs: here

How to delete session cookie in Postman?

Have you tried Clear Cache extension? Give it a try. It clears app cache, downloads, file systems, form data, history, local storage, passwords and much more, available in the Options settings.

Update: try this answer https://superuser.com/a/232794

I'm not sure of a way to do this in Postman. I used to close the whole browser and reset the server in order to authenticate again. Never tested logout because it was an API service.

Remove all stylings (border, glow) from textarea

try this:

textarea {
        border-style: none;
        border-color: Transparent;
        overflow: auto;
        outline: none;
      }

jsbin: http://jsbin.com/orozon/2/

How do I iterate over an NSArray?

For OS X 10.4.x and previous:

 int i;
 for (i = 0; i < [myArray count]; i++) {
   id myArrayElement = [myArray objectAtIndex:i];
   ...do something useful with myArrayElement
 }

For OS X 10.5.x (or iPhone) and beyond:

for (id myArrayElement in myArray) {
   ...do something useful with myArrayElement
}

Setting dropdownlist selecteditem programmatically

var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding));
ctx.SelectedIndex = ctx.Items.IndexOf(index);

OR

foreach (var listItem in ctx.Items)
  listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding);

Should work.. especially when using extended RAD controls in which FindByText/Value doesn't even exist!

Resize a large bitmap file to scaled output file on Android

Here is an article that takes a different approach to resizing. It will attempt to load the largest possible bitmap into memory based on available memory in the process and then perform the transforms.

http://bricolsoftconsulting.com/2012/12/07/handling-large-images-on-android/

Normalize data in pandas

You can use apply for this, and it's a bit neater:

import numpy as np
import pandas as pd

np.random.seed(1)

df = pd.DataFrame(np.random.randn(4,4)* 4 + 3)

          0         1         2         3
0  9.497381  0.552974  0.887313 -1.291874
1  6.461631 -6.206155  9.979247 -0.044828
2  4.276156  2.002518  8.848432 -5.240563
3  1.710331  1.463783  7.535078 -1.399565

df.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))

          0         1         2         3
0  0.515087  0.133967 -0.651699  0.135175
1  0.125241 -0.689446  0.348301  0.375188
2 -0.155414  0.310554  0.223925 -0.624812
3 -0.484913  0.244924  0.079473  0.114448

Also, it works nicely with groupby, if you select the relevant columns:

df['grp'] = ['A', 'A', 'B', 'B']

          0         1         2         3 grp
0  9.497381  0.552974  0.887313 -1.291874   A
1  6.461631 -6.206155  9.979247 -0.044828   A
2  4.276156  2.002518  8.848432 -5.240563   B
3  1.710331  1.463783  7.535078 -1.399565   B


df.groupby(['grp'])[[0,1,2,3]].apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))

     0    1    2    3
0  0.5  0.5 -0.5 -0.5
1 -0.5 -0.5  0.5  0.5
2  0.5  0.5  0.5 -0.5
3 -0.5 -0.5 -0.5  0.5

Shortest way to print current year in a website

<script type="text/javascript">document.write(new Date().getFullYear());</script>

msvcr110.dll is missing from computer error while installing PHP

I had installed PHP in IIS7 on Windows Server 2008 R2 using the Web Platform Installer. It did not work out of the box. I had to install the Visual C++ Redistributable for VS 2012 Update 4 (32bit) as found here http://www.microsoft.com/en-us/download/details.aspx?id=30679 .

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

Batch file to copy directories recursively

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /b

Windows Batch File Looping Through Directories to Process Files?

How to get URL parameter using jQuery or plain JavaScript?

This might be overkill, but there is a pretty popular library now available for parsing URIs, called URI.js.

Example

_x000D_
_x000D_
var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow";_x000D_
var components = URI.parse(uri);_x000D_
var query = URI.parseQuery(components['query']);_x000D_
document.getElementById("result").innerHTML = "URI = " + uri;_x000D_
document.getElementById("result").innerHTML += "<br>technology = " + query['technology'];_x000D_
_x000D_
// If you look in your console, you will see that this library generates a JS array for multi-valued queries!_x000D_
console.log(query['technology']);_x000D_
console.log(query['blog']);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script>_x000D_
_x000D_
<span id="result"></span>
_x000D_
_x000D_
_x000D_

Need to perform Wildcard (*,?, etc) search on a string using Regex

You may want to use WildcardPattern from System.Management.Automation assembly. See my answer here.

How to set the From email address for mailx command?

You can use the "-r" option to set the sender address:

mailx -r [email protected] -s ...

ORA-01882: timezone region not found

What happens is, that the JDBC client sends the timezone ID to the Server. The server needs to know that zone. You can check with

SELECT DISTINCT tzname FROM V$TIMEZONE_NAMES where tzname like 'Etc%';

I have some db servers which know about 'Etc/UTC' and 'UTC' (tzfile version 18) but others only know 'UTC' (tz version 11).

SELECT FILENAME,VERSION from V$TIMEZONE_FILE;

There is also different behavior on the JDBC client side. Starting with 11.2 the driver will sent the zone IDs if it is "known" to Oracle, whereas before it sent the time offset. The problem with this "sending of known IDs" is, that the client does not check what timezone version/content is present on the server but has its own list.

This is explained in Oracle Support Article [ID 1068063.1].

It seems it also depends on the Client OS, it was more likely that Etc/UTC fails with Ubuntu than RHEL or Windows. I guess this is due to some normalization but I haven't figured out what exactly.

Ansible: create a user with sudo privileges

Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

The answer to my question is at Ansible: best practice for maintaining list of sudoers.

The Ansible playbook code fragment looks like this from my problem:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user:
    name=deployer
    groups=wheel
    append=yes
    state=present
    createhome=yes

- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

And the best part is that the solution is idempotent. It doesn't add the line

%wheel ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

Swift Bridging Header import issue

Amongst the other fixes, I had the error come up when I tried to do Product->Archive. Turns out I had this :

Objective-C Bridging Header
  Debug (had the value)
  Release (had the value)
    Any architecture | Any SDK (this was blank - problem here!)

After setting it in that last line, it worked.

How can I align button in Center or right using IONIC framework?

Another Ionic way. Using this ion-buttons tag, and the right keyword puts all the buttons in this group to the right. I made some custom toggle buttons that i wanted on one line, but the group to be right justified.

_x000D_
_x000D_
<ion-buttons right>_x000D_
<button ....>1</button>_x000D_
<button ....>2</button>_x000D_
<button ....>3</button>_x000D_
</ion-buttons>
_x000D_
_x000D_
_x000D_

Alternate table row color using CSS?

You have the :nth-child() pseudo-class:

table tr:nth-child(odd) td{
    ...
}
table tr:nth-child(even) td{
    ...
}

In the early days of :nth-child() its browser support was kind of poor. That's why setting class="odd" became such a common technique. In late 2013 I'm glad to say that IE6 and IE7 are finally dead (or sick enough to stop caring) but IE8 is still around — thankfully, it's the only exception.

Groovy executing shell commands

To add one more important information to above provided answers -

For a process

def proc = command.execute();

always try to use

def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)

rather than

def output = proc.in.text;

to capture the outputs after executing commands in groovy as the latter is a blocking call (SO question for reason).

SQL Server 2008 - Help writing simple INSERT Trigger

cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.

You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.

how to set the query timeout from SQL connection string

you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend

Command to collapse all sections of code?

If you mean shortcut then

CTRL + M + M: This one will collapse the region your cursor is at whether its a method, namespace or whatever for collapsing code blocks, regions and methods. The first will collapse only the block/method or region your cursor is at while the second will collapse the entire region you are at.

http://www.dev102.com/2008/05/06/11-more-visual-studio-shortcuts-you-should-know/

Environment variable in Jenkins Pipeline

You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).

From the documentation:

Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):

env.MYTOOL_VERSION = '1.33'
node {
  sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}

These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.

For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job enter image description here

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

Removing All Items From A ComboBox?

You need to remove each one individually unfortunately:

       For i = 1 To ListBox1.ListCount

           'Remove an item from the ListBox using ListBox1.RemoveItem 
       Next i

Update - I don't know why my answer did not include the full solution:

For i = ListBox1.ListCount - 1 to 0 Step - 1 
        ListBox1.RemoveItem i 
Next i 

Can you write virtual functions / methods in Java?

All non-private instance methods are virtual by default in Java.

In C++, private methods can be virtual. This can be exploited for the non-virtual-interface (NVI) idiom. In Java, you'd need to make the NVI overridable methods protected.

From the Java Language Specification, v3:

8.4.8.1 Overriding (by Instance Methods) An instance method m1 declared in a class C overrides another instance method, m2, declared in class A iff all of the following are true:

  1. C is a subclass of A.
  2. The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
  3. Either * m2 is public, protected or declared with default access in the same package as C, or * m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.

Tablix: Repeat header rows on each page not working - Report Builder 3.0

How I fixed this issue was I manually changed the code behind (from the menu View/code). The section below should have as many number of pairs <TablixMember> </TablixMember> as the number of rows are in the tablix. In my case I had more pairs <TablixMember> </TablixMember>than the number of rows in the tablix. Also if you go to "Advanced mode" (to the right of "Column Groups") the number of static lines behind the "Row groups" should be equal to the number of rows in the tablix. The way to make it equal is changing the code.

<TablixRowHierarchy>
      <TablixMembers>
        <TablixMember>
          <KeepWithGroup>After</KeepWithGroup>
          <RepeatOnNewPage>true</RepeatOnNewPage>
        </TablixMember>
        <TablixMember>
          <Group Name="Detail" />
        </TablixMember>
      </TablixMembers>
    </TablixRowHierarchy>

Lua - Current time in milliseconds

If you're using OpenResty then it provides for in-built millisecond time accuracy through the use of its ngx.now() function. Although if you want fine grained millisecond accuracy then you may need to call ngx.update_time() first. Or if you want to go one step further...

If you are using luajit enabled environment, such as OpenResty, then you can also use ffi to access C based time functions such as gettimeofday() e.g: (Note: The pcall check for the existence of struct timeval is only necessary if you're running it repeatedly e.g. via content_by_lua_file in OpenResty - without it you run into errors such as attempt to redefine 'timeval')

if pcall(ffi.typeof, "struct timeval") then
        -- check if already defined.
else
        -- undefined! let's define it!
        ffi.cdef[[
           typedef struct timeval {
                long tv_sec;
                long tv_usec;
           } timeval;

        int gettimeofday(struct timeval* t, void* tzp);
]]
end
local gettimeofday_struct = ffi.new("struct timeval")
local function gettimeofday()
        ffi.C.gettimeofday(gettimeofday_struct, nil)
        return tonumber(gettimeofday_struct.tv_sec) * 1000000 + tonumber(gettimeofday_struct.tv_usec)
end

Then the new lua gettimeofday() function can be called from lua to provide the clock time to microsecond level accuracy.

Indeed, one could take a similar approaching using clock_gettime() to obtain nanosecond accuracy.

New to unit testing, how to write great tests?

My tests just seems so tightly bound to the method (testing all codepath, expecting some inner methods to be called a number of times, with certain arguments), that it seems that if I ever refactor the method, the tests will fail even if the final behavior of the method did not change.

I think you are doing it wrong.

A unit test should:

  • test one method
  • provide some specific arguments to that method
  • test that the result is as expected

It should not look inside the method to see what it is doing, so changing the internals should not cause the test to fail. You should not directly test that private methods are being called. If you are interested in finding out whether your private code is being tested then use a code coverage tool. But don't get obsessed by this: 100% coverage is not a requirement.

If your method calls public methods in other classes, and these calls are guaranteed by your interface, then you can test that these calls are being made by using a mocking framework.

You should not use the method itself (or any of the internal code it uses) to generate the expected result dynamically. The expected result should be hard-coded into your test case so that it does not change when the implementation changes. Here's a simplified example of what a unit test should do:

testAdd()
{
    int x = 5;
    int y = -2;
    int expectedResult = 3;
    Calculator calculator = new Calculator();
    int actualResult = calculator.Add(x, y);
    Assert.AreEqual(expectedResult, actualResult);
}

Note that how the result is calculated is not checked - only that the result is correct. Keep adding more and more simple test cases like the above until you have have covered as many scenarios as possible. Use your code coverage tool to see if you have missed any interesting paths.

Compression/Decompression string with C#

With the advent of .NET 4.0 (and higher) with the Stream.CopyTo() methods, I thought I would post an updated approach.

I also think the below version is useful as a clear example of a self-contained class for compressing regular strings to Base64 encoded strings, and vice versa:

public static class StringCompression
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

Here’s another approach using the extension methods technique to extend the String class to add string compression and decompression. You can drop the class below into an existing project and then use thusly:

var uncompressedString = "Hello World!";
var compressedString = uncompressedString.Compress();

and

var decompressedString = compressedString.Decompress();

To wit:

public static class Extensions
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(this string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(this string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

How do I set a path in Visual Studio?

You have a couple of options:

  • You can add the path to the DLLs to the Executable files settings under Tools > Options > Projects and Solutions > VC++ Directories (but only for building, for executing or debugging here)
  • You can add them in your global PATH environment variable
  • You can start Visual Studio using a batch file as I described here and manipulate the path in that one
  • You can copy the DLLs into the executable file's directory :-)

How can I create a link to a local file on a locally-run web page?

If you are running IIS on your PC you can add the directory that you are trying to reach as a Virtual Directory. To do this you right-click on your Site in ISS and press "Add Virtual Directory". Name the virtual folder. Point the virtual folder to your folder location on your local PC. You also have to supply credentials that has privileges to access the specific folder eg. HOSTNAME\username and password. After that you can access the file in the virtual folder as any other file on your site.

http://sitename.com/virtual_folder_name/filename.fileextension

By the way, this also works with Chrome that otherwise does not accept the file-protocol file://

Hope this helps someone :)

Why does JSHint throw a warning if I am using const?

You can add a file named .jshintrc in your app's root with the following content to apply this setting for the whole solution:

{
    "esversion": 6
}

James' answer suggests that you can add a comment /*jshint esversion: 6 */ for each file, but it is more work than necessary if you need to control many files.

Create a unique number with javascript time

Easy and always get unique value :

const uniqueValue = (new Date()).getTime() + Math.trunc(365 * Math.random());
**OUTPUT LIKE THIS** : 1556782842762

How to select the last record from MySQL table using SQL syntax

SELECT * FROM your_table ORDER BY id ASC LIMIT 0, 1

The ASC will return resultset in ascending order thereby leaving you with the latest or most recent record. The DESC counterpart will do the exact opposite. That is, return the oldest record.

Multiple line code example in Javadoc comment

Enclose your multiline code with <pre></pre> tags.

Signed to unsigned conversion in C - is it always safe?

As was previously answered, you can cast back and forth between signed and unsigned without a problem. The border case for signed integers is -1 (0xFFFFFFFF). Try adding and subtracting from that and you'll find that you can cast back and have it be correct.

However, if you are going to be casting back and forth, I would strongly advise naming your variables such that it is clear what type they are, eg:

int iValue, iResult;
unsigned int uValue, uResult;

It is far too easy to get distracted by more important issues and forget which variable is what type if they are named without a hint. You don't want to cast to an unsigned and then use that as an array index.

Tools for creating Class Diagrams

Some time ago I used DIA - free and platform-independent. It was ok. Now I use Enterprise Architect but it's not free.

Formatting MM/DD/YYYY dates in textbox in VBA

You could use an input mask on the text box, too. If you set the mask to ##/##/#### it will always be formatted as you type and you don't need to do any coding other than checking to see if what was entered was a true date.

Which just a few easy lines

txtUserName.SetFocus
If IsDate(txtUserName.text) Then
    Debug.Print Format(CDate(txtUserName.text), "MM/DD/YYYY")
Else
    Debug.Print "Not a real date"
End If

UTF-8 text is garbled when form is posted as multipart/form-data

I had the same problem using Apache commons-fileupload. I did not find out what causes the problems especially because I have the UTF-8 encoding in the following places: 1. HTML meta tag 2. Form accept-charset attribute 3. Tomcat filter on every request that sets the "UTF-8" encoding

-> My solution was to especially convert Strings from ISO-8859-1 (or whatever is the default encoding of your platform) to UTF-8:

new String (s.getBytes ("iso-8859-1"), "UTF-8");

hope that helps

Edit: starting with Java 7 you can also use the following:

new String (s.getBytes (StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

There is no argument given that corresponds to the required formal parameter - .NET Error

In the constructor of

 public class ErrorEventArg : EventArgs

You have to add "base" as follows:

    public ErrorEventArg(string errorMsg, string lastQuery) : base (string errorMsg, string lastQuery)
    {
        ErrorMsg = errorMsg;
        LastQuery = lastQuery;
    }

That solved it for me

Is it possible to decrypt SHA1

SHA1 is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.

However, breaking a SHA1 hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.

So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.

As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod eliminate information from your input. Suppose you calculate mod 5 and you get 0. What was the input? Was it 0, 5 or 500? You see, you can't really 'go back' in this case.

Get a random boolean in python?

random.choice([True, False])

would also work.

What is the difference between json.dump() and json.dumps() in python?

The functions with an s take string parameters. The others take file streams.

Is there any quick way to get the last two characters in a string?

theString.substring(theString.length() - 2)

Capturing TAB key in text box

I would advise against changing the default behaviour of a key. I do as much as possible without touching a mouse, so if you make my tab key not move to the next field on a form I will be very aggravated.

A shortcut key could be useful however, especially with large code blocks and nesting. Shift-TAB is a bad option because that normally takes me to the previous field on a form. Maybe a new button on the WMD editor to insert a code-TAB, with a shortcut key, would be possible?

Are there dictionaries in php?

No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?

$array = array(
    "foo" => "bar",
    "bar" => "foo"
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

The following line is allowed with the above array but would give an error if it was a dictionary.

print $array[0]

Python has both arrays and dictionaries.

How can I customize the tab-to-space conversion factor?

I had to do a lot of settings edits like the previous answers, so I don't know which made it work after a lot of modifications.

Nothing worked until I closed and openen my IDE, but the last three things I did was disable the lonefy.vscode-js-css-html-formatter, "html.format.enable": true, and restart Visual Studio.

{
    "editor.suggestSelection": "first",
    "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
    "workbench.colorTheme": "Default Light+",
    "[html]": {
        "editor.defaultFormatter": "vscode.html-language-features",
        "editor.tabSize": 2,
        "editor.detectIndentation": false,
        "editor.insertSpaces": true
    },
    "typescript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": true,
    "editor.tabSize": 2,
    "typescript.format.insertSpaceAfterConstructor": true,
    "files.autoSave": "afterDelay",
    "html.format.indentHandlebars": true,
    "html.format.indentInnerHtml": true,
    "html.format.enable": true,
    "editor.detectIndentation": false,
    "editor.insertSpaces": true,
}

Pandas dataframe fillna() only some columns in place

You can avoid making a copy of the object using Wen's solution and inplace=True:

df.fillna({'a':0, 'b':0}, inplace=True)
print(df)

Which yields:

     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

Extract the first (or last) n characters of a string

If you are coming from Microsoft Excel, the following functions will be similar to LEFT(), RIGHT(), and MID() functions.


# This counts from the left and then extract n characters

str_left <- function(string, n) {
  substr(string, 1, n)
}



# This counts from the right and then extract n characters

str_right <- function(string, n) {
  substr(string, nchar(string) - (n - 1), nchar(string))
}


# This extract characters from the middle

str_mid <- function(string, from = 2, to = 5){
  
  substr(string, from, to)
  }

Examples:

x <- "some text in a string"
str_left(x, 4)
[1] "some"

str_right(x, 6)
[1] "string"

str_mid(x, 6, 9)
[1] "text"

Using FFmpeg in .net?

The original question is now more than 5 years old. In the meantime there is now a solution for a WinRT solution from ffmpeg and an integration sample from Microsoft.

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

The easiest is probably to create a PKCS#12 file using OpenSSL:

openssl pkcs12 -export -in abc.crt -inkey abc.key -out abc.p12

You should be able to use the resulting file directly using the PKCS12 keystore type.

If you really need to, you can convert it to JKS using keytool -importkeystore (available in keytool from Java 6):

keytool -importkeystore -srckeystore abc.p12 \
        -srcstoretype PKCS12 \
        -destkeystore abc.jks \
        -deststoretype JKS

How to find the array index with a value?

It is possible to use a ES6 function Array.prototype.findIndex.

MDN says:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

var fooArray = [5, 10, 15, 20, 25];
console.log(fooArray.findIndex(num=> { return num > 5; }));

// expected output: 1

Find an index by object property.

To find an index by object property:

yourArray.findIndex(obj => obj['propertyName'] === yourValue)

For example, there is a such array:

let someArray = [
    { property: 'OutDate' },
    { property: 'BeginDate'},
    { property: 'CarNumber' },
    { property: 'FirstName'}
];

Then, code to find an index of necessary property looks like that:

let carIndex = someArray.findIndex( filterCarObj=> 
    filterCarObj['property'] === 'CarNumber');

How to register multiple servlets in web.xml in one Spring application

As explained in this thread on the cxf-user mailing list, rather than having the CXFServlet load its own spring context from user-webservice-servlet.xml, you can just load the whole lot into the root context. Rename your existing user-webservice-servlet.xml to some other name (e.g. user-webservice-beans.xml) then change your contextConfigLocation parameter to something like:

<servlet>
  <servlet-name>myservlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>myservlet</servlet-name>
  <url-pattern>*.htm</url-pattern>
</servlet-mapping>

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
    /WEB-INF/applicationContext.xml
    /WEB-INF/user-webservice-beans.xml
  </param-value>
</context-param>

<servlet>
  <servlet-name>user-webservice</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>user-webservice</servlet-name>
  <url-pattern>/UserService/*</url-pattern>
</servlet-mapping>

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

If you have saved the excel file in the same folder as your python program (relative paths) then you just need to mention sheet number along with file name.

Example:

 data = pd.read_excel("wt_vs_ht.xlsx", "Sheet2")
 print(data)
 x = data.Height
 y = data.Weight
 plt.plot(x,y,'x')
 plt.show()

Synchronous request in Node.js

Super Request

This is another synchronous module that is based off of request and uses promises. Super simple to use, works well with mocha tests.

npm install super-request

request("http://domain.com")
    .post("/login")
    .form({username: "username", password: "password"})
    .expect(200)
    .expect({loggedIn: true})
    .end() //this request is done 
    //now start a new one in the same session 
    .get("/some/protected/route")
    .expect(200, {hello: "world"})
    .end(function(err){
        if(err){
            throw err;
        }
    });

Open Source Alternatives to Reflector?

The main reason I used Reflector (and, I think, the main reason most people used it) was for its decompiler: it can translate a method's IL back into source code.

On that count, Monoflector would be the project to watch. It uses Cecil, which does the reflection, and Cecil.Decompiler, which does the decompilation. But Monoflector layers a UI on top of both libraries, which should give you a very good idea of how to use the API.

Monoflector is also a decent alternative to Reflector outright. It lets you browse the types and decompile the methods, which is 99% of what people used Reflector for. It's very rough around the edges, but I'm thinking that will change quickly.

How do I get the current date and time in PHP?

Here are some characters that are commonly used for times:

  • d - Represents the day of the month (01 to 31)

  • m - Represents a month (01 to 12)

  • Y - Represents a year (in four digits)

  • l (lowercase 'L') - Represents the day of the week

  • H - 24-hour format of an hour (00 to 23)

  • h - 12-hour format of an hour with leading zeros (01 to 12)

  • i - Minutes with leading zeros (00 to 59)

  • s - Seconds with leading zeros (00 to 59)

  • a - Lowercase Ante meridiem and Post meridiem (am or pm)

example :

echo "Today " . date("Y/m/d") ;
echo "time " . date("h:i:sa");

Group by with union mysql select query

Try this EDITED:

(SELECT COUNT(motorbike.owner_id),owner.name,transport.type FROM transport,owner,motorbike WHERE transport.type='motobike' AND owner.owner_id=motorbike.owner_id AND transport.type_id=motorbike.motorbike_id GROUP BY motorbike.owner_id)

UNION ALL

(SELECT COUNT(car.owner_id),owner.name,transport.type FROM transport,owner,car WHERE transport.type='car' AND owner.owner_id=car.owner_id AND transport.type_id=car.car_id GROUP BY car.owner_id)

Exception: "URI formats are not supported"

     string ImagePath = "";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
        string a = "";
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
            Stream receiveStream = response.GetResponseStream();
            if (receiveStream.CanRead)
            { a = "OK"; }
        }

        catch { }

PreparedStatement setNull(..)

preparedStatement.setNull(index, java.sql.Types.NULL);

that should work for any type. Though in some cases failure happens on the server-side, like: for SQL:

COALESCE(?, CURRENT_TIMESTAMP)

Oracle 18XE fails with the wrong type: expected DATE, got STRING -- that is a perfectly valid failure;

Bottom line: it is good to know the type if you call .setNull()

Relative frequencies / proportions with dplyr

Try this:

mtcars %>%
  group_by(am, gear) %>%
  summarise(n = n()) %>%
  mutate(freq = n / sum(n))

#   am gear  n      freq
# 1  0    3 15 0.7894737
# 2  0    4  4 0.2105263
# 3  1    4  8 0.6153846
# 4  1    5  5 0.3846154

From the dplyr vignette:

When you group by multiple variables, each summary peels off one level of the grouping. That makes it easy to progressively roll-up a dataset.

Thus, after the summarise, the last grouping variable specified in group_by, 'gear', is peeled off. In the mutate step, the data is grouped by the remaining grouping variable(s), here 'am'. You may check grouping in each step with groups.

The outcome of the peeling is of course dependent of the order of the grouping variables in the group_by call. You may wish to do a subsequent group_by(am), to make your code more explicit.

For rounding and prettification, please refer to the nice answer by @Tyler Rinker.

Format telephone and credit card numbers in AngularJS

Angular-ui has a directive for masking input. Maybe this is what you want for masking (unfortunately, the documentation isn't that great):

http://angular-ui.github.com/

I don't think this will help with obfuscating the credit card number, though.

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

Try negation operator ! before $(this):

if (!$(this).parent().next().is('ul')){

Getting activity from context in android

Never ever use getApplicationContext() with views.

It should always be activity's context, as the view is attached to activity. Also, you may have a custom theme set, and when using application's context, all theming will be lost. Read more about different versions of contexts here.

C# equivalent to Java's charAt()?

You can index into a string in C# like an array, and you get the character at that index.

Example:

In Java, you would say

str.charAt(8);

In C#, you would say

str[8];

jQuery Call to WebService returns "No Transport" error

Add this: jQuery.support.cors = true;

It enables cross-site scripting in jQuery (introduced after 1.4x, I believe).

We were using a really old version of jQuery (1.3.2) and swapped it out for 1.6.1. Everything was working, except .ajax() calls. Adding the above line fixed the problem.

How to create SPF record for multiple IPs?

The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

Convert List to Pandas Dataframe Column

You can directly call the

pd.DataFrame()

method and pass your list as parameter.

l = ['Thanks You','Its fine no problem','Are you sure']
pd.DataFrame(l)

Output:

                      0
0            Thanks You
1   Its fine no problem
2          Are you sure

And if you have multiple lists and you want to make a dataframe out of it.You can do it as following:

import pandas as pd
names =["A","B","C","D"]
salary =[50000,90000,41000,62000]
age = [24,24,23,25]
data = pd.DataFrame([names,salary,age]) #Each list would be added as a row
data = data.transpose() #To Transpose and make each rows as columns
data.columns=['Names','Salary','Age'] #Rename the columns
data.head()

Output:

    Names   Salary  Age
0       A    50000   24
1       B    90000   24
2       C    41000   23
3       D    62000   25

A general tree implementation?

I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.

Hope it is of use,

Ok, here's the code:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name, self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name, self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

extracting days from a numpy.timedelta64 value

Suppose you have a timedelta series:

import pandas as pd
from datetime import datetime
z = pd.DataFrame({'a':[datetime.strptime('20150101', '%Y%m%d')],'b':[datetime.strptime('20140601', '%Y%m%d')]})

td_series = (z['a'] - z['b'])

One way to convert this timedelta column or series is to cast it to a Timedelta object (pandas 0.15.0+) and then extract the days from the object:

td_series.astype(pd.Timedelta).apply(lambda l: l.days)

Another way is to cast the series as a timedelta64 in days, and then cast it as an int:

td_series.astype('timedelta64[D]').astype(int)

How to squash all git commits into one?

To do this, you can reset you local git repository to the first commit hashtag, so all your changes after that commit will be unstaged, then you can commit with --amend option.

git reset your-first-commit-hashtag
git add .
git commit --amend

And then edit the first commit nam if needed and save file.

How do I auto-resize an image to fit a 'div' container?

You have to tell the browser the height of where you are placing it:

.example {
    height: 220px; /* DEFINE HEIGHT */
    background: url('../img/example.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
}

Loop code for each file in a directory

Try GLOB()

$dir = "/etc/php5/*";  

// Open a known directory, and proceed to read its contents  
foreach(glob($dir) as $file)  
{  
    echo "filename: $file : filetype: " . filetype($file) . "<br />";  
}  

Fatal error: Call to undefined function mysqli_connect()

There is no error in the, but the mysqli PHP extension is not installed on your machine. Please contact your service provider to fix this issue.

How to increase the clickable area of a <a> tag button?

Big thanks to the contributors to the answers here, it pointed me in the right direction.

For the Bootstrap4 users out there, this worked for me. Sets the a link (tap target) to correct size to pass the Lighthouse Site Audit on mobiles.

    <span class="small">
         <a class="d-inline position-relative p-3 m-n3" style="z-index: 1;" href="/AdvancedSearch" title="Advanced Site Search using extra optional filters">Advanced Site Search</a>
    </span>

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

This is if you see Java classes in red and get this error, "Cannot resolve symbol".

If you're importing projects into IntelliJ and none of the above solutions worked for you then give this a try. This is what worked for me when everything else failed.

Go to to your project folder and rename/delete the .idea folder which has the idea settings for your project. This would have been created from your old IntelliJ version. Once you have renamed/deleted the .idea folder, import your project into IntelliJ. You should not see any errors for your Java classes now. Hope this helped.

Removing duplicate elements from an array in Swift

You can always use a Dictionary, because a Dictionary can only hold unique values. For example:

var arrayOfDates: NSArray = ["15/04/01","15/04/01","15/04/02","15/04/02","15/04/03","15/04/03","15/04/03"]

var datesOnlyDict = NSMutableDictionary()
var x = Int()

for (x=0;x<(arrayOfDates.count);x++) {
    let date = arrayOfDates[x] as String
    datesOnlyDict.setValue("foo", forKey: date)
}

let uniqueDatesArray: NSArray = datesOnlyDict.allKeys // uniqueDatesArray = ["15/04/01", "15/04/03", "15/04/02"]

println(uniqueDatesArray.count)  // = 3

As you can see, the resulting array will not always be in 'order'. If you wish to sort/order the Array, add this:

var sortedArray = sorted(datesOnlyArray) {
(obj1, obj2) in

    let p1 = obj1 as String
    let p2 = obj2 as String
    return p1 < p2
}

println(sortedArray) // = ["15/04/01", "15/04/02", "15/04/03"]

.

Convert or extract TTC font to TTF - how to?

http://transfonter.org/ will do the job for you. Just upload your .ttc and it will give you a folder with all the fonttypes in .ttf files.

How to customize listview using baseadapter

I suggest using a custom Adapter, first create a Xml-file, for example layout/customlistview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" >
    <ImageView
        android:id="@+id/image"
        android:layout_alignParentRight="true"
        android:paddingRight="4dp" />
    <TextView
        android:id="@+id/title"
        android:layout_toLeftOf="@id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="23sp"
        android:maxLines="1" />
    <TextView
        android:id="@+id/subtitle"
        android:layout_toLeftOf="@id/image" android:layout_below="@id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /> 
</RelativeLayout>

Assuming you have a custom class like this

public class CustomClass {

    private long id;
    private String title, subtitle, picture;

    public CustomClass () {
    }

    public CustomClass (long id, String title, String subtitle, String picture) {
        this.id = id;
        this.title= title;
        this.subtitle= subtitle;
        this.picture= picture;
    }
    //add getters and setters
}

And a CustomAdapter.java uses the xml-layout

public class CustomAdapter extends ArrayAdapter {

private Context context;
private int resource;
private LayoutInflater inflater;

public CustomAdapter (Context context, List<CustomClass> values) { // or String[][] or whatever

    super(context, R.layout.customlistviewitem, values);

    this.context = context;
    this.resource = R.layout.customlistview;
    this.inflater = LayoutInflater.from(context);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    convertView = (RelativeLayout) inflater.inflate(resource, null);

    CustomClass item = (CustomClass) getItem(position);

    TextView textviewTitle = (TextView) convertView.findViewById(R.id.title);
    TextView textviewSubtitle = (TextView) convertView.findViewById(R.id.subtitle);
    ImageView imageview = (ImageView) convertView.findViewById(R.id.image);

    //fill the textviews and imageview with the values
    textviewTitle = item.getTtile();
    textviewSubtitle = item.getSubtitle();

    if (item.getAfbeelding() != null) {
        int imageResource = context.getResources().getIdentifier("drawable/" + item.getImage(), null, context.getPackageName());
        Drawable image = context.getResources().getDrawable(imageResource);
    }
    imageview.setImageDrawable(image);

    return convertView;
    }
}

Did you manage to do it? Feel free to ask if you want more info on something :)

EDIT: Changed the adapter to suit a List instead of just a List

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

if your JVM Cli is: -agentlib:jdwp=transport=dt_socket,address=60000,server=n,suspend=n and JDK version is 7, change "server=n" to "server=y" will be OK.

Converting Float to Dollars and Cents

you said that:

`mony = float(1234.5)
print(money)      #output is 1234.5
'${:,.2f}'.format(money)
print(money)

did not work.... Have you coded exactly that way? This should work (see the little difference):

money = float(1234.5)      #next you used format without printing, nor affecting value of "money"
amountAsFormattedString = '${:,.2f}'.format(money)
print( amountAsFormattedString )

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

How can I get selector from jQuery object

Try this:

$("*").click(function(event){
    console.log($(event.handleObj.selector));
 });

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

Don't worry... Its much easy to solve your problem. Just SET you SDK-LOCATION and JDK-LOCATION.

  • Click on Configure ( As Soon Android studio open )
  • Click Project Default
  • Click Project Structure
  • Clik Android Sdk Location

  • Select & Browse your Android SDK Location (Like: C:\Android\sdk)

  • Uncheck USE EMBEDDED JDK LOCATION

  • Set & Browse JDK Location, Like C:\Program Files\Java\jdk1.8.0_121

Remove carriage return from string

For VB.net

vbcrlf = environment.newline...

Dim MyString As String = "This is a Test" & Environment.NewLine & " This is the second line!"

Dim MyNewString As String = MyString.Replace(Environment.NewLine,String.Empty)

Check if a string is a date value

Here is an improved function that uses only Date.parse():

function isDate(s) {
    if(isNaN(s) && !isNaN(Date.parse(s)))
        return true;
    else return false;
}

Note: Date.parse() will parse numbers: for example Date.parse(1) will return a date. So here we check if s is not a number the, if it is a date.

Get time difference between two dates in seconds

<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();

var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>

Get a list of URLs from a site

Here is a list of sitemap generators (from which obviously you can get the list of URLs from a site): http://code.google.com/p/sitemap-generators/wiki/SitemapGenerators

Web Sitemap Generators

The following are links to tools that generate or maintain files in the XML Sitemaps format, an open standard defined on sitemaps.org and supported by the search engines such as Ask, Google, Microsoft Live Search and Yahoo!. Sitemap files generally contain a collection of URLs on a website along with some meta-data for these URLs. The following tools generally generate "web-type" XML Sitemap and URL-list files (some may also support other formats).

Please Note: Google has not tested or verified the features or security of the third party software listed on this site. Please direct any questions regarding the software to the software's author. We hope you enjoy these tools!

Server-side Programs

  • Enarion phpSitemapsNG (PHP)
  • Google Sitemap Generator (Linux/Windows, 32/64bit, open-source)
  • Outil en PHP (French, PHP)
  • Perl Sitemap Generator (Perl)
  • Python Sitemap Generator (Python)
  • Simple Sitemaps (PHP)
  • SiteMap XML Dynamic Sitemap Generator (PHP) $
  • Sitemap generator for OS/2 (REXX-script)
  • XML Sitemap Generator (PHP) $

CMS and Other Plugins:

  • ASP.NET - Sitemaps.Net
  • DotClear (Spanish)
  • DotClear (2)
  • Drupal
  • ECommerce Templates (PHP) $
  • Ecommerce Templates (PHP or ASP) $
  • LifeType
  • MediaWiki Sitemap generator
  • mnoGoSearch
  • OS Commerce
  • phpWebSite
  • Plone
  • RapidWeaver
  • Textpattern
  • vBulletin
  • Wikka Wiki (PHP)
  • WordPress

Downloadable Tools

  • GSiteCrawler (Windows)
  • GWebCrawler & Sitemap Creator (Windows)
  • G-Mapper (Windows)
  • Inspyder Sitemap Creator (Windows) $
  • IntelliMapper (Windows) $
  • Microsys A1 Sitemap Generator (Windows) $
  • Rage Google Sitemap Automator $ (OS-X)
  • Screaming Frog SEO Spider and Sitemap generator (Windows/Mac) $
  • Site Map Pro (Windows) $
  • Sitemap Writer (Windows) $
  • Sitemap Generator by DevIntelligence (Windows)
  • Sorrowmans Sitemap Tools (Windows)
  • TheSiteMapper (Windows) $
  • Vigos Gsitemap (Windows)
  • Visual SEO Studio (Windows)
  • WebDesignPros Sitemap Generator (Java Webstart Application)
  • Weblight (Windows/Mac) $
  • WonderWebWare Sitemap Generator (Windows)

Online Generators/Services

  • AuditMyPc.com Sitemap Generator
  • AutoMapIt
  • Autositemap $
  • Enarion phpSitemapsNG
  • Free Sitemap Generator
  • Neuroticweb.com Sitemap Generator
  • ROR Sitemap Generator
  • ScriptSocket Sitemap Generator
  • SeoUtility Sitemap Generator (Italian)
  • SitemapDoc
  • Sitemapspal
  • SitemapSubmit
  • Smart-IT-Consulting Google Sitemaps XML Validator
  • XML Sitemap Generator
  • XML-Sitemaps Generator

CMS with integrated Sitemap generators

  • Concrete5

Google News Sitemap Generators The following plugins allow publishers to update Google News Sitemap files, a variant of the sitemaps.org protocol that we describe in our Help Center. In addition to the normal properties of Sitemap files, Google News Sitemaps allow publishers to describe the types of content they publish, along with specifying levels of access for individual articles. More information about Google News can be found in our Help Center and Help Forums.

  • WordPress Google News plugin

Code Snippets / Libraries

  • ASP script
  • Emacs Lisp script
  • Java library
  • Perl script
  • PHP class
  • PHP generator script

If you believe that a tool should be added or removed for a legitimate reason, please leave a comment in the Webmaster Help Forum.

How to set the color of "placeholder" text?

For giving placeholder a color just use these lines of code:

::-webkit-input-placeholder { color: red; }
::-moz-placeholder {color: red; }
:-ms-input-placeholder { color: red; } 
:-o-input-placeholder { color: red; } 

Access images inside public folder in laravel

when you want to access images which are in public/images folder and if you want to access it without using laravel functions, use as follows:

<img src={{url('/images/photo.type')}} width="" height="" alt=""/>

This works fine.

Convert int to ASCII and back in Python

If multiple characters are bound inside a single integer/long, as was my issue:

s = '0123456789'
nchars = len(s)
# string to int or long. Type depends on nchars
x = sum(ord(s[byte])<<8*(nchars-byte-1) for byte in range(nchars))
# int or long to string
''.join(chr((x>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))

Yields '0123456789' and x = 227581098929683594426425L

How to delete last character in a string in C#?

string source;
// source gets initialized
string dest;
if (source.Length > 0)
{
    dest = source.Substring(0, source.Length - 1);
}

Rails how to run rake task

In rails 4.2 the above methods didn't work.

  1. Go to the Terminal.
  2. Change the directory to the location where your rake file is present.
  3. run rake task_name.
  4. In the above case, run rake iqmedier - will run only iqmedir task.
  5. run rake euroads - will run only the euroads task.
  6. To Run all the tasks in that file assign the following inside the same file and run rake all

    task :all => [:iqmedier, :euroads, :mikkelsen, :orville ] do #This will print all the tasks o/p on the screen 
    end
    

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

Confirmation dialog on ng-click - AngularJS

In today's date this solution works for me:

/**
 * A generic confirmation for risky actions.
 * Usage: Add attributes: ng-really-message="Are you sure"? ng-really-click="takeAction()" function
 */
angular.module('app').directive('ngReallyClick', [function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                var message = attrs.ngReallyMessage;
                if (message && confirm(message)) {
                    scope.$apply(attrs.ngReallyClick);
                }
            });
        }
    }
}]);

Credits:https://gist.github.com/asafge/7430497#file-ng-really-js

How do you create a yes/no boolean field in SQL server?

You can use the BIT field

To create new table:

CREATE TABLE Tb_Table1
(
ID              INT,
BitColumn       BIT DEFAULT 1
)

Adding Column in existing Table:

ALTER TABLE Tb_Table1 ADD BitColumn  BIT DEFAULT 1

To Insert record:

INSERT Tb_Table1 VALUES(11,0)

How can I remove punctuation from input text in Java?

If you don't want to use RegEx (which seems highly unnecessary given your problem), perhaps you should try something like this:

public String modified(final String input){
    final StringBuilder builder = new StringBuilder();
    for(final char c : input.toCharArray())
        if(Character.isLetterOrDigit(c))
            builder.append(Character.isLowerCase(c) ? c : Character.toLowerCase(c));
    return builder.toString();
}

It loops through the underlying char[] in the String and only appends the char if it is a letter or digit (filtering out all symbols, which I am assuming is what you are trying to accomplish) and then appends the lower case version of the char.

LaTeX package for syntax highlighting of code in various languages

You can use the listings package. It supports many different languages and there are lots of options for customising the output.

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[language=html]
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>Hello</body>
</html>
\end{lstlisting}
\end{document}

Javascript: Load an Image from url and display

You have to right idea generating the url based off of the input value. The only issue is you are using window.location.href. Setting window.location.href changes the url of the current window. What you probably want to do is change the src attribute of an image.

<html>
<body>
<form>
  <input type="text" value="" id="imagename">
  <input type="button" onclick="var image = document.getElementById('the-image'); image.src='http://webpage.com/images/'+document.getElementById('imagename').value +'.png'" value="GO">
</form>
<img id="the-image">
</body>
</html>

How to represent a DateTime in Excel

Some versions of Excel don't have date-time formats available in the standard pick lists, but you can just enter a custom format string such as yyyy-mm-dd hh:mm:ss by:

  1. Right click -> Format Cells
  2. Number tab
  3. Choose Category Custom
  4. Enter your custom format string into the "Type" field

This works on my Excel 2010

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

How can I require at least one checkbox be checked before a form can be submitted?

The issue with the accepted solution above is that is does not allow for the else condition on form submit (if a box has been selected), thereby preventing form submission - at least when I tried it.

I discovered another solution that effects the desired result more completely IMHO, here:

Making sure at least one checkbox is checked

Code as follows:

function valthis() {
var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
var isChecked = false;
    for (var i = 0; i < checkBoxes.length; i++) {
        if ( checkBoxes[i].checked ) {
            isChecked = true;
        };
    };
    if ( isChecked ) {
        alert( 'At least one checkbox checked!' );
        } else {
            alert( 'Please, check at least one checkbox!' );
        }   
}

Fiddle

That code & answer by Vell

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

How to change context root of a dynamic web project in Eclipse?

If you are running Tomcat from Eclipse, it doesn't use the configuration from your actual Tomcat installation. It uses the Tomcat configuration that it created and stored under "Servers" project. If you view your Eclipse workspace, you should see a project called "Servers". Expand that "Servers" project and you will come across server.xml. Open this file and scroll all the way to the bottom, and you should see something like this:-

<Context docBase="abc" path="/abc" reloadable="true" source="org.eclipse.jst.jee.server:abc"/>

Here, you can just change your project context path to something else.

Hope this helps.

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

If you are using MasterPages and Content pages in your app - you also have the option of putting the ScriptManager on the Masterpage and then every ContentPage that uses that MasterPage will NOT need a script manager added. If you need some of the special configurations of the ScriptManager - like javascript file references - you can use a ScriptManagerProxy control on the content page that needs it.

iOS 7 status bar overlapping UI

To address the issue of the status bar iOS7, we can use the following code to Cordova / PhoneGap:

function onDeviceReady() {
    if (parseFloat(window.device.version) === 7.0) {
          document.body.style.marginTop = "20px";
    }
}

document.addEventListener('deviceready', onDeviceReady, false);

Anyway Cordova 3.1 will soon fix that this and other issues for iOS7.

Create array of regex matches

In Java 9, you can now use Matcher#results() to get a Stream<MatchResult> which you can use to get a list/array of matches.

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
String[] matches = Pattern.compile("your regex here")
                          .matcher("string to search from here")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
                    // or .collect(Collectors.toList())

Iterating through a variable length array

You've specifically mentioned a "variable-length array" in your question, so neither of the existing two answers (as I write this) are quite right.

Java doesn't have any concept of a "variable-length array", but it does have Collections, which serve in this capacity. Any collection (technically any "Iterable", a supertype of Collections) can be looped over as simply as this:

Collection<Thing> things = ...;
for (Thing t : things) {
  System.out.println(t);
}

EDIT: it's possible I misunderstood what he meant by 'variable-length'. He might have just meant it's a fixed length but not every instance is the same fixed length. In which case the existing answers would be fine. I'm not sure what was meant.

How do I create a timer in WPF?

In WPF, you use a DispatcherTimer.

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();


private void dispatcherTimer_Tick(object sender, EventArgs e)
{
  // code goes here
}

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

in order to get the ^M character to match I had to visually select it and then use the OS copy to clipboard command to retrieve it. You can test it by doing a search for the character before trying the replace command.

/^M

should select the first bad line

:%s/^M/\r/g

will replace all the errant ^M with carriage returns.

This is as functions in MacVim, which is based on gvim 7.

EDIT:

Having this problem again on my Windows 10 machine, which has Ubuntu for Windows, and I think this is causing fileformat issues for vim. In this case changing the ff to unix, mac, or dos did nothing other than to change the ^M to ^J and back again.

The solution in this case:

:%s/\r$/ /g
:%s/ $//g

The reason I went this route is because I wanted to ensure I was being non-destructive with my file. I could have :%s/\r$//g but that would have deleted the carriage returns right out, and could have had unexpected results. Instead we convert the singular CR character, here a ^M character, into a space, and then remove all spaces at the end of lines (which for me is a desirable result regardless)

Sorry for reviving an old question that has long since been answered, but there seemed to be some confusion afoot and I thought I'd help clear some of that up since this is coming up high in google searches.

How to insert special characters into a database?

use mysql_real_escape_string

So what does mysql_real_escape_string do?

This PHP library function prepends backslashes to the following characters: \n, \r, \, \x00, \x1a, ‘ and “. The important part is that the single and double quotes are escaped, because these are the characters most likely to open up vulnerabilities.

Please inform yourself about sql_injection. You can use this link as a start

IN vs OR in the SQL WHERE Clause

OR makes sense (from readability point of view), when there are less values to be compared. IN is useful esp. when you have a dynamic source, with which you want values to be compared.

Another alternative is to use a JOIN with a temporary table.
I don't think performance should be a problem, provided you have necessary indexes.

Should operator<< be implemented as a friend or as a member function?

Just for completion sake, I would like to add that you indeed can create an operator ostream& operator << (ostream& os) inside a class and it can work. From what I know it's not a good idea to use it, because it's very convoluted and unintuitive.

Let's assume we have this code:

#include <iostream>
#include <string>

using namespace std;

struct Widget
{
    string name;

    Widget(string _name) : name(_name) {}

    ostream& operator << (ostream& os)
    {
        return os << name;
    }
};

int main()
{
    Widget w1("w1");
    Widget w2("w2");

    // These two won't work
    {
        // Error: operand types are std::ostream << std::ostream
        // cout << w1.operator<<(cout) << '\n';

        // Error: operand types are std::ostream << Widget
        // cout << w1 << '\n';
    }

    // However these two work
    {
        w1 << cout << '\n';

        // Call to w1.operator<<(cout) returns a reference to ostream&
        w2 << w1.operator<<(cout) << '\n';
    }

    return 0;
}

So to sum it up - you can do it, but you most probably shouldn't :)

How do I define and use an ENUM in Objective-C?

Apple provides a macro to help provide better code compatibility, including Swift. Using the macro looks like this.

typedef NS_ENUM(NSInteger, PlayerStateType) {
  PlayerStateOff,
  PlayerStatePlaying,
  PlayerStatePaused
};

Documented here

Is it possible to get all arguments of a function as single object inside that function?

ES6 allows a construct where a function argument is specified with a "..." notation such as

function testArgs (...args) {
 // Where you can test picking the first element
 console.log(args[0]); 
}

What is a monad?

Explaining "what is a monad" is a bit like saying "what is a number?" We use numbers all the time. But imagine you met someone who didn't know anything about numbers. How the heck would you explain what numbers are? And how would you even begin to describe why that might be useful?

What is a monad? The short answer: It's a specific way of chaining operations together.

In essence, you're writing execution steps and linking them together with the "bind function". (In Haskell, it's named >>=.) You can write the calls to the bind operator yourself, or you can use syntax sugar which makes the compiler insert those function calls for you. But either way, each step is separated by a call to this bind function.

So the bind function is like a semicolon; it separates the steps in a process. The bind function's job is to take the output from the previous step, and feed it into the next step.

That doesn't sound too hard, right? But there is more than one kind of monad. Why? How?

Well, the bind function can just take the result from one step, and feed it to the next step. But if that's "all" the monad does... that actually isn't very useful. And that's important to understand: Every useful monad does something else in addition to just being a monad. Every useful monad has a "special power", which makes it unique.

(A monad that does nothing special is called the "identity monad". Rather like the identity function, this sounds like an utterly pointless thing, yet turns out not to be... But that's another story™.)

Basically, each monad has its own implementation of the bind function. And you can write a bind function such that it does hoopy things between execution steps. For example:

  • If each step returns a success/failure indicator, you can have bind execute the next step only if the previous one succeeded. In this way, a failing step aborts the whole sequence "automatically", without any conditional testing from you. (The Failure Monad.)

  • Extending this idea, you can implement "exceptions". (The Error Monad or Exception Monad.) Because you're defining them yourself rather than it being a language feature, you can define how they work. (E.g., maybe you want to ignore the first two exceptions and only abort when a third exception is thrown.)

  • You can make each step return multiple results, and have the bind function loop over them, feeding each one into the next step for you. In this way, you don't have to keep writing loops all over the place when dealing with multiple results. The bind function "automatically" does all that for you. (The List Monad.)

  • As well as passing a "result" from one step to another, you can have the bind function pass extra data around as well. This data now doesn't show up in your source code, but you can still access it from anywhere, without having to manually pass it to every function. (The Reader Monad.)

  • You can make it so that the "extra data" can be replaced. This allows you to simulate destructive updates, without actually doing destructive updates. (The State Monad and its cousin the Writer Monad.)

  • Because you're only simulating destructive updates, you can trivially do things that would be impossible with real destructive updates. For example, you can undo the last update, or revert to an older version.

  • You can make a monad where calculations can be paused, so you can pause your program, go in and tinker with internal state data, and then resume it.

  • You can implement "continuations" as a monad. This allows you to break people's minds!

All of this and more is possible with monads. Of course, all of this is also perfectly possible without monads too. It's just drastically easier using monads.

How to read from stdin with fgets()?

If you want to concatenate the input, then replace printf("%s\n", buffer); with strcat(big_buffer, buffer);. Also create and initialize the big buffer at the beginning: char *big_buffer = new char[BIG_BUFFERSIZE]; big_buffer[0] = '\0';. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit: if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE). The modified program would look like this:

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

#define BUFFERSIZE 10
#define BIG_BUFFERSIZE 1024

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    char *big_buffer = new char[BIG_BUFFERSIZE];
    big_buffer[0] = '\0';
    printf("Enter a message: \n");
    while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
    {
        if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
        {
            strcat(big_buffer, buffer);
        }
    }
    return 0;
}

Ruby on Rails: how to render a string as HTML?

The html_safe version works well in Rails 4...

<%= "<center style=\"color: green; font-size: 1.1em\" > Administrators only </center>".html_safe if current_user.admin? %
>

Unexpected end of file error

Change the Platform of your C++ project to "x64" (or whichever platform you are targeting) instead of "Win32". This can be found in Visual Studio under Build -> Configuration Manager. Find your project in the list and change the Platform column. Don't forget to do this for all solution configurations.

How to get the sign, mantissa and exponent of a floating point number

Cast a pointer to the floating point variable as something like an unsigned int. Then you can shift and mask the bits to get each component.

float foo;
unsigned int ival, mantissa, exponent, sign;

foo = -21.4f;
ival = *((unsigned int *)&foo);
mantissa = ( ival & 0x7FFFFF);
ival = ival >> 23;
exponent = ( ival  & 0xFF );
ival = ival >> 8;
sign = ( ival & 0x01 );

Obviously you probably wouldn't use unsigned ints for the exponent and sign bits but this should at least give you the idea.

Error 1022 - Can't write; duplicate key in table

As others have mentioned, it's possible that the name for your constraint is already in use by another table in your DB. They must be unique across the database.

A good convention for naming foreign key constraints is:

fk_TableName_ColumnName

To investigate whether there's a possible clash, you can list all constraints used by your database with this query:

SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'YOUR_DB';

When I ran this query, I discovered I had previously made a temporary copy of a table and this copy was already using the constraint name I was attempting to use.

Where is Xcode's build folder?

In case of Debug Running

~/Library/Developer/Xcode/DerivedData/{your app}/Build/Products/Debug/{Project Name}.app/Contents/MacOS

You can find standalone executable file(Mach-O 64-bit executable x86_64)

How to add a button dynamically using jquery

the $("body").append(r) statement should be within the test function, also there was misplaced " in the test method

function test() {
    var r=$('<input/>').attr({
        type: "button",
        id: "field",
        value: 'new'
    });
    $("body").append(r);    
}

Demo: Fiddle

Update
In that case try a more jQuery-ish solution

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
          jQuery(function($){
              $('#mybutton').one('click', function(){
                  var r=$('<input/>').attr({
                      type: "button",
                      id: "field",
                      value: 'new'
                  });
                  $("body").append(r);   
              })
          })
        </script>
    </head>
    <body>
        <button id="mybutton">Insert after</button> 
    </body>
</html>

Demo: Plunker

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

Insert an item into sorted list in Python

# function to insert a number in an sorted list


def pstatement(value_returned):
    return print('new sorted list =', value_returned)


def insert(input, n):
    print('input list = ', input)
    print('number to insert = ', n)
    print('range to iterate is =', len(input))

    first = input[0]
    print('first element =', first)
    last = input[-1]
    print('last element =', last)

    if first > n:
        list = [n] + input[:]
        return pstatement(list)
    elif last < n:
        list = input[:] + [n]
        return pstatement(list)
    else:
        for i in range(len(input)):
            if input[i] > n:
                break
    list = input[:i] + [n] + input[i:]
    return pstatement(list)

# Input values
listq = [2, 4, 5]
n = 1

insert(listq, n)

Setting PATH environment variable in OSX permanently

You could also add this

if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

to ~/.bash_profile, then create ~/.bashrc where you can just add more paths to PATH. An example with .

export PATH=$PATH:.

Add a background image to shape in XML Android

I used the following for a drawable image with a circular background.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/colorAccent"/>
        </shape>
    </item>
    <item
        android:drawable="@drawable/ic_select"
        android:bottom="20dp"
        android:left="20dp"
        android:right="20dp"
        android:top="20dp"/>
</layer-list>

Here is what it looks like

enter image description here

Hope that helps someone out.