Programs & Examples On #Selenium fitnesse bridge

A FitNesse fixture that integrates the Selenium web test automation API with test specifications in a FitNesse wiki.

How to fix request failed on channel 0

Just rebooting a AWS instance works for me to clear the error "shell request failed on channel 0"

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

HSL to RGB color conversion

Unity3D C# Code from Mohsen's answer.

Here is the code from Mohsen's answer in C# targeted specifically for Unity3D. It was adapted from the C# answer given by Alec Thilenius above.

using UnityEngine;
using System.Collections;

public class ColorTools {

    /// <summary>
    /// Converts an HSL color value to RGB.
    /// Input: Vector4 ( X: [0.0, 1.0], Y: [0.0, 1.0], Z: [0.0, 1.0], W: [0.0, 1.0] )**strong text**
    /// Output: Color ( R: [0.0, 1.0], G: [0.0, 1.0], B: [0.0, 1.0], A: [0.0, 1.0] )
    /// </summary>
    /// <param name="hsl">Vector4 defining X = h, Y = s, Z = l, W = a. Ranges [0, 1.0]</param>
    /// <returns>RGBA Color. Ranges [0.0, 1.0]</returns>
    public static Color HslToRgba(Vector4 hsl)
    {
        float r, g, b;

        if (hsl.y == 0.0f)
            r = g = b = hsl.z;
        else
        {
            var q = hsl.z < 0.5f ? hsl.z * (1.0f + hsl.y) : hsl.z + hsl.y - hsl.z * hsl.y;
            var p = 2.0f * hsl.z - q;
            r = HueToRgb(p, q, hsl.x + 1.0f / 3.0f);
            g = HueToRgb(p, q, hsl.x);
            b = HueToRgb(p, q, hsl.x - 1.0f / 3.0f);
        }

        return new Color(r, g, b, hsl.w);
    }

    // Helper for HslToRgba
    private static float HueToRgb(float p, float q, float t)
    {
        if (t < 0.0f) t += 1.0f;
        if (t > 1.0f) t -= 1.0f;
        if (t < 1.0f / 6.0f) return p + (q - p) * 6.0f * t;
        if (t < 1.0f / 2.0f) return q;
        if (t < 2.0f / 3.0f) return p + (q - p) * (2.0f / 3.0f - t) * 6.0f;
        return p;
    }

    /// <summary>
    /// Converts an RGB color value to HSL.
    /// Input: Color ( R: [0.0, 1.0], G: [0.0, 1.0], B: [0.0, 1.0], A: [0.0, 1.0] )
    /// Output: Vector4 ( X: [0.0, 1.0], Y: [0.0, 1.0], Z: [0.0, 1.0], W: [0.0, 1.0] )
    /// </summary>
    /// <param name="rgba"></param>
    /// <returns></returns>
    public static Vector4 RgbaToHsl(Color rgba)
    {

        float max = (rgba.r > rgba.g && rgba.r > rgba.b) ? rgba.r : 
            (rgba.g > rgba.b) ? rgba.g : rgba.b;
        float min = (rgba.r < rgba.g && rgba.r < rgba.b) ? rgba.r : 
            (rgba.g < rgba.b) ? rgba.g : rgba.b;

        float h, s, l;
        h = s = l = (max + min) / 2.0f;

        if (max == min)
            h = s = 0.0f;
        else
        {
            float d = max - min;
            s = (l > 0.5f) ? d / (2.0f - max - min) : d / (max + min);

            if (rgba.r > rgba.g && rgba.r > rgba.b)
                h = (rgba.g - rgba.b) / d + (rgba.g < rgba.b ? 6.0f : 0.0f);

            else if (rgba.g > rgba.b)
                h = (rgba.b - rgba.r) / d + 2.0f;

            else
                h = (rgba.r - rgba.g) / d + 4.0f;

            h /= 6.0f;
        }

        return new Vector4(h, s, l, rgba.a);
    }

}

How to get error message when ifstream open fails

Following on @Arne Mertz's answer, as of C++11 std::ios_base::failure inherits from system_error (see http://www.cplusplus.com/reference/ios/ios_base/failure/), which contains both the error code and message that strerror(errno) would return.

std::ifstream f;

// Set exceptions to be thrown on failure
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);

try {
    f.open(fileName);
} catch (std::system_error& e) {
    std::cerr << e.code().message() << std::endl;
}

This prints No such file or directory. if fileName doesn't exist.

Handling JSON Post Request in Go

Please use json.Decoder instead of json.Unmarshal.

func test(rw http.ResponseWriter, req *http.Request) {
    decoder := json.NewDecoder(req.Body)
    var t test_struct
    err := decoder.Decode(&t)
    if err != nil {
        panic(err)
    }
    log.Println(t.Test)
}

Auto populate columns in one sheet from another sheet

Below code will look for last used row in sheet1 and copy the entire range from A1 upto last used row in column A to Sheet2 at exact same location.

Sub test()

    Dim lastRow As Long
    lastRow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
    Sheets("Sheet2").Range("A1:A" & lastRow).Value = Sheets("Sheet1").Range("A1:A" & lastRow).Value

End Sub

How to commit and rollback transaction in sql server?

Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.

Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ...... 

Preloading images with JavaScript

Try this I think this is better.

var images = [];
function preload() {
    for (var i = 0; i < arguments.length; i++) {
        images[i] = new Image();
        images[i].src = preload.arguments[i];
    }
}

//-- usage --//
preload(
    "http://domain.tld/gallery/image-001.jpg",
    "http://domain.tld/gallery/image-002.jpg",
    "http://domain.tld/gallery/image-003.jpg"
)

Source: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

How to remove the last character from a string?

// Remove n last characters  
// System.out.println(removeLast("Hello!!!333",3));

public String removeLast(String mes, int n) {
    return mes != null && !mes.isEmpty() && mes.length()>n
         ? mes.substring(0, mes.length()-n): mes;
}

// Leave substring before character/string  
// System.out.println(leaveBeforeChar("Hello!!!123", "1"));

public String leaveBeforeChar(String mes, String last) {
    return mes != null && !mes.isEmpty() && mes.lastIndexOf(last)!=-1
         ? mes.substring(0, mes.lastIndexOf(last)): mes;
}

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

http://localhost/phpMyAdmin/ unable to connect

http://localhost:(port number of phpmyadmin)/phpmyadmin/

For example: http://localhost:8080/phpmyadmin/

It works great!

Questions every good Database/SQL developer should be able to answer

  • What are the downsides of using adhoc/on-the-fly SQL statements and what would you do instead?

This area can have a huge impact on performance and security of the db. Get this wrong, and you could end up in a world of pain.

  • In what situations would you use adhoc/on-the-fly SQL statements?

Because there is always an exception to the rule :)

How to center a component in Material-UI and make it responsive?

Here is another option without a grid:

<div
    style={{
        position: 'absolute', 
        left: '50%', 
        top: '50%',
        transform: 'translate(-50%, -50%)'
    }}
>
    <YourComponent/>
</div>

"[notice] child pid XXXX exit signal Segmentation fault (11)" in apache error.log

A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.

Try disabling all non-essential modules (in php.ini), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.

If that doesn't help, you should report a php bug.

Send form data with jquery ajax json

The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.

To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.

$.ajax({
    url: 'test.php',
    type: "POST",
    dataType: 'json',
    data: formToJson($("form")),
    contentType: 'application/json;charset=UTF-8',
    ...
})

Where does the .gitignore file belong?

If you want to do it globally, you can use the default path git will search for. Just place it inside a file named "ignore" in the path ~/.config/git

(so full path for your file is: ~/.config/git/ignore)

Calculating the angle between the line defined by two points

Assumptions: x is the horizontal axis, and increases when moving from left to right. y is the vertical axis, and increases from bottom to top. (touch_x, touch_y) is the point selected by the user. (center_x, center_y) is the point at the center of the screen. theta is measured counter-clockwise from the +x axis. Then:

delta_x = touch_x - center_x
delta_y = touch_y - center_y
theta_radians = atan2(delta_y, delta_x)

Edit: you mentioned in a comment that y increases from top to bottom. In that case,

delta_y = center_y - touch_y

But it would be more correct to describe this as expressing (touch_x, touch_y) in polar coordinates relative to (center_x, center_y). As ChrisF mentioned, the idea of taking an "angle between two points" is not well defined.

How To Auto-Format / Indent XML/HTML in Notepad++

It's been the third time that I install Windows and npp and after some time I realize the tidy function no longer work. So I google for a solution, come to this thread, then with the help of few more so threads I finally fix it. I'll put a summary of all my actions once and for all.

  1. Install TextFX plugin: Plugins -> Plugin Manager -> Show Plugin Manager. Select TextFX Characters and install. After a restart of npp, the menu 'TextFX' should be visible. (credits: @remipod).

  2. Install libtidy.dll by pasting the Config folder from an old npp package: Follow instructions in this answer.

  3. After having a Config folder in your latest npp installation destination (typically C:\Program Files (x86)\Notepad++\plugins), npp needs write access to that folder. Right click Config folder -> Properties -> Security tab -> select Users, click Edit -> check Full control to allow read/write access. Note that you need administrator privileges to do that.

  4. Restart npp and verify TextFX -> TextFX HTML Tidy -> Tidy: Reindent XML works.

Check for null variable in Windows batch

Late answer, but currently the accepted one is at least suboptimal.

Using quotes is ALWAYS better than using any other characters to enclose %1.
Because when %1 contains spaces or special characters like &, the IF [%1] == simply stops with a syntax error.

But for the case that %1 contains quotes, like in myBatch.bat "my file.txt", a simple IF "%1" == "" would fail.

But as you can't know if quotes are used or not, there is the syntax %~1, this removes enclosing quotes when necessary.

Therefore, the code should look like

set "file1=%~1"
IF "%~1"=="" set "file1=default file"

type "%file1%"   --- always enclose your variables in quotes

If you have to handle stranger and nastier arguments like myBatch.bat "This & will "^&crash
Then take a look at SO:How to receive even the strangest command line parameters?

How to upgrade Git on Windows to the latest version?

Using the command "where git" find out how command prompt picks up the version. Once you have the path, you can go ahead and uninstall / delete previous version completely. Then if you install and make sure the new installed location is in the path, it should just work fine.

Using git-friendly tools like cmder will make your life much easier. You don't really have to use dual boot or cygwin anymore since the support for git in windows is already top-notch now. (Git for windows installs msysgit which includes all necessary unix tools from MinGW. MinGW has been there for a while and is pretty stable. If you want you can install the full version of msysgit rather than Git for Windows. msysgit is available on Git for windows page at the bottom.)

Single TextView with multiple colored text

Use SpannableBuilder class instead of HTML formatting where it possible because it more faster then HTML format parsing. See my own benchmark "SpannableBuilder vs HTML" on Github Thanks!

Find UNC path of a network drive?

The answer is a simple PowerShell one-liner:

Get-WmiObject Win32_NetworkConnection | ft "RemoteName","LocalName" -A

If you only want to pull the UNC for one particular drive, add a where statement:

Get-WmiObject Win32_NetworkConnection | where -Property 'LocalName' -eq 'Z:'  | ft "RemoteName","LocalName" -A

How to getElementByClass instead of GetElementById with JavaScript?

Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.

Older Answer

You'll want to check into jQuery, which will allow the following:

$(".classname").hide(); // hides everything with class 'classname'

Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
  $(function(){
    $(".classname").hide();
  });
</script>

Java - Check if JTextField is empty or not

if(name.getText().hashCode() != 0){
    JOptionPane.showMessageDialog(null, "not empty");
}
else{
    JOptionPane.showMessageDialog(null, "empty");
}

c# razor url parameter from view

If you're doing the check inside the View, put the value in the ViewBag.

In your controller:

ViewBag["parameterName"] = Request["parameterName"];

It's worth noting that the Request and Response properties are exposed by the Controller class. They have the same semantics as HttpRequest and HttpResponse.

Test a string for a substring

There are several other ways, besides using the in operator (easiest):

index()

>>> try:
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found

find()

>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found

re

>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found

Set Text property of asp:label in Javascript PROPER way

Asp.net codebehind runs on server first and then page is rendered to client (browser). Codebehind has no access to client side (javascript, html) because it lives on server only.

So, either use ajax and sent value of label to code behind. You can use PageMethods , or simply post the page to server where codebehind lives, so codebehind can know the updated value :)

Convert json to a C# array?

Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}

How to create a date object from string in javascript

I can't believe javascript isn't more consistent with parsing dates. And I hear the default when there is no timezone is gonna change from UTC to local -- hope the web is prepared ;)

I prefer to let Javascript do the heavy lifting when it comes to parsing dates. However it would be nice to handle the local timezone issue fairly transparently. With both of these things in mind, here is a function to do it with the current status quo -- and when Javascript changes it will still work but then can be removed (with a little time for people to catch up with older browsers/nodejs of course).

function strToDate(dateStr)
{
    var dateTry = new Date(dateStr);

    if (!dateTry.getTime())
    {
        throw new Exception("Bad Date! dateStr: " + dateStr);
    }

    var tz = dateStr.trim().match(/(Z)|([+-](\d{2})\:?(\d{2}))$/);

    if (!tz)
    {
        var newTzOffset = dateTry.getTimezoneOffset() / 60;
        var newSignStr = (newTzOffset >= 0) ? '-' : '+';
        var newTz = newSignStr + ('0' + Math.abs(newTzOffset)).slice(-2) + ':00';

        dateStr = dateStr.trim() + newTz;
        dateTry = new Date(dateStr);

        if (!dateTry.getTime())
        {
            throw new Exception("Bad Date! dateStr: " + dateStr);
        }
    }

    return dateTry;
}

We need a date object regardless; so createone. If there is a timezone, we are done. Otherwise, create a local timezone string using the +hh:mm format (more accepted than +hhmm).

Entity Framework and SQL Server View

If you do not want to mess with what should be the primary key, I recommend:

  1. Incorporate ROW_NUMBER into your selection
  2. Set it as primary key
  3. Set all other columns/members as non-primary in the model

How to scale a BufferedImage

To scale an image, you need to create a new image and draw into it. One way is to use the filter() method of an AffineTransferOp, as suggested here. This allows you to choose the interpolation technique.

private static BufferedImage scale1(BufferedImage before, double scale) {
    int w = before.getWidth();
    int h = before.getHeight();
    // Create a new image of the proper size
    int w2 = (int) (w * scale);
    int h2 = (int) (h * scale);
    BufferedImage after = new BufferedImage(w2, h2, BufferedImage.TYPE_INT_ARGB);
    AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
    AffineTransformOp scaleOp 
        = new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);

    scaleOp.filter(before, after);
    return after;
}

Another way is to simply draw the original image into the new image, using a scaling operation to do the scaling. This method is very similar, but it also illustrates how you can draw anything you want in the final image. (I put in a blank line where the two methods start to differ.)

private static BufferedImage scale2(BufferedImage before, double scale) {
    int w = before.getWidth();
    int h = before.getHeight();
    // Create a new image of the proper size
    int w2 = (int) (w * scale);
    int h2 = (int) (h * scale);
    BufferedImage after = new BufferedImage(w2, h2, BufferedImage.TYPE_INT_ARGB);
    AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
    AffineTransformOp scaleOp 
        = new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);

    Graphics2D g2 = (Graphics2D) after.getGraphics();
    // Here, you may draw anything you want into the new image, but we're
    // drawing a scaled version of the original image.
    g2.drawImage(before, scaleOp, 0, 0);
    g2.dispose();
    return after;
}

Addendum: Results

To illustrate the differences, I compared the results of the five methods below. Here is what the results look like, scaled both up and down, along with performance data. (Performance varies from one run to the next, so take these numbers only as rough guidelines.) The top image is the original. I scale it double-size and half-size.

As you can see, AffineTransformOp.filter(), used in scaleBilinear(), is faster than the standard drawing method of Graphics2D.drawImage() in scale2(). Also BiCubic interpolation is the slowest, but gives the best results when expanding the image. (For performance, it should only be compared with scaleBilinear() and scaleNearest().) Bilinear seems to be better for shrinking the image, although it's a tough call. And NearestNeighbor is the fastest, with the worst results. Bilinear seems to be the best compromise between speed and quality. The Image.getScaledInstance(), called in the questionable() method, performed very poorly, and returned the same low quality as NearestNeighbor. (Performance numbers are only given for expanding the image.)

enter image description here

public static BufferedImage scaleBilinear(BufferedImage before, double scale) {
    final int interpolation = AffineTransformOp.TYPE_BILINEAR;
    return scale(before, scale, interpolation);
}

public static BufferedImage scaleBicubic(BufferedImage before, double scale) {
    final int interpolation = AffineTransformOp.TYPE_BICUBIC;
    return scale(before, scale, interpolation);
}

public static BufferedImage scaleNearest(BufferedImage before, double scale) {
    final int interpolation = AffineTransformOp.TYPE_NEAREST_NEIGHBOR;
    return scale(before, scale, interpolation);
}

@NotNull
private static 
BufferedImage scale(final BufferedImage before, final double scale, final int type) {
    int w = before.getWidth();
    int h = before.getHeight();
    int w2 = (int) (w * scale);
    int h2 = (int) (h * scale);
    BufferedImage after = new BufferedImage(w2, h2, before.getType());
    AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
    AffineTransformOp scaleOp = new AffineTransformOp(scaleInstance, type);
    scaleOp.filter(before, after);
    return after;
}

/**
 * This is a more generic solution. It produces the same result, but it shows how you 
 * can draw anything you want into the newly created image. It's slower 
 * than scaleBilinear().
 * @param before The original image
 * @param scale The scale factor
 * @return A scaled version of the original image
 */
private static BufferedImage scale2(BufferedImage before, double scale) {
    int w = before.getWidth();
    int h = before.getHeight();
    // Create a new image of the proper size
    int w2 = (int) (w * scale);
    int h2 = (int) (h * scale);
    BufferedImage after = new BufferedImage(w2, h2, before.getType());
    AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
    AffineTransformOp scaleOp
            = new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);

    Graphics2D g2 = (Graphics2D) after.getGraphics();
    // Here, you may draw anything you want into the new image, but we're just drawing
    // a scaled version of the original image. This is slower than 
    // calling scaleOp.filter().
    g2.drawImage(before, scaleOp, 0, 0);
    g2.dispose();
    return after;
}

/**
 * I call this one "questionable" because it uses the questionable getScaledImage() 
 * method. This method is no longer favored because it's slow, as my tests confirm.
 * @param before The original image
 * @param scale The scale factor
 * @return The scaled image.
 */
private static Image questionable(final BufferedImage before, double scale) {
    int w2 = (int) (before.getWidth() * scale);
    int h2 = (int) (before.getHeight() * scale);
    return before.getScaledInstance(w2, h2, Image.SCALE_FAST);
}

Should I use pt or px?

Have a look at this excellent article at CSS-Tricks:

Taken from the article:


pt

The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution.

Just like how pixels are dead-accurate on monitors for font-sizing, point sizes are dead-accurate on paper. For the best cross-browser and cross-platform results while printing pages, set up a print stylesheet and size all fonts with point sizes.

For good measure, the reason we don't use point sizes for screen display (other than it being absurd), is that the cross-browser results are drastically different:

px

If you need fine-grained control, sizing fonts in pixel values (px) is an excellent choice (it's my favorite). On a computer screen, it doesn't get any more accurate than a single pixel. With sizing fonts in pixels, you are literally telling browsers to render the letters exactly that number of pixels in height:

Windows, Mac, aliased, anti-aliased, cross-browsers, doesn't matter, a font set at 14px will be 14px tall. But that isn't to say there won't still be some variation. In a quick test below, the results were slightly more consistent than with keywords but not identical:

Due to the nature of pixel values, they do not cascade. If a parent element has an 18px pixel size and the child is 16px, the child will be 16px. However, font-sizing settings can be using in combination. For example, if the parent was set to 16px and the child was set to larger, the child would indeed come out larger than the parent. A quick test showed me this:

"Larger" bumped the 16px of the parent into 20px, a 25% increase.

Pixels have gotten a bad wrap in the past for accessibility and usability concerns. In IE 6 and below, font-sizes set in pixels cannot be resized by the user. That means that us hip young healthy designers can set type in 12px and read it on the screen just fine, but when folks a little longer in the tooth go to bump up the size so they can read it, they are unable to. This is really IE 6's fault, not ours, but we gots what we gots and we have to deal with it.

Setting font-size in pixels is the most accurate (and I find the most satisfying) method, but do take into consideration the number of visitors still using IE 6 on your site and their accessibility needs. We are right on the bleeding edge of not needing to care about this anymore.


MIT vs GPL license

It seems to me that the chief difference between the MIT license and GPL is that the MIT doesn't require modifications be open sourced whereas the GPL does.

True - in general. You don't have to open-source your changes if you're using GPL. You could modify it and use it for your own purpose as long as you're not distributing it. BUT... if you DO distribute it, then your entire project that is using the GPL code also becomes GPL automatically. Which means, it must be open-sourced, and the recipient gets all the same rights as you - meaning, they can turn around and distribute it, modify it, sell it, etc. And that would include your proprietary code which would then no longer be proprietary - it becomes open source.

The difference with MIT is that even if you actually distribute your proprietary code that is using the MIT licensed code, you do not have to make the code open source. You can distribute it as a closed app where the code is encrypted or is a binary. Including the MIT-licensed code can be encrypted, as long as it carries the MIT license notice.

is the GPL is more restrictive than the MIT license?

Yes, very much so.

How do I get the browser scroll position in jQuery?

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

Bootstrap Dropdown menu is not working

In my case, disabling Chrome Extensions fixed it. I removed them from Chrome one by one until I found the culprit.

Since I'm the author of the offending Chrome extension, I guess I better fix the extension!

LINQ to SQL Left Outer Join

Public Sub LinqToSqlJoin07()
Dim q = From e In db.Employees _
        Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
        From o In ords.DefaultIfEmpty _
        Select New With {e.FirstName, e.LastName, .Order = o}

ObjectDumper.Write(q) End Sub

Check http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Does Ruby have a string.startswith("abc") built in method?

If this is for a non-Rails project, I'd use String#index:

"foobar".index("foo") == 0  # => true

pop/remove items out of a python tuple

In Python 3 this is no longer an issue, and you really don't want to use list comprehension, coercion, filters, functions or lambdas for something like this.

Just use

popped = unpopped[:-1]

Remember that it's an immutable, so you will have to reassign the value if you want it to change

my_tuple = my_tuple[:-1]

Example

>>> foo= 3,5,2,4,78,2,1
>>> foo
(3, 5, 2, 4, 78, 2, 1)
foo[:-1]
(3, 5, 2, 4, 78, 2)

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

Android Studio drawable folders

Just to make complete all answers, 'drawable' is, literally, a drawable image, not a complete and ready set of pixels, as .png

In other word words, drawable is only for vectorial images, just try right-click on 'drawable' and go New > Vector Asset, it will accept it, while Image Asset won't be added.

The data for 'drawing', generating the image is recorded on a XML file like this:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
<path
    android:fillColor="#FF000000"
    android:pathData="M6,18c0,0.55 0.45,1 1,1h1v3.5c0,0.83 0.67,1.5 1.5,1.5s1.5,
    -0.67 1.5,-1.5L11,19h2v3.5c0,0.83 0.67,1.5 1.5,1.5s1.5,-0.67 1.5,-1.5L16,
    19h1c0.55,0 1,-0.45 1,-1L18,8L6,8v10zM3.5,8C2.67,8 2,8.67 2,9.5v7c0,0.83 0.67,
    1.5 1.5,1.5S5,17.33 5,16.5v-7C5,8.67 4.33,8 3.5,8zM20.5,8c-0.83,0 -1.5,0.67 -1.5,
    1.5v7c0,0.83 0.67,1.5 1.5,1.5s1.5,-0.67 1.5,-1.5v-7c0,-0.83 -0.67,-1.5 -1.5,-1.5zM15.53,
    2.16l1.3,-1.3c0.2,-0.2 0.2,-0.51 0,-0.71 -0.2,-0.2 -0.51,-0.2 -0.71,0l-1.48,1.48C13.85,
    1.23 12.95,1 12,1c-0.96,0 -1.86,0.23 -2.66,0.63L7.85,0.15c-0.2,-0.2 -0.51,-0.2 -0.71,0 -0.2,
    0.2 -0.2,0.51 0,0.71l1.31,1.31C6.97,3.26 6,5.01 6,7h12c0,-1.99 -0.97,-3.75 -2.47,-4.84zM10,
    5L9,5L9,4h1v1zM15,5h-1L14,4h1v1z"/>
  </vector>

That's the code for ic_android_black_24dp

How I can check if an object is null in ruby on rails 2?

In your example, you can simply replace null with `nil and it will work fine.

require 'erb'

template = <<EOS
<% if (@objectname != nil) then %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

Contrary to what the other poster said, you can see above that then works fine in Ruby. It's not common, but it is fine.

#blank? and #present? have other implications. Specifically, if the object responds to #empty?, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.

Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be

require 'erb'

template = <<EOS
<% if @objectname %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

If you explicitly need to check nil and not false, you can use the #nil? method, for which nil is the only object that will cause this to return true.

nil.nil?          # => true
false.nil?        # => false
Object.new.nil?   # => false

How do I change the text of a span element using JavaScript?

_x000D_
_x000D_
(function ($) {
    $(document).ready(function(){
    $("#myspan").text("This is span");
  });
}(jQuery));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="myspan"> hereismytext </span>
_x000D_
_x000D_
_x000D_

user text() to change span text.

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

I just fix this problem in my project-

CSS code

.scroll-menu{
   min-width: 220px;
   max-height: 90vh;
   overflow: auto;
 }

HTML code

<ul class="dropdown-menu scroll-menu" role="menu">
   <li><a href="#">Action</a></li>
   <li><a href="#">Another action</a></li>
   <li><a href="#">Something else here</a></li>
   <li><a href="#">Action</a></li>
   ..
   <li><a href="#">Action</a></li>
   <li><a href="#">Another action</a></li>
</ul>

Connecting to remote MySQL server using PHP

It is very easy to connect remote MySQL Server Using PHP, what you have to do is:

  1. Create a MySQL User in remote server.

  2. Give Full privilege to the User.

  3. Connect to the Server using PHP Code (Sample Given Below)

$link = mysql_connect('your_my_sql_servername or IP Address', 'new_user_which_u_created', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';

mysql_select_db('sandsbtob',$link) or die ("could not open db".mysql_error());
// we connect to localhost at port 3306

Node.js Write a line into a .txt file

I did a log file which prints data into text file using "Winston" log. The source code is here below,

const { createLogger, format, transports } = require('winston');
var fs = require('fs')
var logger = fs.createWriteStream('Data Log.txt', {`
flags: 'a' 
})
const os = require('os');
var sleep = require('system-sleep');
var endOfLine = require('os').EOL;
var t = '             ';var s = '         ';var q = '               ';
var array1=[];
var array2=[];
var array3=[];
var array4=[];

array1[0]  =  78;`
array1[1]  =  56;
array1[2]  =  24;
array1[3]  =  34;

for (var n=0;n<4;n++)
{
array2[n]=array1[n].toString();
}

for (var k=0;k<4;k++)
{
array3[k]=Buffer.from('                    ');
}

for (var a=0;a<4;a++)  
{
array4[a]=Buffer.from(array2[a]);
}

for (m=0;m<4;m++)
{
array4[m].copy(array3[m],0);
}

logger.write('Date'+q);
logger.write('Time'+(q+'  '))
logger.write('Data 01'+t);
logger.write('Data 02'+t); 
logger.write('Data 03'+t);
logger.write('Data 04'+t)

logger.write(endOfLine);
logger.write(endOfLine);
enter code here`enter code here`
}

function mydata()      //user defined function
{
logger.write(datechar+s);
logger.write(timechar+s);
for ( n = 0; n < 4; n++) 
{
logger.write(array3[n]);
}
logger.write(endOfLine); 
}

for (;;)
}
var now = new Date();
var dateFormat = require('dateformat');
var date = dateFormat(now,"isoDate");
var time = dateFormat(now, "h:MM:ss TT ");
var datechar = date.toString();
var timechar = time.toString();
mydata();
sleep(5*1000);
}

Avoid dropdown menu close on click inside

In .dropdown content put the .keep-open class on any label like so:

$('.dropdown').on('click', function (e) {
    var target = $(e.target);
    var dropdown = target.closest('.dropdown');
    if (target.hasClass('keep-open')) {
        $(dropdown).addClass('keep-open');
    } else {
        $(dropdown).removeClass('keep-open');
    }
});

$(document).on('hide.bs.dropdown', function (e) {
    var target = $(e.target);
    if ($(target).is('.keep-open')) {
        return false
    }
});

The previous cases avoided the events related to the container objects, now the container inherits the class keep-open and check before being closed.

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

ffprobe or avprobe not found. Please install one

Compiling the last answers into one:

If you're on Windows, use chocolatey:

choco install ffmpeg

If you are on Mac, use Brew:

brew install ffmpeg

If you are on a Debian Linux distribution, use apt:

sudo apt-get install ffmpeg

And make sure Youtube-dl is updated:

youtube-dl -U

HTTP Basic: Access denied fatal: Authentication failed

  • Try if it works on the Git Bash
  • Have you added a ssh key to your account? If yes remove it and try again. If not add one and try the ssh url.
  • You don't necessarily need Tortoise Git but it may also work around your problem
  • Try to re-install Git without the Git Credential Manager for Windows

When you've fixed the push problem you will also be able to clone it when it is private or internal.

Express.js: how to get remote client address

If you are running behind a proxy like NGiNX or what have you, only then you should check for 'x-forwarded-for':

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

If the proxy isn't 'yours', I wouldn't trust the 'x-forwarded-for' header, because it can be spoofed.

Sorting Characters Of A C++ String

There is a sorting algorithm in the standard library, in the header <algorithm>. It sorts inplace, so if you do the following, your original word will become sorted.

std::sort(word.begin(), word.end());

If you don't want to lose the original, make a copy first.

std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

What is the most efficient/quickest way to loop through rows in VBA (excel)?

For Each is much faster than for I=1 to X, for some reason. Just try to go through the same dictionary,


once with for each Dkey in dDict,


and once with for Dkey = lbound(dDict.keys) to ubound(dDict.keys)

=>You will notice a huge difference, even though you are going through the same construct.

How to set page content to the middle of screen?

If you want to center the content horizontally and vertically, but don't know in prior how high your page will be, you have to you use JavaScript.

HTML:

<body>
    <div id="content">...</div>
</body>

CSS:

#content {
    max-width: 1000px;
    margin: auto;
    left: 1%;
    right: 1%;
    position: absolute;
}

JavaScript (using jQuery):

$(function() {
    $(window).on('resize', function resize()  {
        $(window).off('resize', resize);
        setTimeout(function () {
            var content = $('#content');
            var top = (window.innerHeight - content.height()) / 2;
            content.css('top', Math.max(0, top) + 'px');
            $(window).on('resize', resize);
        }, 50);
    }).resize();
});

Centered horizontally and vertically

Demo: http://jsfiddle.net/nBzcb/

When should I really use noexcept?

There are many examples of functions that I know will never throw, but for which the compiler cannot determine so on its own. Should I append noexcept to the function declaration in all such cases?

When you say "I know [they] will never throw", you mean by examining the implementation of the function you know that the function will not throw. I think that approach is inside out.

It is better to consider whether a function may throw exceptions to be part of the design of the function: as important as the argument list and whether a method is a mutator (... const). Declaring that "this function never throws exceptions" is a constraint on the implementation. Omitting it does not mean the function might throw exceptions; it means that the current version of the function and all future versions may throw exceptions. It is a constraint that makes the implementation harder. But some methods must have the constraint to be practically useful; most importantly, so they can be called from destructors, but also for implementation of "roll-back" code in methods that provide the strong exception guarantee.

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

Convert String to equivalent Enum value

Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration class), you can use the valueOf method of java.lang.Enum subclass:

MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");

How do you check if a string is not equal to an object or other string value in java?

you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to be clear you can also do

if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to have the not (one or the other) phrase in the code (remember the (silent) brackets)

Variably modified array at file scope

If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES automagically:

#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = { 
  1,
  2, 
  3, 
  4 };

Remove HTML Tags in Javascript with Regex

you can use a powerful library for management String which is undrescore.string.js

_('a <a href="#">link</a>').stripTags()

=> 'a link'

_('a <a href="#">link</a><script>alert("hello world!")</script>').stripTags()

=> 'a linkalert("hello world!")'

Don't forget to import this lib as following :

        <script src="underscore.js" type="text/javascript"></script>
        <script src="underscore.string.js" type="text/javascript"></script>
        <script type="text/javascript"> _.mixin(_.str.exports())</script>

How to connect to a remote MySQL database with Java?

  1. Create a new user in the schema ‘mysql’ (mysql.user) Run this code in your mysql work space “GRANT ALL ON . to user@'%'IDENTIFIED BY '';

  2. Open the ‘3306’ port at the machine which is having the Data Base. Control Panel -> Windows Firewall -> Advance Settings -> Inbound Rules -> New Rule -> Port -> Next -> TCP & set port as 3306 -> Next -> Next -> Next -> Fill Name and Description -> Finish ->

  3. Try to check by a telnet msg on cmd including DB server's IP

Difference between using gradlew and gradle

The difference lies in the fact that ./gradlew indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle and then invoke gradle using the gradle command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.

Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.

Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable

Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html

Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk

Joda DateTime to Timestamp conversion

//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));               
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));

How to change port for jenkins window service when 8080 is being used

Restart Jenkins service

Just restart the Jenkins service after you changed the port in jenkins.xml.

  1. Press Win + R
  2. Type "services.msc"
  3. Right click on the "Jenkins" line > Restart

    Restart Jenkins

  4. Type http://localhost:8081/ in your browser to test the change.

Overriding css style?

Instead of override you can add another class to the element and then you have an extra abilities. for example:

HTML

<div class="style1 style2"></div>

CSS

//only style for the first stylesheet
.style1 {
   width: 100%;      
}
//only style for second stylesheet
.style2 {
   width: 50%;     
}
//override all
.style1.style2 { 
   width: 70%;
}

How can I select records ONLY from yesterday?

If you want the timestamp for yesterday try something like:

(CURRENT_TIMESTAMP - INTERVAL '1' DAY)

SpringMVC RequestMapping for GET parameters

Use @RequestParam in your method arguments so Spring can bind them, also use the @RequestMapping.params array to narrow the method that will be used by spring. Sample code:

@RequestMapping("/userGrid", 
params = {"_search", "nd", "rows", "page", "sidx", "sort"})
public @ResponseBody GridModel getUsersForGrid(
@RequestParam(value = "_search") String search, 
@RequestParam(value = "nd") int nd, 
@RequestParam(value = "rows") int rows, 
@RequestParam(value = "page") int page, 
@RequestParam(value = "sidx") int sidx, 
@RequestParam(value = "sort") Sort sort) {
// Stuff here
}

This way Spring will only execute this method if ALL PARAMETERS are present saving you from null checking and related stuff.

Possible to view PHP code of a website?

A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.

For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.

Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.

However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.

Read the Security section of the PHP manual as a starting point to keeping your code safe.

Use the auto keyword in C++ STL

auto keyword is intended to use in such situation, it is absolutely safe. But unfortunately it available only in C++0x so you will have portability issues with it.

Get the name of a pandas DataFrame

You can name the dataframe with the following, and then call the name wherever you like:

import pandas as pd
df = pd.DataFrame( data=np.ones([4,4]) )
df.name = 'Ones'

print df.name
>>>
Ones

Hope that helps.

URL string format for connecting to Oracle database with JDBC

The correct format for url can be one of the following formats:

jdbc:oracle:thin:@<hostName>:<portNumber>:<sid>;  (if you have sid)
jdbc:oracle:thin:@//<hostName>:<portNumber>/serviceName; (if you have oracle service name)

And don't put any space there. Try to use 1521 as port number. sid (database name) must be the same as the one which is in environment variables (if you are using windows).

what is the difference between GROUP BY and ORDER BY in sql

ORDER BY: sort the data in ascending or descending order.

Consider the CUSTOMERS table:

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would sort the result in ascending order by NAME:

SQL> SELECT * FROM CUSTOMERS
     ORDER BY NAME;

This would produce the following result:

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
+----+----------+-----+-----------+----------+

GROUP BY: arrange identical data into groups.

Now, CUSTOMERS table has the following records with duplicate names:

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Ramesh   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | kaushik  |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

if you want to group identical names into single name, then GROUP BY query would be as follows:

SQL> SELECT * FROM CUSTOMERS
     GROUP BY NAME;

This would produce the following result: (for identical names it would pick the last one and finally sort the column in ascending order)

    +----+----------+-----+-----------+----------+   
    | ID | NAME     | AGE | ADDRESS   | SALARY   |
    +----+----------+-----+-----------+----------+
    |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    |  4 | kaushik  |  25 | Mumbai    |  6500.00 |
    |  6 | Komal    |  22 | MP        |  4500.00 |
    |  7 | Muffy    |  24 | Indore    | 10000.00 |
    |  2 | Ramesh   |  25 | Delhi     |  1500.00 |
    +----+----------+-----+-----------+----------+

as you have inferred that it is of no use without SQL functions like sum,avg etc..

so go through this definition to understand the proper use of GROUP BY:

A GROUP BY clause works on the rows returned by a query by summarizing identical rows into a single/distinct group and returns a single row with the summary for each group, by using appropriate Aggregate function in the SELECT list, like COUNT(), SUM(), MIN(), MAX(), AVG(), etc.

Now, if you want to know the total amount of salary on each customer(name), then GROUP BY query would be as follows:

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
     GROUP BY NAME;

This would produce the following result: (sum of the salaries of identical names and sort the NAME column after removing identical names)

+---------+-------------+
| NAME    | SUM(SALARY) |
+---------+-------------+
| Hardik  |     8500.00 |
| kaushik |     8500.00 |
| Komal   |     4500.00 |
| Muffy   |    10000.00 |
| Ramesh  |     3500.00 |
+---------+-------------+

Calling a class method raises a TypeError in Python

You can instantiate the class by declaring a variable and calling the class as if it were a function:

x = mystuff()
print x.average(9,18,27)

However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message:

TypeError: average() takes exactly 3 arguments (4 given)

To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.

Getting a count of objects in a queryset in django

To get the number of votes for a specific item, you would use:

vote_count = Item.objects.filter(votes__contest=contestA).count()

If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:

contest = Contest.objects.get(pk=contest_id)
votes   = contest.votes_set.select_related()

vote_counts = {}

for vote in votes:
  if not vote_counts.has_key(vote.item.id):
    vote_counts[vote.item.id] = {
      'item': vote.item,
      'count': 0
    }

  vote_counts[vote.item.id]['count'] += 1

This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.

Bring a window to the front in WPF

I know this question is rather old, but I've just come across this precise scenario and wanted to share the solution I've implemented.

As mentioned in comments on this page, several of the solutions proposed do not work on XP, which I need to support in my scenario. While I agree with the sentiment by @Matthew Xavier that generally this is a bad UX practice, there are times where it's entirely a plausable UX.

The solution to bringing a WPF window to the top was actually provided to me by the same code I'm using to provide the global hotkey. A blog article by Joseph Cooney contains a link to his code samples that contains the original code.

I've cleaned up and modified the code a little, and implemented it as an extension method to System.Windows.Window. I've tested this on XP 32 bit and Win7 64 bit, both of which work correctly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interop;
using System.Runtime.InteropServices;

namespace System.Windows
{
    public static class SystemWindows
    {
        #region Constants

        const UInt32 SWP_NOSIZE = 0x0001;
        const UInt32 SWP_NOMOVE = 0x0002;
        const UInt32 SWP_SHOWWINDOW = 0x0040;

        #endregion

        /// <summary>
        /// Activate a window from anywhere by attaching to the foreground window
        /// </summary>
        public static void GlobalActivate(this Window w)
        {
            //Get the process ID for this window's thread
            var interopHelper = new WindowInteropHelper(w);
            var thisWindowThreadId = GetWindowThreadProcessId(interopHelper.Handle, IntPtr.Zero);

            //Get the process ID for the foreground window's thread
            var currentForegroundWindow = GetForegroundWindow();
            var currentForegroundWindowThreadId = GetWindowThreadProcessId(currentForegroundWindow, IntPtr.Zero);

            //Attach this window's thread to the current window's thread
            AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, true);

            //Set the window position
            SetWindowPos(interopHelper.Handle, new IntPtr(0), 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);

            //Detach this window's thread from the current window's thread
            AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, false);

            //Show and activate the window
            if (w.WindowState == WindowState.Minimized) w.WindowState = WindowState.Normal;
            w.Show();
            w.Activate();
        }

        #region Imports

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

        [DllImport("user32.dll")]
        private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

        [DllImport("user32.dll")]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        #endregion
    }
}

I hope this code helps others who encounter this problem.

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

Regex not operator

You could capture the (2001) part and replace the rest with nothing.

public static string extractYearString(string input) {
    return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}

var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"

.*\(([0-9]{4})\).* means

  • .* match anything
  • \( match a ( character
  • ( begin capture
  • [0-9]{4} any single digit four times
  • ) end capture
  • \) match a ) character
  • .* anything (rest of string)

how to use XPath with XDocument?

If you have XDocument it is easier to use LINQ-to-XML:

var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;

If you are sure that XPath is the only solution you need:

using System.Xml.XPath;

var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;

Use YAML with variables

if your requirement is like parsing an replacing multiple variable and then use it as a hash/or anything then you can do something like this

require 'yaml'
require 'json'
yaml = YAML.load_file("xxxx.yaml")
blueprint = yaml.to_json % { var_a: "xxxx", var_b: "xxxx"}
hash = JSON.parse(blueprint)

inside the yaml just put variables like this

"%{var_a}"

Is true == 1 and false == 0 in JavaScript?

In JavaScript, == is pronounced "Probably Equals".

What I mean by that is that JavaScript will automatically convert the Boolean into an integer and then attempt to compare the two sides.

For real equality, use the === operator.

Create <div> and append <div> dynamically

window.onload = function() {
  var iDiv = document.createElement('div');
  iDiv.id = 'block';
  iDiv.className = 'block';
  document.body.appendChild(iDiv);

  var iiDiv = document.createElement('div');
  iiDiv.className = 'block-2';

  var s = document.getElementById('block');
  s.appendChild(iiDiv);
}

Can anonymous class implement interface?

No; an anonymous type can't be made to do anything except have a few properties. You will need to create your own type. I didn't read the linked article in depth, but it looks like it uses Reflection.Emit to create new types on the fly; but if you limit discussion to things within C# itself you can't do what you want.

How to highlight a current menu item?

None of the above directive suggestions were useful to me. If you have a bootstrap navbar like this

<ul class="nav navbar-nav">
    <li><a ng-href="#/">Home</a></li>
    <li><a ng-href="#/about">About</a></li>
  ...
</ul>

(that could be a $ yo angular startup) then you want to add .active to the parent <li> element class list, not the element itself; i.e <li class="active">..</li>. So I wrote this :

.directive('setParentActive', ['$location', function($location) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs, controller) {
      var classActive = attrs.setParentActive || 'active',
          path = attrs.ngHref.replace('#', '');
      scope.location = $location;
      scope.$watch('location.path()', function(newPath) {
        if (path == newPath) {
          element.parent().addClass(classActive);
        } else {
          element.parent().removeClass(classActive);
        }
      })
    }
  }
}])

usage set-parent-active; .active is default so not needed to be set

<li><a ng-href="#/about" set-parent-active>About</a></li>

and the parent <li> element will be .active when the link is active. To use an alternative .active class like .highlight, simply

<li><a ng-href="#/about" set-parent-active="highlight">About</a></li>

Shell equality operators (=, ==, -eq)

Several answers show dangerous examples. OP's example [ $a == $b ] specifically used unquoted variable substitution (as of Oct '17 edit). For [...] that is safe for string equality.

But if you're going to enumerate alternatives like [[...]], you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").

Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:

$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$

"Fade" borders in CSS

You can specify gradients for colours in certain circumstances in CSS3, and of course borders can be set to a colour, so you should be able to use a gradient as a border colour. This would include the option of specifying a transparent colour, which means you should be able to achieve the effect you're after.

However, I've never seen it used, and I don't know how well supported it is by current browsers. You'll certainly need to accept that at least some of your users won't be able to see it.

A quick google turned up these two pages which should help you on your way:

Hope that helps.

Adding one day to a date

While I agree with Doug Hays' answer, I'll chime in here to say that the reason your code doesn't work is because strtotime() expects an INT as the 2nd argument, not a string (even one that represents a date)

If you turn on max error reporting you'll see this as a "A non well formed numeric value" error which is E_NOTICE level.

How to make a div with a circular shape?

You can do following

FIDDLE

<div id="circle"></div>

CSS

#circle {
    width: 100px;
    height: 100px;
    background: red;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
}

Other shape SOURCE

Removing leading zeroes from a field in a SQL statement

select replace(replace(rtrim(replace(replace(replace(replace(ltrim(replace(replace([COLUMN],' ','[Ltrim]'),[Ltrim],' ')),' ',[Ltrim]),'[Ltrim]',' '),' ','[Rtrim]'),[Rtrim],' ')),' ',[Rtrim]),'[Rtrim]',' ') As Result

This is a Sql script that emulates the functionality of the TRIM command in tsql prior to 2017, its basically the same as the other recomendateions,but the others replace with a single uncommon character which still can occur, '[Rtrim]' or '[Ltrim]' could still occur in text, but replacing hat with a unique text, for example a Guid would solve that problem.

i havent tested it regarding speed

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

My answer might not be solution to your question but it will surely help others looking for similar issue like this one: javax.net.ssl.SSLHandshakeException: Chain validation failed

You just need to check your Android Device's Date and Time, it should be fix the issue. This resoled my problem.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

To answer your bonus question, the general answer is no, you don't need to set variables to "Nothing" in short .VBS scripts like yours, that get called by Wscript or Cscript.

The reason you might do this in the middle of a longer script is to release memory back to the operating system that VB would otherwise have been holding. These days when 8GB of RAM is typical and 16GB+ relatively common, this is unlikely to produce any measurable impact, even on a huge script that has several megabytes in a single variable. At this point it's kind of a hold-over from the days where you might have been working in 1MB or 2MB of RAM.

You're correct, the moment your .VBS script completes, all of your variables get destroyed and the memory is reclaimed anyway. Setting variables to "Nothing" simply speeds up that process, and allows you to do it in the middle of a script.

How to form tuple column from two columns in Pandas

I'd like to add df.values.tolist(). (as long as you don't mind to get a column of lists rather than tuples)

import pandas as pd
import numpy as np

size = int(1e+07)
df = pd.DataFrame({'a': np.random.rand(size), 'b': np.random.rand(size)}) 

%timeit df.values.tolist()
1.47 s ± 38.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit list(zip(df.a,df.b))
1.92 s ± 131 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

How to install the Six module in Python2.7

You need to install this

https://pypi.python.org/pypi/six

If you still don't know what pip is , then please also google for pip install

Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/

What is the role of the bias in neural networks?

If you're working with images, you might actually prefer to not use a bias at all. In theory, that way your network will be more independent of data magnitude, as in whether the picture is dark, or bright and vivid. And the net is going to learn to do it's job through studying relativity inside your data. Lots of modern neural networks utilize this.

For other data having biases might be critical. It depends on what type of data you're dealing with. If your information is magnitude-invariant --- if inputting [1,0,0.1] should lead to the same result as if inputting [100,0,10], you might be better off without a bias.

minimize app to system tray

don't forget to add icon file to your notifyIcon or it will not appear in the tray.

Manually Triggering Form Validation using jQuery

In some extent, You CAN trigger HTML5 form validation and show hints to user without submitting the form!

Two button, one for validate, one for submit

Set a onclick listener on the validate button to set a global flag(say justValidate) to indicate this click is intended to check the validation of the form.

And set a onclick listener on the submit button to set the justValidate flag to false.

Then in the onsubmit handler of the form, you check the flag justValidate to decide the returning value and invoke the preventDefault() to stop the form to submit. As you know, the HTML5 form validation(and the GUI hint to user) is preformed before the onsubmit event, and even if the form is VALID you can stop the form submit by returning false or invoke preventDefault().

And, in HTML5 you have a method to check the form's validation: the form.checkValidity(), then in you can know if the form is validate or not in your code.

OK, here is the demo: http://jsbin.com/buvuku/2/edit

Get loop count inside a Python FOR loop

The pythonic way is to use enumerate:

for idx,item in enumerate(list):

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

Regex for quoted string with escaping quotes

An option that has not been touched on before is:

  1. Reverse the string.
  2. Perform the matching on the reversed string.
  3. Re-reverse the matched strings.

This has the added bonus of being able to correctly match escaped open tags.

Lets say you had the following string; String \"this "should" NOT match\" and "this \"should\" match" Here, \"this "should" NOT match\" should not be matched and "should" should be. On top of that this \"should\" match should be matched and \"should\" should not.

First an example.

// The input string.
const myString = 'String \\"this "should" NOT match\\" and "this \\"should\\" match"';

// The RegExp.
const regExp = new RegExp(
    // Match close
    '([\'"])(?!(?:[\\\\]{2})*[\\\\](?![\\\\]))' +
    '((?:' +
        // Match escaped close quote
        '(?:\\1(?=(?:[\\\\]{2})*[\\\\](?![\\\\])))|' +
        // Match everything thats not the close quote
        '(?:(?!\\1).)' +
    '){0,})' +
    // Match open
    '(\\1)(?!(?:[\\\\]{2})*[\\\\](?![\\\\]))',
    'g'
);

// Reverse the matched strings.
matches = myString
    // Reverse the string.
    .split('').reverse().join('')
    // '"hctam "\dluohs"\ siht" dna "\hctam TON "dluohs" siht"\ gnirtS'

    // Match the quoted
    .match(regExp)
    // ['"hctam "\dluohs"\ siht"', '"dluohs"']

    // Reverse the matches
    .map(x => x.split('').reverse().join(''))
    // ['"this \"should\" match"', '"should"']

    // Re order the matches
    .reverse();
    // ['"should"', '"this \"should\" match"']

Okay, now to explain the RegExp. This is the regexp can be easily broken into three pieces. As follows:

# Part 1
(['"])         # Match a closing quotation mark " or '
(?!            # As long as it's not followed by
  (?:[\\]{2})* # A pair of escape characters
  [\\]         # and a single escape
  (?![\\])     # As long as that's not followed by an escape
)
# Part 2
((?:          # Match inside the quotes
(?:           # Match option 1:
  \1          # Match the closing quote
  (?=         # As long as it's followed by
    (?:\\\\)* # A pair of escape characters
    \\        # 
    (?![\\])  # As long as that's not followed by an escape
  )           # and a single escape
)|            # OR
(?:           # Match option 2:
  (?!\1).     # Any character that isn't the closing quote
)
)*)           # Match the group 0 or more times
# Part 3
(\1)           # Match an open quotation mark that is the same as the closing one
(?!            # As long as it's not followed by
  (?:[\\]{2})* # A pair of escape characters
  [\\]         # and a single escape
  (?![\\])     # As long as that's not followed by an escape
)

This is probably a lot clearer in image form: generated using Jex's Regulex

Image on github (JavaScript Regular Expression Visualizer.) Sorry, I don't have a high enough reputation to include images, so, it's just a link for now.

Here is a gist of an example function using this concept that's a little more advanced: https://gist.github.com/scagood/bd99371c072d49a4fee29d193252f5fc#file-matchquotes-js

How do I get values from a SQL database into textboxes using C#?

Make a connection and open it.

con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<database_name>)));User Id =<userid>; Password =<password>");
con.Open();

Write the select query:

string sql = "select * from Pending_Tasks";

Create a command object:

OracleCommand cmd = new OracleCommand(sql, con);

Execute the command and put the result in a object to read it.

OracleDataReader r = cmd.ExecuteReader();

now start reading from it.

while (read.Read())
{
 CustID.Text = (read["Customer_ID"].ToString());
 CustName.Text = (read["Customer_Name"].ToString());
 Add1.Text = (read["Address_1"].ToString());
 Add2.Text = (read["Address_2"].ToString());
 PostBox.Text = (read["Postcode"].ToString());
 PassBox.Text = (read["Password"].ToString());
 DatBox.Text = (read["Data_Important"].ToString());
 LanNumb.Text = (read["Landline"].ToString());
 MobNumber.Text = (read["Mobile"].ToString());
 FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();

Add this too using Oracle.ManagedDataAccess.Client;

Is it possible to open developer tools console in Chrome on Android phone?

You can do it using remote debugging, here is official documentation. Basic process:

  1. Connect your android device
  2. Select your device: More tools > Inspect devices* from dev tools on pc/mac.
  3. Authorize on your mobile.
  4. Happy debugging!!

* This is now "Remote devices".

Use Ant for running program with command line arguments

The only effective mechanism for passing parameters into a build is to use Java properties:

ant -Done=1 -Dtwo=2

The following example demonstrates how you can check and ensure the expected parameters have been passed into the script

<project name="check" default="build">

    <condition property="params.set">
        <and>
            <isset property="one"/>
            <isset property="two"/>
        </and>
    </condition>

    <target name="check">
        <fail unless="params.set">
        Must specify the parameters: one, two
        </fail>
    </target>

    <target name="build" depends="check">
        <echo>
        one = ${one}
        two = ${two}
        </echo>
    </target>

</project>

PHP Warning: Division by zero

when my divisor has 0 value

if ($divisor == 0) {
    $divisor = 1;
}

Android get current Locale, not default

I´ve used this:

String currentLanguage = Locale.getDefault().getDisplayLanguage();
if (currentLanguage.toLowerCase().contains("en")) {
   //do something
}

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

As per keras tutorial, you can simply use the same tf.device scope as in regular tensorflow:

with tf.device('/gpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops in the LSTM layer will live on GPU:0

with tf.device('/cpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops in the LSTM layer will live on CPU:0

What is the easiest way to remove the first character from a string?

I kind of favor using something like:

asdf = "[12,23,987,43"
asdf[0] = '' 

p asdf
# >> "12,23,987,43"

I'm always looking for the fastest and most readable way of doing things:

require 'benchmark'

N = 1_000_000

puts RUBY_VERSION

STR = "[12,23,987,43"

Benchmark.bm(7) do |b|
  b.report('[0]') { N.times { "[12,23,987,43"[0] = '' } }
  b.report('sub') { N.times { "[12,23,987,43".sub(/^\[+/, "") } }

  b.report('gsub') { N.times { "[12,23,987,43".gsub(/^\[/, "") } }
  b.report('[1..-1]') { N.times { "[12,23,987,43"[1..-1] } }
  b.report('slice') { N.times { "[12,23,987,43".slice!(0) } }
  b.report('length') { N.times { "[12,23,987,43"[1..STR.length] } }

end

Running on my Mac Pro:

1.9.3
              user     system      total        real
[0]       0.840000   0.000000   0.840000 (  0.847496)
sub       1.960000   0.010000   1.970000 (  1.962767)
gsub      4.350000   0.020000   4.370000 (  4.372801)
[1..-1]   0.710000   0.000000   0.710000 (  0.713366)
slice     1.020000   0.000000   1.020000 (  1.020336)
length    1.160000   0.000000   1.160000 (  1.157882)

Updating to incorporate one more suggested answer:

require 'benchmark'

N = 1_000_000

class String
  def eat!(how_many = 1)
    self.replace self[how_many..-1]
  end

  def first(how_many = 1)
    self[0...how_many]
  end

  def shift(how_many = 1)
    shifted = first(how_many)
    self.replace self[how_many..-1]
    shifted
  end
  alias_method :shift!, :shift
end

class Array
  def eat!(how_many = 1)
    self.replace self[how_many..-1]
  end
end

puts RUBY_VERSION

STR = "[12,23,987,43"

Benchmark.bm(7) do |b|
  b.report('[0]') { N.times { "[12,23,987,43"[0] = '' } }
  b.report('sub') { N.times { "[12,23,987,43".sub(/^\[+/, "") } }

  b.report('gsub') { N.times { "[12,23,987,43".gsub(/^\[/, "") } }
  b.report('[1..-1]') { N.times { "[12,23,987,43"[1..-1] } }
  b.report('slice') { N.times { "[12,23,987,43".slice!(0) } }
  b.report('length') { N.times { "[12,23,987,43"[1..STR.length] } }
  b.report('eat!') { N.times { "[12,23,987,43".eat! } }
  b.report('reverse') { N.times { "[12,23,987,43".reverse.chop.reverse } }
end

Which results in:

2.1.2
              user     system      total        real
[0]       0.300000   0.000000   0.300000 (  0.295054)
sub       0.630000   0.000000   0.630000 (  0.631870)
gsub      2.090000   0.000000   2.090000 (  2.094368)
[1..-1]   0.230000   0.010000   0.240000 (  0.232846)
slice     0.320000   0.000000   0.320000 (  0.320714)
length    0.340000   0.000000   0.340000 (  0.341918)
eat!      0.460000   0.000000   0.460000 (  0.452724)
reverse   0.400000   0.000000   0.400000 (  0.399465)

And another using /^./ to find the first character:

require 'benchmark'

N = 1_000_000

class String
  def eat!(how_many = 1)
    self.replace self[how_many..-1]
  end

  def first(how_many = 1)
    self[0...how_many]
  end

  def shift(how_many = 1)
    shifted = first(how_many)
    self.replace self[how_many..-1]
    shifted
  end
  alias_method :shift!, :shift
end

class Array
  def eat!(how_many = 1)
    self.replace self[how_many..-1]
  end
end

puts RUBY_VERSION

STR = "[12,23,987,43"

Benchmark.bm(7) do |b|
  b.report('[0]') { N.times { "[12,23,987,43"[0] = '' } }
  b.report('[/^./]') { N.times { "[12,23,987,43"[/^./] = '' } }
  b.report('[/^\[/]') { N.times { "[12,23,987,43"[/^\[/] = '' } }
  b.report('sub+') { N.times { "[12,23,987,43".sub(/^\[+/, "") } }
  b.report('sub') { N.times { "[12,23,987,43".sub(/^\[/, "") } }
  b.report('gsub') { N.times { "[12,23,987,43".gsub(/^\[/, "") } }
  b.report('[1..-1]') { N.times { "[12,23,987,43"[1..-1] } }
  b.report('slice') { N.times { "[12,23,987,43".slice!(0) } }
  b.report('length') { N.times { "[12,23,987,43"[1..STR.length] } }
  b.report('eat!') { N.times { "[12,23,987,43".eat! } }
  b.report('reverse') { N.times { "[12,23,987,43".reverse.chop.reverse } }
end

Which results in:

# >> 2.1.5
# >>               user     system      total        real
# >> [0]       0.270000   0.000000   0.270000 (  0.270165)
# >> [/^./]    0.430000   0.000000   0.430000 (  0.432417)
# >> [/^\[/]   0.460000   0.000000   0.460000 (  0.458221)
# >> sub+      0.590000   0.000000   0.590000 (  0.590284)
# >> sub       0.590000   0.000000   0.590000 (  0.596366)
# >> gsub      1.880000   0.010000   1.890000 (  1.885892)
# >> [1..-1]   0.230000   0.000000   0.230000 (  0.223045)
# >> slice     0.300000   0.000000   0.300000 (  0.299175)
# >> length    0.320000   0.000000   0.320000 (  0.325841)
# >> eat!      0.410000   0.000000   0.410000 (  0.409306)
# >> reverse   0.390000   0.000000   0.390000 (  0.393044)

Here's another update on faster hardware and a newer version of Ruby:

2.3.1
              user     system      total        real
[0]       0.200000   0.000000   0.200000 (  0.204307)
[/^./]    0.390000   0.000000   0.390000 (  0.387527)
[/^\[/]   0.360000   0.000000   0.360000 (  0.360400)
sub+      0.490000   0.000000   0.490000 (  0.492083)
sub       0.480000   0.000000   0.480000 (  0.487862)
gsub      1.990000   0.000000   1.990000 (  1.988716)
[1..-1]   0.180000   0.000000   0.180000 (  0.181673)
slice     0.260000   0.000000   0.260000 (  0.266371)
length    0.270000   0.000000   0.270000 (  0.267651)
eat!      0.400000   0.010000   0.410000 (  0.398093)
reverse   0.340000   0.000000   0.340000 (  0.344077)

Why is gsub so slow?

After doing a search/replace, gsub has to check for possible additional matches before it can tell if it's finished. sub only does one and finishes. Consider gsub like it's a minimum of two sub calls.

Also, it's important to remember that gsub, and sub can also be handicapped by poorly written regex which match much more slowly than a sub-string search. If possible anchor the regex to get the most speed from it. There are answers here on Stack Overflow demonstrating that so search around if you want more information.

Listening for variable changes in JavaScript

With the help of getter and setter, you can define a JavaScript class that does such a thing.

First, we define our class called MonitoredVariable:

class MonitoredVariable {
  constructor(initialValue) {
    this._innerValue = initialValue;
    this.beforeSet = (newValue, oldValue) => {};
    this.beforeChange = (newValue, oldValue) => {};
    this.afterChange = (newValue, oldValue) => {};
    this.afterSet = (newValue, oldValue) => {};
  }

  set val(newValue) {
    const oldValue = this._innerValue;
    // newValue, oldValue may be the same
    this.beforeSet(newValue, oldValue);
    if (oldValue !== newValue) {
      this.beforeChange(newValue, oldValue);
      this._innerValue = newValue;
      this.afterChange(newValue, oldValue);
    }
    // newValue, oldValue may be the same
    this.afterSet(newValue, oldValue);
  }

  get val() {
    return this._innerValue;
  }
}

Assume that we want to listen for money changes, let's create an instance of MonitoredVariable with initial money 0:

const money = new MonitoredVariable(0);

Then we could get or set its value using money.val:

console.log(money.val); // Get its value
money.val = 2; // Set its value

Since we have not defined any listeners for it, nothing special happens after money.val changes to 2.

Now let's define some listeners. We have four listeners available: beforeSet, beforeChange, afterChange, afterSet. The following will happen sequentially when you use money.val = newValue to change variable's value:

  1. money.beforeSet(newValue, oldValue);
  2. money.beforeChange(newValue, oldValue); (Will be skipped if its value not changed)
  3. money.val = newValue;
  4. money.afterChange(newValue, oldValue); (Will be skipped if its value not changed)
  5. money.afterSet(newValue, oldValue);

Now we define afterChange listener which be triggered only after money.val has changed (while afterSet will be triggered even if the new value is the same as the old one):

money.afterChange = (newValue, oldValue) => {
  console.log(`Money has been changed from ${oldValue} to ${newValue}`);
};

Now set a new value 3 and see what happens:

money.val = 3;

You will see the following in the console:

Money has been changed from 2 to 3

For full code, see https://gist.github.com/yusanshi/65745acd23c8587236c50e54f25731ab.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

This is not a new answer but will help somebody who's not sure how to set primary key for their table. Use this in a new query and run. This will set UniqueID column as primary key.

USE [YourDatabaseName]
GO

Alter table  [dbo].[YourTableNname]
Add Constraint PK_YourTableName_UniqueID Primary Key Clustered (UniqueID);
GO

Find a string within a cell using VBA

For a search routine you should look to use Find, AutoFilter or variant array approaches. Range loops are nomally too slow, worse again if they use Select

The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2 which you can then further process

Option Explicit

Const strText As String = "%"

Sub ColSearch_DelRows()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim cel1 As Range
    Dim cel2 As Range
    Dim strFirstAddress As String
    Dim lAppCalc As Long


    'Get working range from user
    On Error Resume Next
    Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub

    With Application
        lAppCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)

    'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
    If Not cel1 Is Nothing Then
        Set rng2 = cel1
        strFirstAddress = cel1.Address
        Do
            Set cel1 = rng1.FindNext(cel1)
            Set rng2 = Union(rng2, cel1)
        Loop While strFirstAddress <> cel1.Address
    End If

    If Not rng2 Is Nothing Then
        For Each cel2 In rng2
            Debug.Print cel2.Address & " contained " & strText
        Next
    Else
        MsgBox "No " & strText
    End If

    With Application
        .ScreenUpdating = True
        .Calculation = lAppCalc
    End With

End Sub

How to check whether particular port is open or closed on UNIX?

netstat -ano|grep 443|grep LISTEN

will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).

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

I followed the steps in killthrush's answer and to my surprise it did not work. Logging in as sa I could see my Windows domain user and had made them a sysadmin, but when I tried logging in with Windows auth I couldn't see my login under logins, couldn't create databases, etc. Then it hit me. That login was probably tied to another domain account with the same name (with some sort of internal/hidden ID that wasn't right). I had left this organization a while back and then came back months later. Instead of re-activating my old account (which they might have deleted) they created a new account with the same domain\username and a new internal ID. Using sa I deleted my old login, re-added it with the same name and added sysadmin. I logged back in with Windows Auth and everything looks as it should. I can now see my logins (and others) and can do whatever I need to do as a sysadmin using my Windows auth login.

In PowerShell, how do I test whether or not a specific variable exists in global scope?

There's an even easier way:

if ($variable)
{
    Write-Host "bar exist"
}
else
{
    Write-Host "bar does not exists"
}

Why would an Enum implement an Interface?

It's required for extensibility -- if someone uses an API you've developed, the enums you define are static; they can't be added to or modified. However, if you let it implement an interface, the person using the API can develop their own enum using the same interface. You can then register this enum with an enum manager which conglomerates the enums together with the standard interface.

Edit: @Helper Method has the perfect example of this. Think about having other libraries defining new operators and then telling a manager class that 'hey, this enum exists -- register it'. Otherwise, you'd only be able to define Operators in your own code - there'd be no extensibility.

How to retrieve an Oracle directory path?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Get human readable version of file size?

You should use "humanize".

>>> humanize.naturalsize(1000000)
'1.0 MB'
>>> humanize.naturalsize(1000000, binary=True)
'976.6 KiB'
>>> humanize.naturalsize(1000000, gnu=True)
'976.6K'

Reference:

https://pypi.org/project/humanize/

How can I make a Python script standalone executable to run without ANY dependency?

You can use PyInstaller to package Python programs as standalone executables. It works on Windows, Linux, and Mac.

PyInstaller Quickstart

Install PyInstaller from PyPI:

pip install pyinstaller

Go to your program’s directory and run:

pyinstaller yourprogram.py

This will generate the bundle in a subdirectory called dist.

For a more detailed walkthrough, see the manual.

How do you compare structs for equality in C?

It depends on whether the question you are asking is:

  1. Are these two structs the same object?
  2. Do they have the same value?

To find out if they are the same object, compare pointers to the two structs for equality. If you want to find out in general if they have the same value you have to do a deep comparison. This involves comparing all the members. If the members are pointers to other structs you need to recurse into those structs too.

In the special case where the structs do not contain pointers you can do a memcmp to perform a bitwise comparison of the data contained in each without having to know what the data means.

Make sure you know what 'equals' means for each member - it is obvious for ints but more subtle when it comes to floating-point values or user-defined types.

Going through a text file line by line in C

To read a line from a file, you should use the fgets function: It reads a string from the specified file up to either a newline character or EOF.

The use of sscanf in your code would not work at all, as you use filename as your format string for reading from line into a constant string literal %s.

The reason for SEGV is that you write into the non-allocated memory pointed to by line.

Arguments to main in C

Had made just a small change to @anthony code so we can get nicely formatted output with argument numbers and values. Somehow easier to read on output when you have multiple arguments:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("The following arguments were passed to main():\n");
    printf("argnum \t value \n");
    for (int i = 0; i<argc; i++) printf("%d \t %s \n", i, argv[i]);
    printf("\n");

    return 0;
} 

And output is similar to:

The following arguments were passed to main():
0        D:\Projects\test\vcpp\bcppcomp1\Debug\bcppcomp.exe
1        -P
2        TestHostAttoshiba
3        _http._tcp
4        local
5        80
6        MyNewArgument
7        200.124.211.235
8        type=NewHost
9        test=yes
10       result=output

How to get a unique device ID in Swift?

For Swift 3.X Latest Working Code, Easily usage;

   let deviceID = UIDevice.current.identifierForVendor!.uuidString
   print(deviceID)

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

Only to supplement. If you need to pass a variable and iterate it, you can do just like so:

function start(counter){
  if(counter < 10){
    setTimeout(function(){
      counter++;
      console.log(counter);
      start(counter);
    }, 1000);
  }
}
start(0);

Output:

1
2
3
...
9
10

One line per second.

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['auth_type'] = 'cookie';

should work.

From the manual:

auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.

Find rows that have the same value on a column in MySQL

I know this is a very old question but this is more for someone else who might have the same problem and I think this is more accurate to what was wanted.

SELECT * FROM member WHERE email = (Select email From member Where login_id = [email protected]) 

This will return all records that have [email protected] as a login_id value.

Simple parse JSON from URL on Android and display in listview

try as:

 // your get json request to server.. 
 HttpResponse response = httpClient.execute(httpPost);
 HttpEntity entity = response.getEntity();

 if(entity != null){
    JSONObject respObject = new JSONObject(EntityUtils.toString(entity));
    String active = respObject.getString("active");   
    String name = respObject.getString("name");  
    String tab1_text = respObject.getString("tab1_text");  
    //.... 
  }
else{
       //Do something here...
    }

see this example for Getting and parsing json response from server :

http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/

Twig: in_array or similar possible within if statement?

Try this

{% if var in ['foo', 'bar', 'beer'] %}
    ...
{% endif %}

HTML5 Canvas: Zooming

One option is to use css zoom feature:

$("#canvas_id").css("zoom","x%"); 

Pass parameter to controller from @Html.ActionLink MVC 4

You are using a wrong overload of the Html.ActionLink helper. What you think is routeValues is actually htmlAttributes! Just look at the generated HTML, you will see that this anchor's href property doesn't look as you expect it to look.

Here's what you are using:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // routeValues
    new {                                                     // htmlAttributes
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    }
)

and here's what you should use:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // controllerName
    new {                                                     // routeValues
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    },
    null                                                      // htmlAttributes
)

Also there's another very serious issue with your code. The following routeValue:

replyblogPostmodel = Model

You cannot possibly pass complex objects like this in an ActionLink. So get rid of it and also remove the BlogPostModel parameter from your controller action. You should use the blogPostId parameter to retrieve the model from wherever this model is persisted, or if you prefer from wherever you retrieved the model in the GET action:

public ActionResult BlogReplyCommentAdd(int blogPostId, bool captchaValid)
{
    BlogPostModel model = repository.Get(blogPostId);
    ...
}

As far as your initial problem is concerned with the wrong overload I would recommend you writing your helpers using named parameters:

@Html.ActionLink(
    linkText: "Reply",
    actionName: "BlogReplyCommentAdd",
    controllerName: "Blog",
    routeValues: new {
        blogPostId = blogPostId, 
        captchaValid = Model.AddNewComment.DisplayCaptcha
    },
    htmlAttributes: null
)

Now not only that your code is more readable but you will never have confusion between the gazillions of overloads that Microsoft made for those helpers.

How do I create an executable in Visual Studio 2013 w/ C++?

Just click on "Build" on the top menu and then click on "Publish ".... Then a pop up will open and there u can define the folder which u want to save the .exe file and by clicking "Next" will allow u to set up the advanced settings... DONE!

TypeError : Unhashable type

The real reason because set does not work is the fact, that it uses the hash function to distinguish different values. This means that sets only allows hashable objects. Why a list is not hashable is already pointed out.

Android lollipop change navigation bar color

Here are some ways to change Navigation Bar color.

By the XML

1- values-v21/style.xml

<item name="android:navigationBarColor">@color/navigationbar_color</item>

Or if you want to do it only using the values/ folder then-

2- values/style.xml

<resources xmlns:tools="http://schemas.android.com/tools">

<item name="android:navigationBarColor" tools:targetApi="21">@color/navigationbar_color</item>

You can also change navigation bar color By Programming.

 if (Build.VERSION.SDK_INT >= 21)
    getWindow().setNavigationBarColor(getResources().getColor(R.color.navigationbar_color));

By Using Compat Library-

if (Build.VERSION.SDK_INT >= 21) {
    getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.primary));
}

please find the link for more details- http://developer.android.com/reference/android/view/Window.html#setNavigationBarColor(int)

Submitting the value of a disabled input field

I wanna Disable an Input Field on a form and when i submit the form the values from the disabled form is not submitted.

Use Case: i am trying to get Lat Lng from Google Map and wanna Display it.. but dont want the user to edit it.

You can use the readonly property in your input field

<input type="text" readonly="readonly" />

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

When creating a Dockerfile, there are two commands that you can use to copy files/directories into it – ADD and COPY. Although there are slight differences in the scope of their function, they essentially perform the same task.

So, why do we have two commands, and how do we know when to use one or the other?

DOCKER ADD COMMAND

Let’s start by noting that the ADD command is older than COPY. Since the launch of the Docker platform, the ADD instruction has been part of its list of commands.

The command copies files/directories to a file system of the specified container.

The basic syntax for the ADD command is:

ADD <src> … <dest>

It includes the source you want to copy (<src>) followed by the destination where you want to store it (<dest>). If the source is a directory, ADD copies everything inside of it (including file system metadata).

For instance, if the file is locally available and you want to add it to the directory of an image, you type:

ADD /source/file/path  /destination/path

ADD can also copy files from a URL. It can download an external file and copy it to the wanted destination. For example:

ADD http://source.file/url  /destination/path

An additional feature is that it copies compressed files, automatically extracting the content in the given destination. This feature only applies to locally stored compressed files/directories.

ADD source.file.tar.gz /temp

Bear in mind that you cannot download and extract a compressed file/directory from a URL. The command does not unpack external packages when copying them to the local filesystem.

DOCKER COPY COMMAND

Due to some functionality issues, Docker had to introduce an additional command for duplicating content – COPY.

Unlike its closely related ADD command, COPY only has only one assigned function. Its role is to duplicate files/directories in a specified location in their existing format. This means that it doesn’t deal with extracting a compressed file, but rather copies it as-is.

The instruction can be used only for locally stored files. Therefore, you cannot use it with URLs to copy external files to your container.

To use the COPY instruction, follow the basic command format:

Type in the source and where you want the command to extract the content as follows:

COPY <src> … <dest> 

For example:

COPY /source/file/path  /destination/path 

Which command to use?(Best Practice)

Considering the circumstances in which the COPY command was introduced, it is evident that keeping ADD was a matter of necessity. Docker released an official document outlining best practices for writing Dockerfiles, which explicitly advises against using the ADD command.

Docker’s official documentation notes that COPY should always be the go-to instruction as it is more transparent than ADD.

If you need to copy from the local build context into a container, stick to using COPY.

The Docker team also strongly discourages using ADD to download and copy a package from a URL. Instead, it’s safer and more efficient to use wget or curl within a RUN command. By doing so, you avoid creating an additional image layer and save space.

What are ODEX files in Android?

This Blog article explains the internals of ODEX files:

WHAT IS AN ODEX FILE?

In Android file system, applications come in packages with the extension .apk. These application packages, or APKs contain certain .odex files whose supposed function is to save space. These ‘odex’ files are actually collections of parts of an application that are optimized before booting. Doing so speeds up the boot process, as it preloads part of an application. On the other hand, it also makes hacking those applications difficult because a part of the coding has already been extracted to another location before execution.

How Can I Remove “public/index.php” in the URL Generated Laravel?

1) Check whether mod_rewrite is enabled. Go to /etc/apache2/mods-enabled directory and see whether the rewrite.load is available. If not, enable it using the command sudo a2enmod rewrite.It will enable the rewrite module. If its already enabled, it will show the message Module rewrite already enabled.
2)Create a virtual host for public directory so that instead of giving http://localhost/public/index.php we will be able to use like that http://example.com/index.php. [hence public folder name will be hidded]
3)Then create a .htaccess which will hide the index.php from your url which shoul be inside the root directory (public folder)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]

How to copy folders to docker image from Dockerfile?

COPY . <destination>

Which would be in your case:

COPY . /

How to kill MySQL connections

In MySQL Workbench:

Left-hand side navigator > Management > Client Connections

It gives you the option to kill queries and connections.

Note: this is not TOAD like the OP asked, but MySQL Workbench users like me may end up here

How do you know a variable type in java?

I learned from the Search Engine(My English is very bad , So code...) How to get variable's type? Up's :

String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String

this method :

str.getClass().getSimpleName();
value:String

now example:

Object o = 1;
o.getClass().getSimpleName();
value:Integer

How can I connect to a Tor hidden service using cURL in PHP?

I use Privoxy and cURL to scrape Tor pages:

<?php
    $ch = curl_init('http://jhiwjjlqpyawmpjx.onion'); // Tormail URL
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
    curl_setopt($ch, CURLOPT_PROXY, "localhost:8118"); // Default privoxy port
    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    curl_exec($ch);
    curl_close($ch);
?>

After installing Privoxy you need to add this line to the configuration file (/etc/privoxy/config). Note the space and '.' a the end of line.

forward-socks4a / localhost:9050 .

Then restart Privoxy.

/etc/init.d/privoxy restart

Multiple aggregations of the same column using pandas GroupBy.agg()

TLDR; Pandas groupby.agg has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use

df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))

           Mean       Sum
dummy                    
1      0.036901  0.369012

OR

df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')

           Mean       Sum
dummy                    
1      0.036901  0.369012

Pandas >= 0.25: Named Aggregation

Pandas has changed the behavior of GroupBy.agg in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.

From the documentation,

To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in GroupBy.agg(), known as “named aggregation”, where

  • The keywords are the output column names
  • The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.

You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>).

import pandas as pd

pd.__version__                                                                                                                            
# '0.25.0.dev0+840.g989f912ee'

# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                   'height': [9.1, 6.0, 9.5, 34.0],
                   'weight': [7.9, 7.5, 9.9, 198.0]
})

df.groupby('kind').agg(
    max_height=('height', 'max'), min_weight=('weight', 'min'),)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

Alternatively, you can use pd.NamedAgg (essentially a namedtuple) which makes things more explicit.

df.groupby('kind').agg(
    max_height=pd.NamedAgg(column='height', aggfunc='max'), 
    min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

It is even simpler for Series, just pass the aggfunc to a keyword argument.

df.groupby('kind')['height'].agg(max_height='max', min_height='min')    

      max_height  min_height
kind                        
cat          9.5         9.1
dog         34.0         6.0       

Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:

df.groupby('kind')['height'].agg(**{'max height': 'max', ...})

Pandas < 0.25

In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning:

df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed 
# in a future version

Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.

df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})

        returns          
            op1       op2
dummy                    
1      0.328953  0.032895

Or,

df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])

            op1       op2
dummy                    
1      0.328953  0.032895

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

How can you check for a #hash in a URL using JavaScript?

sometimes you get the full query string such as "#anchorlink?firstname=mark"

this is my script to get the hash value:

var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);

returns -> #anchorlink

how to use DEXtoJar

Follow the below steps to do so_

  1. Rename your APK file(e.g., rename your APK file to .zip Ex- test.apk -> test.zip) & extract resultant zip file.
  2. Copy your .dex file in to dex2jar folder.
  3. Run setclasspath.bat. This should be run because this data is used in the next step.
  4. Go to Windows Command prompt, change the folder path to the path of your dex2jar folder and run the command as follows: d2j-dex2jar.bat classes.dex
  5. enjoy!! Your jar file will be ready in the same folder with name classes_dex2jar.jar.

Hope this helps you and All reading this... :)

Save array in mysql database

To convert any array (or any object) into a string using PHP, call the serialize():

$array = array( 1, 2, 3 );
$string = serialize( $array );
echo $string;

$string will now hold a string version of the array. The output of the above code is as follows:

a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}

To convert back from the string to the array, use unserialize():

// $array will contain ( 1, 2, 3 )
$array = unserialize( $string );

Passing data between controllers in Angular JS?

I don't know if it will help anyone, but based on Charx (thanks!) answer I have created simple cache service. Feel free to use, remix and share:

angular.service('cache', function() {
    var _cache, _store, _get, _set, _clear;
    _cache = {};

    _store = function(data) {
        angular.merge(_cache, data);
    };

    _set = function(data) {
        _cache = angular.extend({}, data);
    };

    _get = function(key) {
        if(key == null) {
            return _cache;
        } else {
            return _cache[key];
        }
    };

    _clear = function() {
        _cache = {};
    };

    return {
        get: _get,
        set: _set,
        store: _store,
        clear: _clear
    };
});

Decrementing for loops

range step should be -1

   for k in range(10,0,-1):
      print k

How can I escape a single quote?

You could try using: &#145;

Return Bit Value as 1/0 and NOT True/False in SQL Server

 Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
              ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME

in your query for only true or false column

What does `return` keyword mean inside `forEach` function?

From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

how to create a cookie and add to http response from inside my service layer?

Following @Aravind's answer with more details

@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
    myServiceMethodSettingCookie(request, response);        //Do service call passing the response
    return new ModelAndView("CustomerAddView");
}

// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
    final String cookieName = "my_cool_cookie";
    final String cookieValue = "my cool value here !";  // you could assign it some encoded value
    final Boolean useSecureCookie = false;
    final int expiryTime = 60 * 60 * 24;  // 24h in seconds
    final String cookiePath = "/";

    Cookie cookie = new Cookie(cookieName, cookieValue);

    cookie.setSecure(useSecureCookie);  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL

    cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

    cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories

    response.addCookie(cookie);
}

Related docs:

http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html

http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case, the error was triggered by duplicating an import of a component in the module.

javascript push multidimensional array

Arrays must have zero based integer indexes in JavaScript. So:

var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);

Or maybe you want to use objects (which are associative arrays):

var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);

which is equivalent to:

var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);

It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.

Command line input in Python

It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:

For interactive user input (or piped commands or redirected input)

Use raw_input in Python 2.x, and input in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)

For example:

user_input = raw_input("Some input please: ")

More details can be found here.

So, for example, you might have a script that looks like this

# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)

# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3

# Now do something with the above
print(user_input)

If you saved this in foo.py, you could just call the script from the command line, it would print out tok tiktok, then ask you for input. You could enter bar baz (followed by the enter key) and it would print bar baz. Here's what that would look like:

$ python foo.py
tok tiktok
Some input please: bar baz
bar baz

Here, $ represents the command-line prompt (so you don't actually type that), and I hit Enter after typing bar baz when it asked for input.

For command-line arguments

Suppose you have a script named foo.py and want to call it with arguments bar and baz from the command line like

$ foo.py bar baz

(Again, $ represents the command-line prompt.) Then, you can do that with the following in your script:

import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]

Here, the variable arg1 will contain the string 'bar', and arg2 will contain 'baz'. The object sys.argv is just a list containing everything from the command line. Note that sys.argv[0] is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:].

What is the OAuth 2.0 Bearer Token exactly?

Bearer token is one or more repetition of alphabet, digit, "-" , "." , "_" , "~" , "+" , "/" followed by 0 or more "=".

RFC 6750 2.1. Authorization Request Header Field (Format is ABNF (Augmented BNF))

The syntax for Bearer credentials is as follows:

     b64token    = 1*( ALPHA / DIGIT /
                       "-" / "." / "_" / "~" / "+" / "/" ) *"="
     credentials = "Bearer" 1*SP b64token

It looks like Base64 but according to Should the token in the header be base64 encoded?, it is not.

Digging a bit deeper in to "HTTP/1.1, part 7: Authentication"**, however, I see that b64token is just an ABNF syntax definition allowing for characters typically used in base64, base64url, etc.. So the b64token doesn't define any encoding or decoding but rather just defines what characters can be used in the part of the Authorization header that will contain the access token.

This fully addresses the first 3 items in the OP question's list. So I'm extending this answer to address the 4th question, about whether the token must be validated, so @mon feel free to remove or edit:

The authorizer is responsible for accepting or rejecting the http request. If the authorizer says the token is valid, it's up to you to decide what this means:

  • Does the authorizer have a way of inspecting the URL, identifying the operation, and looking up some role-based access control database to see if it is allowed? If yes and the request comes through, the service can assume it is allowed, and does not need to verify.
  • Is the token an all-or-nothing, so if the token is correct, all operations are allowed? Then the service doesn't need to verify.
  • Does the token mean "this request is allowed, but here is the UUID for the role, you check whether the operation is allowed". Then it's up to the service to look up that role, and see if the operation is allowed.

References

jQuery - simple input validation - "empty" and "not empty"

Actually there is a simpler way to do this, just:

if ($("#input").is(':empty')) {
console.log('empty');
} else {
console.log('not empty');
}

src: https://www.geeksforgeeks.org/how-to-check-an-html-element-is-empty-using-jquery/

Git push failed, "Non-fast forward updates were rejected"

Pull changes first:

git pull origin branch_name

How to implement a Keyword Search in MySQL?

For a single keyword on VARCHAR fields you can use LIKE:

SELECT id, category, location
FROM table
WHERE
(
    category LIKE '%keyword%'
    OR location LIKE '%keyword%'
)

For a description you're usually better adding a full text index and doing a Full-Text Search (MyISAM only):

SELECT id, description
FROM table
WHERE MATCH (description) AGAINST('keyword1 keyword2')

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Render is

def render(request, *args, **kwargs):
    """ Simple wrapper for render_to_response. """
    kwargs['context_instance'] = RequestContext(request)
    return render_to_response(*args, **kwargs)

So there is really no difference between render_to_response except it wraps your context making the template pre-processors work.

Direct to template is a generic view.

There is really no sense in using it here because there is overhead over render_to_response in the form of view function.

Converting JSON to XLS/CSV in Java

you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.

Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html

If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.

HTML Display Current date

This helped me:

<p>Date/Time: <span id="datetime"></span></p><script>var dt = new Date();
document.getElementById("datetime").innerHTML=dt.toLocaleString();</script>    

How to add image in Flutter

To use image in Flutter. Do these steps.

1. Create a Directory inside assets folder named images. As shown in figure belowenter image description here

2. Put your desired images to images folder.

3. Open pubpsec.yaml file . And add declare your images.Like:--enter image description here

4. Use this images in your code as.

  Card(
            elevation: 10,
              child: Container(
              decoration: BoxDecoration(
                color: Colors.orangeAccent,
              image: DecorationImage(
              image: AssetImage("assets/images/dropbox.png"),
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
          ),
          ),
          child: Text("$index",style: TextStyle(color: Colors.red,fontSize: 16,fontFamily:'LangerReguler')),
                alignment: Alignment.center,
          ),
          );

Is it better practice to use String.format over string Concatenation in Java?

Generally, string concatenation should be prefered over String.format. The latter has two main disadvantages:

  1. It does not encode the string to be built in a local manner.
  2. The building process is encoded in a string.

By point 1, I mean that it is not possible to understand what a String.format() call is doing in a single sequential pass. One is forced to go back and forth between the format string and the arguments, while counting the position of the arguments. For short concatenations, this is not much of an issue. In these cases however, string concatenation is less verbose.

By point 2, I mean that the important part of the building process is encoded in the format string (using a DSL). Using strings to represent code has many disadvantages. It is not inherently type-safe, and complicates syntax-highlighting, code analysis, optimization, etc.

Of course, when using tools or frameworks external to the Java language, new factors can come into play.

Is there a function to copy an array in C/C++?

You can use the memcpy(),

void * memcpy ( void * destination, const void * source, size_t num );

memcpy() copies the values of num bytes from the location pointed by source directly to the memory block pointed by destination.

If the destination and source overlap, then you can use memmove().

void * memmove ( void * destination, const void * source, size_t num );

memmove() copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.

Nginx not picking up site in sites-enabled?

Changing from:

include /etc/nginx/sites-enabled/*; 

to

include /etc/nginx/sites-enabled/*.*; 

fixed my issue

How do I register a DLL file on Windows 7 64-bit?

Knowing the error message would be rather valuable. It is meant to provide info, even though it doesn't make any sense to you it does to us. Being forced to guess, I'd say that the DLL is a 32-bit DirectX filter. In which case this should be the proper course of action:

cd c:\windows\syswow64
move ..\system32\dllname.ax .
regsvr32.exe dllname.ax

This must be run at an elevated command prompt so that UAC cannot stop the registry access that's required. Ask more questions about this at superuser.com

How can I check the extension of a file?

An old thread, but may help future readers...

I would avoid using .lower() on filenames if for no other reason than to make your code more platform independent. (linux is case sensistive, .lower() on a filename will surely corrupt your logic eventually ...or worse, an important file!)

Why not use re? (Although to be even more robust, you should check the magic file header of each file... How to check type of files without extensions in python? )

import re

def checkext(fname):   
    if re.search('\.mp3$',fname,flags=re.IGNORECASE):
        return('mp3')
    if re.search('\.flac$',fname,flags=re.IGNORECASE):
        return('flac')
    return('skip')

flist = ['myfile.mp3', 'myfile.MP3','myfile.mP3','myfile.mp4','myfile.flack','myfile.FLAC',
     'myfile.Mov','myfile.fLaC']

for f in flist:
    print "{} ==> {}".format(f,checkext(f)) 

Output:

myfile.mp3 ==> mp3
myfile.MP3 ==> mp3
myfile.mP3 ==> mp3
myfile.mp4 ==> skip
myfile.flack ==> skip
myfile.FLAC ==> flac
myfile.Mov ==> skip
myfile.fLaC ==> flac

How to get distinct values for non-key column fields in Laravel?

You should use groupby. In Query Builder you can do it this way:

$users = DB::table('users')
            ->select('id','name', 'email')
            ->groupBy('name')
            ->get();

Which comment style should I use in batch files?

A very detailed and analytic discussion on the topic is available on THIS page

It has the example codes and the pros/cons of different options.

How does the @property decorator work in Python?

Documentation says it's just a shortcut for creating readonly properties. So

@property
def x(self):
    return self._x

is equivalent to

def getx(self):
    return self._x
x = property(getx)

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Setting locales in terminal resolved the issue for me. Open the terminal and

  1. Check if locale settings are missing

    > locale
    LANG=
    LC_COLLATE="C"
    LC_CTYPE="UTF-8"
    LC_MESSAGES="C"
    LC_MONETARY="C"
    LC_NUMERIC="C"
    LC_TIME="C"
    LC_ALL=
    
  2. Edit ~/.profile or ~/.bashrc

    export LANG=en_US.UTF-8
    export LC_ALL=en_US.UTF-8
    
  3. Run . ~/.profile or . ~/.bashrc to read from the file.

  4. Open a new terminal window and check that the locales are properly set

    > locale
    LANG="en_US.UTF-8"
    LC_COLLATE="en_US.UTF-8"
    LC_CTYPE="en_US.UTF-8"
    LC_MESSAGES="en_US.UTF-8"
    LC_MONETARY="en_US.UTF-8"
    LC_NUMERIC="en_US.UTF-8"
    LC_TIME="en_US.UTF-8"
    LC_ALL="en_US.UTF-8"
    

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

How can I disable editing cells in a WPF Datagrid?

The DataGrid has an XAML property IsReadOnly that you can set to true:

<my:DataGrid
    IsReadOnly="True"
/>

How can I compare two dates in PHP?

Here's my spin on how to get the difference in days between two dates with PHP. Note the use of '!' in the format to discard the time part of the dates, thanks to info from DateTime createFromFormat without time.

$today = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));
$wanted = DateTime::createFromFormat('!d-m-Y', $row["WANTED_DELIVERY_DATE"]);
$diff = $today->diff($wanted);
$days = $diff->days;
if (($diff->invert) != 0) $days = -1 * $days;
$overdue = (($days < 0) ? true : false);
print "<!-- (".(($days > 0) ? '+' : '').($days).") -->\n";

Appending to list in Python dictionary

dates_dict[key] = dates_dict.get(key, []).append(date) sets dates_dict[key] to None as list.append returns None.

In [5]: l = [1,2,3]

In [6]: var = l.append(3)

In [7]: print var
None

You should use collections.defaultdict

import collections
dates_dict = collections.defaultdict(list)

Position Absolute + Scrolling

position: fixed; will solve your issue. As an example, review my implementation of a fixed message area overlay (populated programmatically):

#mess {
    position: fixed;
    background-color: black;
    top: 20px;
    right: 50px;
    height: 10px;
    width: 600px;
    z-index: 1000;
}

And in the HTML

<body>
    <div id="mess"></div>
    <div id="data">
        Much content goes here.
    </div>
</body>

When #data becomes longer tha the sceen, #mess keeps its position on the screen, while #data scrolls under it.

Setting max-height for table cell contents

Another way around it that may/may not suit but surely the simplest:

td {
    display: table-caption;
}

Inserting a string into a list without getting split into characters

You have to add another list:

list[:0]=['foo']

How do you dynamically allocate a matrix?

You can also use std::vectors for achieving this:

using std::vector< std::vector<int> >

Example:

std::vector< std::vector<int> > a;

  //m * n is the size of the matrix

    int m = 2, n = 4;
    //Grow rows by m
    a.resize(m);
    for(int i = 0 ; i < m ; ++i)
    {
        //Grow Columns by n
        a[i].resize(n);
    }
    //Now you have matrix m*n with default values

    //you can use the Matrix, now
    a[1][0]=1;
    a[1][1]=2;
    a[1][2]=3;
    a[1][3]=4;

//OR
for(i = 0 ; i < m ; ++i)
{
    for(int j = 0 ; j < n ; ++j)
    {      //modify matrix
        int x = a[i][j];
    }

}

android ellipsize multiline textview

In my case, there is no need to code this in Java. Everything works as expected. No need for something like android:singleLine="false".

<TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:ellipsize="end"
  android:maxLines="4"
  android:text="@string/very_long_text" />

But there seems to be a bug in the layout preview of Android Studio (v3.0): layout preview

Given Android 7.1.1 on my device this is working: device screenshot

How to make grep only match if the entire line matches?

This worked well for me when trying to do something similar:

grep -F ABB.log a.tmp

Set cursor position on contentEditable <div>

You can leverage selectNodeContents which is supported by modern browsers.

var el = document.getElementById('idOfYoursContentEditable');
var selection = window.getSelection();
var range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(el);
range.collapse(false);
selection.addRange(range);
el.focus();

Change the On/Off text of a toggle button Android

You can do this by 2 options:

Option 1: By setting its xml attributes

 `android:textOff="TEXT OFF"
  android:textOn="TEXT ON"`

Option 2: Programmatically

Set the attribute onClick: methodNameHere (mine is toggleState) Then write this code:

public void toggleState(View view) {
   boolean toggle = ((ToogleButton)view).isChecked();
   if (toggle){
       ((ToogleButton)view).setTextOn("TEXT ON");
   } else {
      ((ToogleButton)view).setTextOff("TEXT OFF");
   }
}

PS: it works for me, hope it works for you too

jQuery - prevent default, then continue default

In a pure Javascript way, you can submit the form after preventing default.

This is because HTMLFormElement.submit() never calls the onSubmit(). So we're relying on that specification oddity to submit the form as if it doesn't have a custom onsubmit handler here.

var submitHandler = (event) => {
  event.preventDefault()
  console.log('You should only see this once')
  document.getElementById('formId').submit()
}

See this fiddle for a synchronous request.


Waiting for an async request to finish up is just as easy:

var submitHandler = (event) => {
  event.preventDefault()
  console.log('before')
  setTimeout(function() {
    console.log('done')
    document.getElementById('formId').submit()
  }, 1400);
  console.log('after')
}

You can check out my fiddle for an example of an asynchronous request.


And if you are down with promises:

var submitHandler = (event) => {
  event.preventDefault()
  console.log('Before')
    new Promise((res, rej) => {
      setTimeout(function() {
        console.log('done')
        res()
      }, 1400);
    }).then(() => {
      document.getElementById('bob').submit()
    })
  console.log('After')
}

And here's that request.

How to spawn a process and capture its STDOUT in .NET?

Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output:

process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
process.Start();
process.BeginOutputReadLine();

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

the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.

this code work with the library: https://github.com/tsayen/dom-to-image

*the "id_div" is the id of the element html that you want to transform.

**the "canvas_out" is the id of the div that will contain the canvas so try this code. :

   function Guardardiv(id_div){

      var mode = 2 // default 1 (save to image), mode 2 = save to canvas
      console.log("Process start");
      var node = document.getElementById(id_div);
      // get the div that will contain the canvas
      var canvas_out = document.getElementById('canvas_out');
      var canvas = document.createElement('canvas');
      canvas.width = node.scrollWidth;
      canvas.height = node.scrollHeight;

      domtoimage.toPng(node).then(function (pngDataUrl) {
          var img = new Image();
          img.onload = function () {
          var context = canvas.getContext('2d');
          context.drawImage(img, 0, 0);
        };

        if (mode == 1){ // save to image
             downloadURI(pngDataUrl, "salida.png");
        }else if (mode == 2){ // save to canvas
          img.src = pngDataUrl;
          canvas_out.appendChild(img);

        }
      console.log("Process finish");
    });

    }

so, if you want to save to image just add this function:

    function downloadURI(uri, name) {
        var link = document.createElement("a");

        link.download = name;
        link.href = uri;
        document.body.appendChild(link);
        link.click();   
    }

Example of use:

 <html>
 <head>
 </script src="/dom-to-image.js"></script>
 </head> 
 <body>
 <div id="container">
   All content that want to transform
  </div>
  <button onclick="Guardardiv('container');">Convert<button> 

 <!-- if use mode 2 -->
 <div id="canvas_out"></div>
 </html>

Comment if that work. Comenten si les sirvio :)

Converting a string to a date in JavaScript

ISO 8601-esque datestrings, as excellent as the standard is, are still not widely supported.

This is a great resource to figure out which datestring format you should use:

http://dygraphs.com/date-formats.html

Yes, that means that your datestring could be as simple as as opposed to

"2014/10/13 23:57:52" instead of "2014-10-13 23:57:52"

How can I detect the touch event of an UIImageView?

I've been on different threads on the past few hours trying to find a solution for my problem, to no avail. I see that many developers share this problem, and I think people here know about this. I have multiple images inside a UIScrollView, trying to get tap events on them.

I am not getting any events from an UIImangeView, but I do get an event from a similar UILable with very similar parameters I am setting to it. Under iOS 5.1.

I have already done the following:

  1. set setUserInteractionEnabled to YES for both `UIImageView and parent view .
  2. set setMultipleTouchEnabled to YES for UIImageView.
  3. Tried subclassing UIImageView, didn't help any.

Attaching some code below, in this code I initialize both a UIImageView and UILabel, the label works fine in terms of firing events. I tried keeping out irrelevant code.

UIImageView *single_view = [[UIImageView alloc]initWithFrame:CGRectMake(200, 200, 100, 100)];
single_view.image = img;
single_view.layer.zPosition = 4;

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
[single_view addGestureRecognizer:singleTap];
[single_view setMultipleTouchEnabled:YES];
[single_view setUserInteractionEnabled:YES];
[self.myScrollView addSubview:single_view];
self.myScrollView.userInteractionEnabled = YES;

UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
testLabel.backgroundColor = [UIColor redColor];
[self.myScrollView addSubview:testLabel];
[testLabel addGestureRecognizer:singleTap];
[testLabel setMultipleTouchEnabled:YES];
[testLabel setUserInteractionEnabled:YES];
testLabel.layer.zPosition = 4;

And the method which handles the event:

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
    UIView *tappedView = [gesture.view hitTest:[gesture locationInView:gesture.view] withEvent:nil];
    NSLog(@"Touch event on view: %@", [tappedView class]);
}

As said, the label tap is received.

Change WPF window background image in C# code

img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);

Making an asynchronous task in Flask

I would use Celery to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended).

app.py:

from flask import Flask
from celery import Celery

broker_url = 'amqp://guest@localhost'          # Broker URL for RabbitMQ task queue

app = Flask(__name__)    
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig')      # Your celery configurations in a celeryconfig.py

@celery.task(bind=True)
def some_long_task(self, x, y):
    # Do some long task
    ...

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    data = json.loads(request.data)
    text_list = data.get('text_list')
    final_file = audio_class.render_audio(data=text_list)
    some_long_task.delay(x, y)                 # Call your async task and pass whatever necessary variables
    return Response(
        mimetype='application/json',
        status=200
    )

Run your Flask app, and start another process to run your celery worker.

$ celery worker -A app.celery --loglevel=debug

I would also refer to Miguel Gringberg's write up for a more in depth guide to using Celery with Flask.

What is the best way to compare floats for almost-equality in Python?

The common wisdom that floating-point numbers cannot be compared for equality is inaccurate. Floating-point numbers are no different from integers: If you evaluate "a == b", you will get true if they are identical numbers and false otherwise (with the understanding that two NaNs are of course not identical numbers).

The actual problem is this: If I have done some calculations and am not sure the two numbers I have to compare are exactly correct, then what? This problem is the same for floating-point as it is for integers. If you evaluate the integer expression "7/3*3", it will not compare equal to "7*3/3".

So suppose we asked "How do I compare integers for equality?" in such a situation. There is no single answer; what you should do depends on the specific situation, notably what sort of errors you have and what you want to achieve.

Here are some possible choices.

If you want to get a "true" result if the mathematically exact numbers would be equal, then you might try to use the properties of the calculations you perform to prove that you get the same errors in the two numbers. If that is feasible, and you compare two numbers that result from expressions that would give equal numbers if computed exactly, then you will get "true" from the comparison. Another approach is that you might analyze the properties of the calculations and prove that the error never exceeds a certain amount, perhaps an absolute amount or an amount relative to one of the inputs or one of the outputs. In that case, you can ask whether the two calculated numbers differ by at most that amount, and return "true" if they are within the interval. If you cannot prove an error bound, you might guess and hope for the best. One way of guessing is to evaluate many random samples and see what sort of distribution you get in the results.

Of course, since we only set the requirement that you get "true" if the mathematically exact results are equal, we left open the possibility that you get "true" even if they are unequal. (In fact, we can satisfy the requirement by always returning "true". This makes the calculation simple but is generally undesirable, so I will discuss improving the situation below.)

If you want to get a "false" result if the mathematically exact numbers would be unequal, you need to prove that your evaluation of the numbers yields different numbers if the mathematically exact numbers would be unequal. This may be impossible for practical purposes in many common situations. So let us consider an alternative.

A useful requirement might be that we get a "false" result if the mathematically exact numbers differ by more than a certain amount. For example, perhaps we are going to calculate where a ball thrown in a computer game traveled, and we want to know whether it struck a bat. In this case, we certainly want to get "true" if the ball strikes the bat, and we want to get "false" if the ball is far from the bat, and we can accept an incorrect "true" answer if the ball in a mathematically exact simulation missed the bat but is within a millimeter of hitting the bat. In that case, we need to prove (or guess/estimate) that our calculation of the ball's position and the bat's position have a combined error of at most one millimeter (for all positions of interest). This would allow us to always return "false" if the ball and bat are more than a millimeter apart, to return "true" if they touch, and to return "true" if they are close enough to be acceptable.

So, how you decide what to return when comparing floating-point numbers depends very much on your specific situation.

As to how you go about proving error bounds for calculations, that can be a complicated subject. Any floating-point implementation using the IEEE 754 standard in round-to-nearest mode returns the floating-point number nearest to the exact result for any basic operation (notably multiplication, division, addition, subtraction, square root). (In case of tie, round so the low bit is even.) (Be particularly careful about square root and division; your language implementation might use methods that do not conform to IEEE 754 for those.) Because of this requirement, we know the error in a single result is at most 1/2 of the value of the least significant bit. (If it were more, the rounding would have gone to a different number that is within 1/2 the value.)

Going on from there gets substantially more complicated; the next step is performing an operation where one of the inputs already has some error. For simple expressions, these errors can be followed through the calculations to reach a bound on the final error. In practice, this is only done in a few situations, such as working on a high-quality mathematics library. And, of course, you need precise control over exactly which operations are performed. High-level languages often give the compiler a lot of slack, so you might not know in which order operations are performed.

There is much more that could be (and is) written about this topic, but I have to stop there. In summary, the answer is: There is no library routine for this comparison because there is no single solution that fits most needs that is worth putting into a library routine. (If comparing with a relative or absolute error interval suffices for you, you can do it simply without a library routine.)

How do you calculate the variance, median, and standard deviation in C++ or Java?

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

double sum = 0.0;
int length = 0;

for( double number : numbers ) {
    sum += number;
    length++;
}

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

double stddev = Math.sqrt( variance );

Delete branches in Bitbucket

In Android Studio, the options down the right corner of the IDE:

  • Change/checkout other local branch
  • Delete unwanted local branches (i.e. v0.0.1...)
  • Delete unwanted remote branches (i.e. origin/v0.0.1...) -- this step will delete branches in BitBucket if the branches are not prevented to be deleted and they are not the MAIN BRANCH.

Convert IEnumerable to DataTable

I've written a library to handle this for me. It's called DataTableProxy and is available as a NuGet package. Code and documentation is on Github

Calculate days between two Dates in Java 8

Use the DAYS in enum java.time.temporal.ChronoUnit . Below is the Sample Code :

Output : *Number of days between the start date : 2015-03-01 and end date : 2016-03-03 is ==> 368. **Number of days between the start date : 2016-03-03 and end date : 2015-03-01 is ==> -368*

package com.bitiknow.date;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

/**
 * 
 * @author pradeep
 *
 */
public class LocalDateTimeTry {
    public static void main(String[] args) {

        // Date in String format.
        String dateString = "2015-03-01";

        // Converting date to Java8 Local date
        LocalDate startDate = LocalDate.parse(dateString);
        LocalDate endtDate = LocalDate.now();
        // Range = End date - Start date
        Long range = ChronoUnit.DAYS.between(startDate, endtDate);
        System.out.println("Number of days between the start date : " + dateString + " and end date : " + endtDate
                + " is  ==> " + range);

        range = ChronoUnit.DAYS.between(endtDate, startDate);
        System.out.println("Number of days between the start date : " + endtDate + " and end date : " + dateString
                + " is  ==> " + range);

    }

}

Check if datetime instance falls in between other two datetime objects

You can, use:

if (date >= startDate && date<= EndDate) { return true; }