Programs & Examples On #Mutation testing

A method of software testing that involves modifying the source code or compiled intermediate code (Java: byte code, .NET: IL). Test suites that do not fail under each of these "mutations" is considered to be inadequate.

Detect Scroll Up & Scroll down in ListView

My solution works perfectly giving the exact value for each scroll direction. distanceFromFirstCellToTop contains the exact distance from the first cell to the top of the parent View. I save this value in previousDistanceFromFirstCellToTop and as I scroll I compare it with the new value. If it's lower then I scrolled up, else, I scrolled down.

private int previousDistanceFromFirstCellToTop;

listview.setOnScrollListener(new OnScrollListener() {

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        View firstCell = listview.getChildAt(0);
        int distanceFromFirstCellToTop = listview.getFirstVisiblePosition() * firstCell.getHeight() - firstCell.getTop();

        if(distanceFromFirstCellToTop < previousDistanceFromFirstCellToTop)
        {
           //Scroll Up
        }
        else if(distanceFromFirstCellToTop  > previousDistanceFromFirstCellToTop)
        {
           //Scroll Down
        }
        previousDistanceFromFirstCellToTop = distanceFromFirstCellToTop;
    }
});

For Xamarin developers, the solution is the following:

Note: don't forget to run on UI thread

listView.Scroll += (o, e) =>
{
    View firstCell = listView.GetChildAt(0);
    int distanceFromFirstCellToTop = listView.FirstVisiblePosition * firstCell.Height - firstCell.Top;

    if (distanceFromFirstCellToTop < previousDistanceFromFirstCellToTop)
    {
        //Scroll Up
    }
    else if (distanceFromFirstCellToTop > previousDistanceFromFirstCellToTop)
    {
        //Scroll Down
    }
    previousDistanceFromFirstCellToTop = distanceFromFirstCellToTop;
};

C++: Converting Hexadecimal to Decimal

    std::cout << "Enter decimal number: " ;
    std::cin >> input ;

    std::cout << "0x" << std::hex << input << '\n' ;

if your adding a input that can be a boolean or float or int it will be passed back in the int main function call...

With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.

Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square. With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.

Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square.

#include <iostream>
 using namespace std;
template <class T>      // function template
T square(T);    /* returns a value of type T and accepts                  type T     (int or float or whatever) */
  void main()
{
int x, y;
float w, z;
cout << "Enter a integer:  ";
cin >> x;
y = square(x);
cout << "The square of that number is:  " << y << endl;
cout << "Enter a float:  ";
cin >> w;
z = square(w);
cout << "The square of that number is:  " << z << endl;
}

template <class T>      // function template
T square(T u) //accepts a parameter u of type T (int or float)
{
return u * u;
}

Here is the output:

Enter a integer:  5
The square of that number is:  25
Enter a float:  5.3
The square of that number is:  28.09

How do I bottom-align grid elements in bootstrap fluid layout

.align-bottom {
    position: absolute;
    bottom: 10px;
    right: 10px;
}

How can I view array structure in JavaScript with alert()?

pass your js array to the function below and it will do the same as php print_r() function

 alert(print_r(your array));  //call it like this

function print_r(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects 
    for(var item in arr) {
        var value = arr[item];

        if(typeof(value) == 'object') { //If it is an array,
            dumped_text += level_padding + "'" + item + "' ...\n";
            dumped_text += print_r(value,level+1);
        } else {
            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
        }
    }
} else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}

PHP Sort a multidimensional array by element containing date

http://us2.php.net/manual/en/function.array-multisort.php see third example:

<?php

$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);

?>

fyi, using a unix (seconds from 1970) or mysql timestamp (YmdHis - 20100526014500) would be be easier for the parser but i think in your case it makes no difference.

Extending from two classes

Make an interface. Java doesn't have multiple inheritance.

http://csis.pace.edu/~bergin/patterns/multipleinheritance.html

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

rebase in progress. Cannot commit. How to proceed or stop (abort)?

You told your repository to rebase. It looks like you were on a commit (identified by SHA 9c168a5) and then did git rebase master or git pull --rebase master.

You are rebasing the branch master onto that commit. You can end the rebase via git rebase --abort. This would put back at the state that you were at before you started rebasing.

jQuery - checkbox enable/disable

<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="chk9[120]" class="chkGroup">
<input type="checkbox" name="chk9[140]" class="chkGroup">
<input type="checkbox" name="chk9[150]" class="chkGroup">
</form>

$("#chkAll").click(function() {
   $(".chkGroup").attr("checked", this.checked);
});

With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:

$(".chkGroup").click(function() {
  $("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;
});

how to run the command mvn eclipse:eclipse

I don't think one needs it any more. The latest versions of Eclipse have Maven plugin enabled. So you will just need to import a Maven project into Eclipse and no more as an existing project. Eclipse will create the needed .project, .settings, .classpath files based on your pom.xml and environment settings (installed Java version, etc.) . The earlier versions of Eclipse needed to have run the command mvn eclipse:eclipse which produced the same result.

AttributeError: can't set attribute in python

namedtuples are immutable, just like standard tuples. You have two choices:

  1. Use a different data structure, e.g. a class (or just a dictionary); or
  2. Instead of updating the structure, replace it.

The former would look like:

class N(object):

    def __init__(self, ind, set, v):
        self.ind = ind
        self.set = set
        self.v = v

And the latter:

item = items[node.ind]
items[node.ind] = N(item.ind, item.set, node.v)

Edit: if you want the latter, Ignacio's answer does the same thing more neatly using baked-in functionality.

Use space as a delimiter with cut command

To complement the existing, helpful answers; tip of the hat to QZ Support for encouraging me to post a separate answer:

Two distinct mechanisms come into play here:

  • (a) whether cut itself requires the delimiter (space, in this case) passed to the -d option to be a separate argument or whether it's acceptable to append it directly to -d.

  • (b) how the shell generally parses arguments before passing them to the command being invoked.

(a) is answered by a quote from the POSIX guidelines for utilities (emphasis mine)

If the SYNOPSIS of a standard utility shows an option with a mandatory option-argument [...] a conforming application shall use separate arguments for that option and its option-argument. However, a conforming implementation shall also permit applications to specify the option and option-argument in the same argument string without intervening characters.

In other words: In this case, because -d's option-argument is mandatory, you can choose whether to specify the delimiter as:

  • (s) EITHER: a separate argument
  • (d) OR: as a value directly attached to -d.

Once you've chosen (s) or (d), it is the shell's string-literal parsing - (b) - that matters:

  • With approach (s), all of the following forms are EQUIVALENT:

    • -d ' '
    • -d " "
    • -d \<space> # <space> used to represent an actual space for technical reasons
  • With approach (d), all of the following forms are EQUIVALENT:

    • -d' '
    • -d" "
    • "-d "
    • '-d '
    • d\<space>

The equivalence is explained by the shell's string-literal processing:

All solutions above result in the exact same string (in each group) by the time cut sees them:

  • (s): cut sees -d, as its own argument, followed by a separate argument that contains a space char - without quotes or \ prefix!.

  • (d): cut sees -d plus a space char - without quotes or \ prefix! - as part of the same argument.

The reason the forms in the respective groups are ultimately identical is twofold, based on how the shell parses string literals:

  • The shell allows literal to be specified as is through a mechanism called quoting, which can take several forms:
    • single-quoted strings: the contents inside '...' is taken literally and forms a single argument
    • double-quoted strings: the contents inside "..." also forms a single argument, but is subject to interpolation (expands variable references such as $var, command substitutions ($(...) or `...`), or arithmetic expansions ($(( ... ))).
    • \-quoting of individual characters: a \ preceding a single character causes that character to be interpreted as a literal.
  • Quoting is complemented by quote removal, which means that once the shell has parsed a command line, it removes the quote characters from the arguments (enclosing '...' or "..." or \ instances) - thus, the command being invoked never sees the quote characters.

Calling javascript function in iframe

Use:

document.getElementById("resultFrame").contentWindow.Reset();

to access the Reset function in the iframe

document.getElementById("resultFrame") will get the iframe in your code, and contentWindow will get the window object in the iframe. Once you have the child window, you can refer to javascript in that context.

Also see HERE in particular the answer from bobince.

How to run vbs as administrator from vbs?

Nice article for elevation options - http://www.novell.com/support/kb/doc.php?id=7010269

Configuring Applications to Always Request Elevated Rights:

Programs can be configured to always request elevation on the user level via registry settings under HKCU. These registry settings are effective on the fly, so they can be set immediately prior to launching a particular application and even removed as soon as the application is launched, if so desired. Simply create a "String Value" under "HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" for the full path to an executable with a value of "RUN AS ADMIN". Below is an example for CMD.

Windows Registry Editor Version 5.00
[HKEY_Current_User\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"c:\\windows\\system32\\cmd.exe"="RUNASADMIN"

Rownum in postgresql

Postgresql does not have an equivalent of Oracle's ROWNUM. In many cases you can achieve the same result by using LIMIT and OFFSET in your query.

What's a clean way to stop mongod on Mac OS X?

This is an old question, but its one I found while searching as well.

If you installed with brew then the solution would actually be the this:

launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist

how to send a post request with a web browser

You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.

As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox

Illegal access: this web application instance has been stopped already

If it's a local development tomcat launched from IDE, then restarting this IDE and rebuild project also helps.

Update:

You could also try to find if there is any running tomcat process in the background and kill it.

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

AngularJS - ng-if check string empty value

Probably your item.photo is undefined if you don't have a photo attribute on item in the first place and thus undefined != ''. But if you'd put some code to show how you provide values to item, it would help.

PS: Sorry to post this as an answer (I rather think it's more of a comment), but I don't have enough reputation yet.

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

I fixed this with below steps:

  1. Check your CDN scripts and add them locally.
  2. Move your scripts includes into the header section.

How to check if a string contains an element from a list in Python

Use a generator together with any, which short-circuits on the first True:

if any(ext in url_string for ext in extensionsToCheck):
    print(url_string)

EDIT: I see this answer has been accepted by OP. Though my solution may be "good enough" solution to his particular problem, and is a good general way to check if any strings in a list are found in another string, keep in mind that this is all that this solution does. It does not care WHERE the string is found e.g. in the ending of the string. If this is important, as is often the case with urls, you should look to the answer of @Wladimir Palant, or you risk getting false positives.

JavaScript string and number conversion

parseInt is misfeatured like scanf:

parseInt("12 monkeys", 10) is a number with value '12'
+"12 monkeys"              is a number with value 'NaN'
Number("12 monkeys")       is a number with value 'NaN'

How can I read user input from the console?

I think there are some compiler errors.

  • Writeline should be WriteLine (capital 'L')
  • missing semicolon at the end of a line

        double a, b;
        Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
        a = double.Parse(Console.ReadLine());
        b = a * Math.PI; // Missing colon!
        Console.WriteLine("Sonuç " + b);
    

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

You have quite a few options for this:

1 - If you can find an SVG file for the map you want, you can use something like RaphaelJS or SnapSVG to add click listeners for your states/regions, this solution is the most customizable...

2 - You can use dedicated tools such as clickablemapbuilder (free) or makeaclickablemap (i think free also).

[disclaimer] Im the author of clickablemapbuilder.com :)

CodeIgniter: "Unable to load the requested class"

I had a similar issue when deploying from OSx on my local to my Linux live site.

It ran fine on OSx, but on Linux I was getting:

An Error Was Encountered

Unable to load the requested class: Ckeditor

The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

I also changed my load call to match the capitalization:

$this->load->library('CKEditor');

Importing PNG files into Numpy?

Using just scipy, glob and having PIL installed (pip install pillow) you can use scipy's imread method:

from scipy import misc
import glob

for image_path in glob.glob("/home/adam/*.png"):
    image = misc.imread(image_path)
    print image.shape
    print image.dtype

UPDATE

According to the doc, scipy.misc.imread is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead. See the answer by Charles.

How to align a div to the top of its parent but keeping its inline-block behaviour?

Use vertical-align:top; for the element you want at the top, as I have demonstrated on your jsfiddle.

http://www.brunildo.org/test/inline-block.html

MySQL - How to select rows where value is in array?

By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:

$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';

If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:

$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';

Which version of CodeIgniter am I currently using?

you can easily find the current CodeIgniter version by

echo CI_VERSION 


or you can navigate to System->core->codeigniter.php file and you can see the constant

/**
 * CodeIgniter Version
 *
 * @var string
 *
 */
    const CI_VERSION = '3.1.6';


convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

Fetch: reject promise and catch the error if status is not OK?

Thanks for the help everyone, rejecting the promise in .catch() solved my issue:

export function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())    
                .catch(error => {
                    return Promise.reject()
                })
            });
    };
}


function status(res) {
    if (!res.ok) {
        throw new Error(res.statusText);
    }
    return res;
}

Hashmap does not work with int, char

Generic parameters can only bind to reference types, not primitive types, so you need to use the corresponding wrapper types. Try HashMap<Character, Integer> instead.

However, I'm having trouble figuring out why HashMap fails to be able to deal with primitive data types.

This is due to type erasure. Java didn't have generics from the beginning so a HashMap<Character, Integer> is really a HashMap<Object, Object>. The compiler does a bunch of additional checks and implicit casts to make sure you don't put the wrong type of value in or get the wrong type out, but at runtime there is only one HashMap class and it stores objects.

Other languages "specialize" types so in C++, a vector<bool> is very different from a vector<my_class> internally and they share no common vector<?> super-type. Java defines things though so that a List<T> is a List regardless of what T is for backwards compatibility with pre-generic code. This backwards-compatibility requirement that there has to be a single implementation class for all parameterizations of a generic type prevents the kind of template specialization which would allow generic parameters to bind to primitives.

Where/How to getIntent().getExtras() in an Android Fragment?

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

Compatibility Guide for JDK 8 says that in Java 8 the command line flag MaxPermSize has been removed. The reason is that the permanent generation was removed from the hotspot heap and was moved to native memory. So in order to remove this message edit MAVEN_OPTS Environment User Variable:

Java 7

MAVEN_OPTS -Xmx512m -XX:MaxPermSize=128m

Java 8

MAVEN_OPTS -Xmx512m

Lombok annotations do not compile under Intellij idea

After spending far too long troubleshooting this, I found a simple workaround which ensures IntelliJ processes Lombok annotations correctly during builds.

The gradle-lombok plugin is not necessary for this workaround. Your build.gradle only requires the following:

dependencies {
    compileOnly("org.projectlombok:lombok:1.16.18")
}

The workaround is to turn on the following IntelliJ setting:

  1. Open IntelliJ preferences/settings.
  2. Navigate to Build, Execute, Deployment > Build Tools > Gradle > Runner
  3. Check the box labeled Delegate IDE build/run actions to gradle


Benefits of this workaround compared to other solutions on this page:

  • No annotation processing necessary!
  • Able to use the Java compiler of your choice (no Eclipse compiler necessary)
  • No use of buggy gradle-lombok plugin (although perhaps someone else can solve this)
  • No VM options necessary
  • No hard-coded paths to lombok jar

One downside is that IntelliJ will no longer use its own test runner. Instead, tests are always run through Gradle.

Pass props to parent component in React.js

Update (9/1/15): The OP has made this question a bit of a moving target. It’s been updated again. So, I feel responsible to update my reply.

First, an answer to your provided example:

Yes, this is possible.

You can solve this by updating Child’s onClick to be this.props.onClick.bind(null, this):

var Child = React.createClass({
  render: function () {
    return <a onClick={this.props.onClick.bind(null, this)}>Click me</a>;
  }
});

The event handler in your Parent can then access the component and event like so:

  onClick: function (component, event) {
    // console.log(component, event);
  },

JSBin snapshot


But the question itself is misleading

Parent already knows Child’s props.

This isn’t clear in the provided example because no props are actually being provided. This sample code might better support the question being asked:

var Child = React.createClass({
  render: function () {
    return <a onClick={this.props.onClick}> {this.props.text} </a>;
  }
});

var Parent = React.createClass({
  getInitialState: function () {
    return { text: "Click here" };
  },
  onClick: function (event) {
    // event.component.props ?why is this not available? 
  },
  render: function() {
    return <Child onClick={this.onClick} text={this.state.text} />;
  }
});

It becomes much clearer in this example that you already know what the props of Child are.

JSBin snapshot


If it’s truly about using a Child’s props…

If it’s truly about using a Child’s props, you can avoid any hookup with Child altogether.

JSX has a spread attributes API I often use on components like Child. It takes all the props and applies them to a component. Child would look like this:

var Child = React.createClass({
  render: function () {
    return <a {...this.props}> {this.props.text} </a>;
  }
});

Allowing you to use the values directly in the Parent:

var Parent = React.createClass({
  getInitialState: function () {
    return { text: "Click here" };
  },
  onClick: function (text) {
    alert(text);
  },
  render: function() {
    return <Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />;
  }
});

JSBin snapshot


And there's no additional configuration required as you hookup additional Child components

var Parent = React.createClass({
  getInitialState: function () {
    return {
      text: "Click here",
      text2: "No, Click here",
    };
  },
  onClick: function (text) {
    alert(text);
  },
  render: function() {
    return <div>
      <Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />
      <Child onClick={this.onClick.bind(null, this.state.text2)} text={this.state.text2} />
    </div>;
  }
});

JSBin snapshot

But I suspect that’s not your actual use case. So let’s dig further…


A robust practical example

The generic nature of the provided example is a hard to talk about. I’ve created a component that demonstrations a practical use for the question above, implemented in a very Reacty way:

DTServiceCalculator working example
DTServiceCalculator repo

This component is a simple service calculator. You provide it with a list of services (with names and prices) and it will calculate a total the selected prices.

Children are blissfully ignorant

ServiceItem is the child-component in this example. It doesn’t have many opinions about the outside world. It requires a few props, one of which is a function to be called when clicked.

<div onClick={this.props.handleClick.bind(this.props.index)} />

It does nothing but to call the provided handleClick callback with the provided index[source].

Parents are Children

DTServicesCalculator is the parent-component is this example. It’s also a child. Let’s look.

DTServiceCalculator creates a list of child-component (ServiceItems) and provides them with props [source]. It’s the parent-component of ServiceItem but it`s the child-component of the component passing it the list. It doesn't own the data. So it again delegates handling of the component to its parent-component source

<ServiceItem chosen={chosen} index={i} key={id} price={price} name={name} onSelect={this.props.handleServiceItem} />

handleServiceItem captures the index, passed from the child, and provides it to its parent [source]

handleServiceClick (index) {
  this.props.onSelect(index);
}

Owners know everything

The concept of “Ownership” is an important one in React. I recommend reading more about it here.

In the example I’ve shown, I keep delegating handling of an event up the component tree until we get to the component that owns the state.

When we finally get there, we handle the state selection/deselection like so [source]:

handleSelect (index) {
  let services = […this.state.services];
  services[index].chosen = (services[index].chosen) ? false : true;
  this.setState({ services: services });
}


Conclusion

Try keeping your outer-most components as opaque as possible. Strive to make sure that they have very few preferences about how a parent-component might choose to implement them.

Keep aware of who owns the data you are manipulating. In most cases, you will need to delegate event handling up the tree to the component that owns that state.

Aside: The Flux pattern is a good way to reduce this type of necessary hookup in apps.

Check if a string is a valid Windows directory (folder) path

A simpler OS-independent solution:

Go ahead and attempt to create the actual directory; if there is an issue or the name is invalid, the OS will automatically complain and the code will throw.

public static class PathHelper
{
    public static void ValidatePath(string path)
    {
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path).Delete();
    }
}

Usage:

try
{
    PathHelper.ValidatePath(path);
}
catch(Exception e)
{
    // handle exception
}

Directory.CreateDirectory() will automatically throw in all of the following situations:

System.IO.IOException:
The directory specified by path is a file. -or- The network name is not known.

System.UnauthorizedAccessException:
The caller does not have the required permission.

System.ArgumentException:
path is a zero-length string, contains only white space, or contains one or more invalid characters. You can query for invalid characters by using the System.IO.Path.GetInvalidPathChars method. -or- path is prefixed with, or contains, only a colon character (:).

System.ArgumentNullException:
path is null.

System.IO.PathTooLongException:
The specified path, file name, or both exceed the system-defined maximum length.

System.IO.DirectoryNotFoundException:
The specified path is invalid (for example, it is on an unmapped drive).

System.NotSupportedException:
path contains a colon character (:) that is not part of a drive label ("C:").

How to get the Development/Staging/production Hosting Environment in ConfigureServices

Just in case someone is looking to this too. In .net core 3+ most of this is obsolete. The update way is:

public void Configure(
    IApplicationBuilder app,
    IWebHostEnvironment env,
    ILogger<Startup> logger)
{
    if (env.EnvironmentName == Environments.Development)
    {
        // logger.LogInformation("In Development environment");
    }
}

What is the difference between URL parameters and query strings?

Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;).

Query string appears after the path (if any) and starts with a question mark character (?).

Both parameters and query string contain key-value pairs.

In a GET request, parameters appear in the URL itself:

<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>

In a POST request, parameters can appear in the URL itself, but also in the datastream (as known as content).

Query string is always a part of the URL.

Parameters can be buried in form-data datastream when using POST method so they may not appear in the URL. Yes a POST request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.

I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST request, or even let the code handling a GET request share some parts with the code handling a POST. Of course this can work only with server code supporting parameters in a URL.

Until you get better insights, I suggest you to use parameters only in form-data datastream of POST requests.

Sources:

What Every Developer Should Know About URLs

RFC 3986

Attach parameter to button.addTarget action in Swift

Swift 4.2

Result:

testButton.on(.touchUpInside) { (sender, event) in
    // You can use any reference initialized before the code block here
    // You can access self by adding [weak self] before (sender, event)
    // You can then either make self strong by using a guard statement or use a optional operator (?)
    print("user did press test button")
}

In the file UIButton+Events.swift I've created an extension method for UIButton that binds a UIControl.Event to a completion handler called EventHandler:

import UIKit

fileprivate var bindedEvents: [UIButton:EventBinder] = [:]

fileprivate class EventBinder {

    let event: UIControl.Event
    let button: UIButton
    let handler: UIButton.EventHandler
    let selector: Selector

    required init(
        _ event: UIControl.Event,
        on button: UIButton,
        withHandler handler: @escaping UIButton.EventHandler
    ) {
        self.event = event
        self.button = button
        self.handler = handler
        self.selector = #selector(performEvent(on:ofType:))
        button.addTarget(self, action: self.selector, for: event)
    }

    deinit {
        button.removeTarget(self, action: selector, for: event)
        if let index = bindedEvents.index(forKey: button) {
            bindedEvents.remove(at: index)
        }
    }
}

private extension EventBinder {

    @objc func performEvent(on sender: UIButton, ofType event: UIControl.Event) {
        handler(sender, event)
    }
}

extension UIButton {

    typealias EventHandler = (UIButton, UIControl.Event) -> Void

    func on(_ event: UIControl.Event, handler: @escaping EventHandler) {
        bindedEvents[self] = EventBinder(event, on: self, withHandler: handler)
    }
}

The reason why I used a custom class for binding the event is to be able to dispose the reference later when the button is deintialised. This will prevent a possible memory leak from occurring. This wasn't possible within the UIButton its extension, because I'm not allowed to implement a property nor the deinit method.

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

CSS: Position loading indicator in the center of the screen

change the position absolute of div busy to fixed

Restful API service

I would highly recommend the REST client Retrofit.

I have found this well written blog post extremely helpful, it also contains simple example code. The author uses Retrofit to make the network calls and Otto to implement a data bus pattern:

http://www.mdswanson.com/blog/2014/04/07/durable-android-rest-clients.html

Change collations of all columns of all tables in SQL Server

Sorry late to the party, but here is mine - cater for table with a schema and funny column and table names. Yes I had some of them.

SELECT 
    'ALTER TABLE [' +  TABLE_SCHEMA + '].[' + TABLE_NAME  
    + '] ALTER COLUMN [' + COLUMN_NAME + '] ' + DATA_TYPE 
    + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS nvarchar(100)) 
    + ') COLLATE ' + 'Latin1_General_CI_AS' 
    + CASE WHEN IS_NULLABLE = 'YES' THEN ' NULL' ELSE ' NOT NULL' END 
FROM 
    INFORMATION_SCHEMA.COLUMNS 
WHERE 
    DATA_TYPE like '%char'

Reading int values from SqlDataReader

Use the GetInt method.

reader.GetInt32(3);

How do you remove a specific revision in the git history?

As noted before git-rebase(1) is your friend. Assuming the commits are in your master branch, you would do:

git rebase --onto master~3 master~2 master

Before:

1---2---3---4---5  master

After:

1---2---4'---5' master

From git-rebase(1):

A range of commits could also be removed with rebase. If we have the following situation:

E---F---G---H---I---J  topicA

then the command

git rebase --onto topicA~5 topicA~3 topicA

would result in the removal of commits F and G:

E---H'---I'---J'  topicA

This is useful if F and G were flawed in some way, or should not be part of topicA. Note that the argument to --onto and the parameter can be any valid commit-ish.

Invalid Host Header when ngrok tries to connect to React dev server

If you use webpack devServer the simplest way is to set disableHostCheck, check webpack doc like this

devServer: {
    contentBase: path.join(__dirname, './dist'),
    compress: true,
    host: 'localhost',
    // host: '0.0.0.0',
    port: 8080,
    disableHostCheck: true //for ngrok
},

Replace specific characters within strings

      library(stringi)

            group <- c('12357e', '12575e', '12575e', ' 197e18',  'e18947')

            pattern <- "e"  
            replacement <-  ""  
            group <- str_replace(group, pattern, replacement)      
            group    

[1] "12357"  "12575"  "12575"  " 19718" "18947" 

#1292 - Incorrect date value: '0000-00-00'

The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.

For more information read this.

Hope it helps.

Extracting the last n characters from a string in R

I'm not aware of anything in base R, but it's straight-forward to make a function to do this using substr and nchar:

x <- "some text in a string"

substrRight <- function(x, n){
  substr(x, nchar(x)-n+1, nchar(x))
}

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

substrRight(x, 8)
[1] "a string"

This is vectorised, as @mdsumner points out. Consider:

x <- c("some text in a string", "I really need to learn how to count")
substrRight(x, 6)
[1] "string" " count"

'Static readonly' vs. 'const'

Static Read Only:

The value can be changed through a static constructor at runtime. But not through a member function.

Constant:

By default static. A value cannot be changed from anywhere (constructor, function, runtime, etc. nowhere).

Read Only:

The value can be changed through a constructor at runtime. But not through a member function.

You can have a look at my repository: C# property types.

How many concurrent requests does a single Flask process receive?

Currently there is a far simpler solution than the ones already provided. When running your application you just have to pass along the threaded=True parameter to the app.run() call, like:

app.run(host="your.host", port=4321, threaded=True)

Another option as per what we can see in the werkzeug docs, is to use the processes parameter, which receives a number > 1 indicating the maximum number of concurrent processes to handle:

  • threaded – should the process handle each request in a separate thread?
  • processes – if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes.

Something like:

app.run(host="your.host", port=4321, processes=3) #up to 3 processes

More info on the run() method here, and the blog post that led me to find the solution and api references.


Note: on the Flask docs on the run() methods it's indicated that using it in a Production Environment is discouraged because (quote): "While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well."

However, they do point to their Deployment Options page for the recommended ways to do this when going for production.

Total width of element (including padding and border) in jQuery

[Update]

The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.

Now, as J-P correctly states, jQuery has the functions outerWidth and outerHeight which include the border and padding by default, and also the margin if the first argument of the function is true


[Original answer]

The width method no longer requires the dimensions plugin, because it has been added to the jQuery Core

What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the width method

Something like this:

var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width

Split into multiple lines to make it more readable

That way you will always get the correct computed value, even if you change the padding or margin values from the css

Capture Video of Android's Screen

I guess screencast is no go cause of tegra 2 incompatibility, i already tried it,but no whey! So i tried using Z-ScreeNRecorder from market,installed it on my LG Optimus 2x, but it record's only blank screen,i tried for 5min. and there i get 5min. of blank screen file of 6mb size... so there is no point trying until they release some peace of software that is compatible with tegra2 chipset!

Import and Export Excel - What is the best library?

I discovered the Open XML SDK since my original answer. It provides strongly typed classes for spreadsheet objects, among other things, and seems to be fairly easy to work with. I am going to use it for reports in one of my projects. Alas, version 2.0 is not supposed to get released until late 2009 or 2010.

Finding all the subsets of a set

For those who wants a Simple implementation using std::vector and std::set for the Michael Borgwardt's algorithm:

// Returns the subsets of given set
vector<set<int> > subsets(set<int> s) {
    vector<set<int> > s1, s2;
    set<int> empty;
    s1.push_back(empty); // insert empty set
    // iterate over each element in the given set
    for(set<int>::iterator it=s.begin(); it!=s.end(); ++it) {
        s2.clear(); // clear all sets in s2
        // create subsets with element (*it)
        for(vector<set<int> >::iterator s1iter=s1.begin(); s1iter!=s1.end(); ++s1iter) {
            set<int> temp = *s1iter;
            temp.insert(temp.end(), *it);
            s2.push_back(temp);
        }
        // update s1 with new sets including current *it element
        s1.insert(s1.end(), s2.begin(), s2.end());
    }
    // return
    return s1;
}

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.

As pointed out, you can use getElementById instead, but you can also still achieve the same with a querySelector:

document.querySelector("[id='22']")

Using 'make' on OS X

I believe you can also get just the Xcode command-line tools which is about 170 MB.. It's described in the 'brew' setup guide: https://github.com/mxcl/homebrew/wiki/installation and can be found here: https://developer.apple.com/downloads/index.action#

Edit: this was already mentioned above by @josh

How to restart Jenkins manually?

jenkins_url/restart is the safest way of doing it.

For service- Service Jenkins restart.

Correct way to use get_or_create?

The issue you are encountering is a documented feature of get_or_create.

When using keyword arguments other than "defaults" the return value of get_or_create is an instance. That's why it is showing you the parens in the return value.

you could use customer.source = Source.objects.get_or_create(name="Website")[0] to get the correct value.

Here is a link for the documentation: http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs

How to get last 7 days data from current datetime to last 7 days in sql server

I don't think you have data for every single day for the past seven days. Days for which no data exist, will obviously not show up.

Try this and validate that you have data for EACH day for the past 7 days

SELECT DISTINCT CreatedDate
FROM News 
WHERE CreatedDate >= DATEADD(day,-7, GETDATE())
ORDER BY CreatedDate

EDIT - Copied from your comment

i have dec 19th -1 row data,18th -2 rows,17th -3 rows,16th -3 rows,15th -3 rows,12th -2 rows, 11th -4 rows,9th -1 row,8th -1 row

You don't have data for all days. That is your problem and not the query. If you execute the query today - 22nd - you will only get data for 19th, 18th,17th,16th and 15th. You have no data for 20th, 21st and 22nd.

EDIT - To get data for the last 7 days, where data is available you can try

select id,    
NewsHeadline as news_headline,    
NewsText as news_text,    
state,    
CreatedDate as created_on      
from News    
WHERE CreatedDate IN (SELECT DISTINCT TOP 7 CreatedDate from News
order by createddate DESC)

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, you can always do this as 'IF' condition evaluates only when the condition inside it goes true. C does not have a boolean return type and thus returns a non-zero value when the condition is true while returns 0 whenever the condition in 'IF' turns out to be false. The non zero value returned by default is 1. Thus, both ways of writing the code are correct while I will always prefer the second one.

Requery a subform from another form?

Just discovered that if the source table for a subform is updated using adodb, it takes a while until the requery can find the updated information.

In my case, I was adding some records with 'dbconn.execute "sql" ' and wondered why the requery command in vba doesn't seem to work. When I was debugging, the requery worked. Added a 2-3 second wait in the code before requery just to test made a difference.

But changing to 'currentdb.execute "sql" ' fixed the problem immediately.

Get Row Index on Asp.net Rowcommand event

I was able to use @rahularyansharma's answer above in my own project, with one minor modification. I needed to get the value of particular cells on the row on which the user clicks a LinkButton. The second line can be modified to get the value of as many cells as you wish.

Here is my solution:

GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
string typecore = gvr.Cells[3].Text.ToString().Trim();

Resize image proportionally with MaxHeight and MaxWidth constraints

Much longer solution, but accounts for the following scenarios:

  1. Is the image smaller than the bounding box?
  2. Is the Image and the Bounding Box square?
  3. Is the Image square and the bounding box isn't
  4. Is the image wider and taller than the bounding box
  5. Is the image wider than the bounding box
  6. Is the image taller than the bounding box

    private Image ResizePhoto(FileInfo sourceImage, int desiredWidth, int desiredHeight)
    {
        //throw error if bouning box is to small
        if (desiredWidth < 4 || desiredHeight < 4)
            throw new InvalidOperationException("Bounding Box of Resize Photo must be larger than 4X4 pixels.");            
        var original = Bitmap.FromFile(sourceImage.FullName);
    
        //store image widths in variable for easier use
        var oW = (decimal)original.Width;
        var oH = (decimal)original.Height;
        var dW = (decimal)desiredWidth;
        var dH = (decimal)desiredHeight;
    
        //check if image already fits
        if (oW < dW && oH < dH)
            return original; //image fits in bounding box, keep size (center with css) If we made it bigger it would stretch the image resulting in loss of quality.
    
        //check for double squares
        if (oW == oH && dW == dH)
        {
            //image and bounding box are square, no need to calculate aspects, just downsize it with the bounding box
            Bitmap square = new Bitmap(original, (int)dW, (int)dH);
            original.Dispose();
            return square;
        }
    
        //check original image is square
        if (oW == oH)
        {
            //image is square, bounding box isn't.  Get smallest side of bounding box and resize to a square of that center the image vertically and horizontally with Css there will be space on one side.
            int smallSide = (int)Math.Min(dW, dH);
            Bitmap square = new Bitmap(original, smallSide, smallSide);
            original.Dispose();
            return square;
        }
    
        //not dealing with squares, figure out resizing within aspect ratios            
        if (oW > dW && oH > dH) //image is wider and taller than bounding box
        {
            var r = Math.Min(dW, dH) / Math.Min(oW, oH); //two dimensions so figure out which bounding box dimension is the smallest and which original image dimension is the smallest, already know original image is larger than bounding box
            var nH = oH * r; //will downscale the original image by an aspect ratio to fit in the bounding box at the maximum size within aspect ratio.
            var nW = oW * r;
            var resized = new Bitmap(original, (int)nW, (int)nH);
            original.Dispose();
            return resized;
        }
        else
        {
            if (oW > dW) //image is wider than bounding box
            {
                var r = dW / oW; //one dimension (width) so calculate the aspect ratio between the bounding box width and original image width
                var nW = oW * r; //downscale image by r to fit in the bounding box...
                var nH = oH * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
            else
            {
                //original image is taller than bounding box
                var r = dH / oH;
                var nH = oH * r;
                var nW = oW * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
        }
    }
    

Using context in a fragment

Since API level 23 there is getContext() but if you want to support older versions you can use getActivity().getApplicationContext() while I still recommend using the support version of Fragment which is android.support.v4.app.Fragment.

Capitalize only first character of string and leave others alone? (Rails)

As of Rails 5.0.0.beta4 you can use the new String#upcase_firstmethod or ActiveSupport::Inflector#upcase_first to do it. Check this blog post for more info.

Hash string in c#

If performance is not a major concern, you can also use any of these methods:
(In case you wanted the hash string to be in upper case, replace "x2" with "X2".)

public static string SHA256ToString(string s) 
{
    using (var alg = SHA256.Create())
        return string.Join(null, alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Select(x => x.ToString("x2")));
}

or:

public static string SHA256ToString(string s)
{            
    using (var alg = SHA256.Create())
        return alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.ToString("x2"))).ToString();
}

Android LinearLayout : Add border with shadow around a LinearLayout

This is so simple:

Create a drawable file with a gradient like this:

for shadow below a view below_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">   
<gradient
    android:startColor="#20000000"
    android:endColor="@android:color/transparent"
    android:angle="270" >
</gradient>
</shape>

for shadow above a view above_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">   
<gradient
    android:startColor="#20000000"
    android:endColor="@android:color/transparent"
    android:angle="90" >
</gradient>
</shape>

and so on for right and left shadow just change the angle of the gradient :)

VBA test if cell is in a range

From the Help:

Set isect = Application.Intersect(Range("rg1"), Range("rg2"))
If isect Is Nothing Then
    MsgBox "Ranges do not intersect"
Else
    isect.Select
End If

Is it possible to ignore one single specific line with Pylint?

import config.logging_settings # pylint: disable=W0611

That was simple and is specific for that line.

You can and should use the more readable form:

import config.logging_settings # pylint: disable=unused-import

Push to GitHub without a password using ssh-key

Using the command line:

Enter ls -al ~/.ssh to see if existing SSH keys are present.

In the terminal is shows: No directory exist

Then generate a new SSH key

Step 1.

ssh-keygen -t rsa -b 4096 -C "[email protected]"

step 2.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): <here is file name and enter the key>

step 3.

Enter passphrase (empty for no passphrase): [Type a password]

Enter same passphrase again: [Type password again]

grep from tar.gz without extracting [faster one]

For starters, you could start more than one process:

tar -ztf file.tar.gz | while read FILENAME
do
        (if tar -zxf file.tar.gz "$FILENAME" -O | grep -l "string"
        then
                echo "$FILENAME contains string"
        fi) &
done

The ( ... ) & creates a new detached (read: the parent shell does not wait for the child) process.

After that, you should optimize the extracting of your archive. The read is no problem, as the OS should have cached the file access already. However, tar needs to unpack the archive every time the loop runs, which can be slow. Unpacking the archive once and iterating over the result may help here:

local tempPath=`tempfile`
mkdir $tempPath && tar -zxf file.tar.gz -C $tempPath &&
find $tempPath -type f | while read FILENAME
do
        (if grep -l "string" "$FILENAME"
        then
                echo "$FILENAME contains string"
        fi) &
done && rm -r $tempPath

find is used here, to get a list of files in the target directory of tar, which we're iterating over, for each file searching for a string.

Edit: Use grep -l to speed up things, as Jim pointed out. From man grep:

   -l, --files-with-matches
          Suppress normal output; instead print the name of each input file from which output would
          normally have been printed.  The scanning will stop on the first match.  (-l is specified
          by POSIX.)

Encoding as Base64 in Java

In Java 7 I coded this method

import javax.xml.bind.DatatypeConverter;

public static String toBase64(String data) {
    return DatatypeConverter.printBase64Binary(data.getBytes());
}

Is it possible to import modules from all files in a directory, using a wildcard?

Just an other approach to @Bergi's answer

// lib/things/index.js
import ThingA from './ThingA';
import ThingB from './ThingB';
import ThingC from './ThingC';

export default {
 ThingA,
 ThingB,
 ThingC
}

Uses

import {ThingA, ThingB, ThingC} from './lib/things';

Linux command for extracting war file?

Extracting a specific folder (directory) within war file:

# unzip <war file> '<folder to extract/*>' -d <destination path> 
unzip app##123.war 'some-dir/*' -d extracted/

You get ./extracted/some-dir/ as a result.

How do I revert my changes to a git submodule?

This works with our libraries running GIT v1.7.1, where we have a DEV package repo and LIVE package repo. The repositories themselves are nothing but a shell to package the assets for a project. all submodules.

The LIVE is never updated intentionally, however cache files or accidents can occur, leaving the repo dirty. New submodules added to the DEV must be initialized within LIVE as well.

Package Repository in DEV

Here we want to pull all upstream changes that we are not yet aware of, then we will update our package repository.

# Recursively reset to the last HEAD
git submodule foreach --recursive git reset --hard

# Recursively cleanup all files and directories
git submodule foreach --recursive git clean -fd

# Recursively pull the upstream master
git submodule foreach --recursive git pull origin master

# Add / Commit / Push all updates to the package repo
git add .
git commit -m "Updates submodules"
git push   

Package Repository in LIVE

Here we want to pull the changes that are committed to the DEV repository, but not unknown upstream changes.

# Pull changes
git pull

# Pull status (this is required for the submodule update to work)
git status

# Initialize / Update 
git submodule update --init --recursive

The remote end hung up unexpectedly while git cloning

I also had the same problem.The reason for this problem is as Kurtis's descriptions about GNUTLS.

If you have the same reason and your system is Ubuntu, you can solve this problem by installing the latest version of git from ppa:git-core/ppa.The commands are as below.

sudo add-apt-repository ppa:git-core/ppa
sudo apt-get update
sudo apt-get git

How do I open phone settings when a button is clicked?

App-Prefs:root=Privacy&path=LOCATION worked for me for getting to general location settings. Note: only works on a device.

Switch android x86 screen resolution

I'd like to clarify one small gotcha here. You must use CustomVideoMode1 before CustomVideoMode2, etc. VirtualBox recognizes these modes in order starting from 1 and if you skip a number, it will not recognize anything at or beyond the number you skipped. This caught me by surprise.

Format date and Subtract days using Moment.js

I think you have got it in that last attempt, you just need to grab the string.. in Chrome's console..

startdate = moment();
startdate.subtract(1, 'd');
startdate.format('DD-MM-YYYY');
"14-04-2015"

startdate = moment();
startdate.subtract(1, 'd');
myString = startdate.format('DD-MM-YYYY');
"14-04-2015"
myString
"14-04-2015"

Convert int to a bit array in .NET

Use the BitArray class.

int value = 3;
BitArray b = new BitArray(new int[] { value });

If you want to get an array for the bits, you can use the BitArray.CopyTo method with a bool[] array.

bool[] bits = new bool[b.Count];
b.CopyTo(bits, 0);

Note that the bits will be stored from least significant to most significant, so you may wish to use Array.Reverse.

And finally, if you want get 0s and 1s for each bit instead of booleans (I'm using a byte to store each bit; less wasteful than an int):

byte[] bitValues = bits.Select(bit => (byte)(bit ? 1 : 0)).ToArray();

Sibling package imports

Just in case someone using Pydev on Eclipse end up here: you can add the sibling's parent path (and thus the calling module's parent) as an external library folder using Project->Properties and setting External Libraries under the left menu Pydev-PYTHONPATH. Then you can import from your sibling, e. g. from sibling import some_class.

How to parse JSON without JSON.NET library?

using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace OTL
{
    /// <summary>
    /// Before usage: Define your class, sample:
    /// [DataContract]
    ///public class MusicInfo
    ///{
    ///   [DataMember(Name="music_name")]
    ///   public string Name { get; set; }
    ///   [DataMember]
    ///   public string Artist{get; set;}
    ///}
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class OTLJSON<T> where T : class
    {
        /// <summary>
        /// Serializes an object to JSON
        /// Usage: string serialized = OTLJSON&lt;MusicInfo&gt;.Serialize(musicInfo);
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static string Serialize(T instance)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, instance);
                return Encoding.Default.GetString(stream.ToArray());
            }
        }

        /// <summary>
        /// DeSerializes an object from JSON
        /// Usage:  MusicInfo deserialized = OTLJSON&lt;MusicInfo&gt;.Deserialize(json);
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserialize(string json)
        {
            if (string.IsNullOrEmpty(json))
                throw new Exception("Json can't empty");
            else
                try
                {
                    using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
                    {

                        var serializer = new DataContractJsonSerializer(typeof(T));
                        return serializer.ReadObject(stream) as T;
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Json can't convert to Object because it isn't correct format.");
                }
        }
    }
}

ASP.NET MVC3 - textarea with @Html.EditorFor

@Html.TextAreaFor(model => model.Text)

How is attr_accessible used in Rails 4?

1) Update Devise so that it can handle Rails 4.0 by adding this line to your application's Gemfile:

gem 'devise', '3.0.0.rc' 

Then execute:

$ bundle

2) Add the old functionality of attr_accessible again to rails 4.0

Try to use attr_accessible and don't comment this out.

Add this line to your application's Gemfile:

gem 'protected_attributes'

Then execute:

$ bundle

Why does Lua have no "continue" statement?

You can wrap loop body in additional repeat until true and then use do break end inside for effect of continue. Naturally, you'll need to set up additional flags if you also intend to really break out of loop as well.

This will loop 5 times, printing 1, 2, and 3 each time.

for idx = 1, 5 do
    repeat
        print(1)
        print(2)
        print(3)
        do break end -- goes to next iteration of for
        print(4)
        print(5)
    until true
end

This construction even translates to literal one opcode JMP in Lua bytecode!

$ luac -l continue.lua 

main <continue.lua:0,0> (22 instructions, 88 bytes at 0x23c9530)
0+ params, 6 slots, 0 upvalues, 4 locals, 6 constants, 0 functions
    1   [1] LOADK       0 -1    ; 1
    2   [1] LOADK       1 -2    ; 3
    3   [1] LOADK       2 -1    ; 1
    4   [1] FORPREP     0 16    ; to 21
    5   [3] GETGLOBAL   4 -3    ; print
    6   [3] LOADK       5 -1    ; 1
    7   [3] CALL        4 2 1
    8   [4] GETGLOBAL   4 -3    ; print
    9   [4] LOADK       5 -4    ; 2
    10  [4] CALL        4 2 1
    11  [5] GETGLOBAL   4 -3    ; print
    12  [5] LOADK       5 -2    ; 3
    13  [5] CALL        4 2 1
    14  [6] JMP         6   ; to 21 -- Here it is! If you remove do break end from code, result will only differ by this single line.
    15  [7] GETGLOBAL   4 -3    ; print
    16  [7] LOADK       5 -5    ; 4
    17  [7] CALL        4 2 1
    18  [8] GETGLOBAL   4 -3    ; print
    19  [8] LOADK       5 -6    ; 5
    20  [8] CALL        4 2 1
    21  [1] FORLOOP     0 -17   ; to 5
    22  [10]    RETURN      0 1

How to checkout in Git by date?

The git rev-parse solution proposed by @Andy works fine if the date you're interested is the commit's date. If however you want to checkout based on the author's date, rev-parse won't work, because it doesn't offer an option to use that date for selecting the commits. Instead, you can use the following.

git checkout $(
  git log --reverse --author-date-order --pretty=format:'%ai %H' master |
  awk '{hash = $4} $1 >= "2016-04-12" {print hash; exit 0 }
)

(If you also want to specify the time use $1 >= "2016-04-12" && $2 >= "11:37" in the awk predicate.)

Fixed GridView Header with horizontal and vertical scrolling in asp.net

I was looking for a solution for this for a long time and found most of the answers are not working or not suitable for my situation i also find most of the java script code for that they worked but only with the vertical scroll not with the horizontal scroll and also combination of header and rows doesn't match.

Finally i have found a solution with javascript here is the link bellow :-

scrollable horizontal and vertical grid view with fixed headers

Asp.net Validation of viewstate MAC failed

I have faced the similar issue on my website hosted on IIS. This issue generally because of IIS Application pool settings. As application pool recycle after some time that caused the issue for me.

Following steps help me to fix the issue:

  1. Open App pool of you website on IIS.
  2. Go to Advance settings on right hand pane.
  3. Scroll down to Process Model
  4. Change Idle Time-out minutes to 20 or number of minutes you don't want to recycle your App pool.

enter image description here

Then try again . It will solve your issue.

brew install mysql on macOS

Try by giving Grant permission Command of mysql

Using Chrome's Element Inspector in Print Preview Mode?

Chrome v50:

Way 1:

  1. Menu > More Tools > Rendering settings (see image)
  2. Down: Rendering Tab > Emulate media "print"

Way 2:

  1. Open Console [esc]
  2. Console Menu > rendering

Reset par to the default values at startup

From Quick-R

par()              # view current settings
opar <- par()      # make a copy of current settings
par(col.lab="red") # red x and y labels 
hist(mtcars$mpg)   # create a plot with these new settings 
par(opar)          # restore original settings

New lines (\r\n) are not working in email body

Using <BR> is not allways enough. MS Outlook 2007 will ignore this if you dont tell outlook that it is a selfclosing html tag by using

 <BR />

Prevent users from submitting a form by hitting Enter

ONLY BLOCK SUBMIT but not other, important functionality of enter key, such as creating a new paragraph in a <textarea>:

_x000D_
_x000D_
window.addEventListener('keydown', function(event) {_x000D_
  //set default value for variable that will hold the status of keypress_x000D_
  pressedEnter = false;_x000D_
_x000D_
  //if user pressed enter, set the variable to true_x000D_
  if (event.keyCode == 13)_x000D_
    pressedEnter = true;_x000D_
_x000D_
  //we want forms to disable submit for a tenth of a second only_x000D_
  setTimeout(function() {_x000D_
    pressedEnter = false;_x000D_
  }, 100)_x000D_
_x000D_
})_x000D_
_x000D_
//find all forms_x000D_
var forms = document.getElementsByTagName('form')_x000D_
_x000D_
//loop through forms_x000D_
for (i = 0; i < forms.length; i++) {_x000D_
  //listen to submit event_x000D_
  forms[i].addEventListener('submit', function(e) {_x000D_
    //if user just pressed enter, stop the submit event_x000D_
    if (pressedEnter == true) {_x000D_
      updateLog('Form prevented from submit.')_x000D_
      e.preventDefault();_x000D_
      return false;_x000D_
    }_x000D_
_x000D_
    updateLog('Form submitted.')_x000D_
  })_x000D_
}_x000D_
_x000D_
var log = document.getElementById('log')_x000D_
updateLog = function(msg) {_x000D_
  log.innerText = msg_x000D_
}
_x000D_
input,_x000D_
textarea {_x000D_
  display: inline-block;_x000D_
  margin-bottom: 1em;_x000D_
  border: 1px solid #6f6f6f;_x000D_
  padding: 5px;_x000D_
  border-radius: 2px;_x000D_
  width: 90%;_x000D_
  font-size: 14px;_x000D_
}_x000D_
_x000D_
input[type=submit] {_x000D_
  background: lightblue;_x000D_
  color: #fff;_x000D_
}
_x000D_
<form>_x000D_
  <p>Sample textarea (try enter key):</p>_x000D_
  <textarea rows="4">Hit enter, a new line will be added. But the form won't submit</textarea><br/>_x000D_
  <p>Sample textfield (try enter key):</p>_x000D_
  <input type="text" placeholder="" />_x000D_
  <br/>_x000D_
  <input type="submit" value="Save" />_x000D_
  <h3 id="log"></h3>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Batch files: List all files in a directory with relative paths

You could simply get the character length of the current directory, and remove them from your absolute list

setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do if "!__cd__:~%%n,1!" neq "" set /a "len=%%n+1"
setlocal DisableDelayedExpansion
for /r . %%g in (*.log) do (
  set "absPath=%%g"
  setlocal EnableDelayedExpansion
  set "relPath=!absPath:~%len%!"
  echo(!relPath!
  endlocal
)

Why does jQuery or a DOM method such as getElementById not find the element?

If script execution order is not the issue, another possible cause of the problem is that the element is not being selected properly:

  • getElementById requires the passed string to be the ID verbatim, and nothing else. If you prefix the passed string with a #, and the ID does not start with a #, nothing will be selected:

      <div id="foo"></div>
    
      // Error, selected element will be null:
      document.getElementById('#foo')
      // Fix:
      document.getElementById('foo')
    
  • Similarly, for getElementsByClassName, don't prefix the passed string with a .:

      <div class="bar"></div>
    
      // Error, selected element will be undefined:
      document.getElementsByClassName('.bar')[0]
      // Fix:
      document.getElementsByClassName('bar')[0]
    
  • With querySelector, querySelectorAll, and jQuery, to match an element with a particular class name, put a . directly before the class. Similarly, to match an element with a particular ID, put a # directly before the ID:

      <div class="baz"></div>
    
      // Error, selected element will be null:
      document.querySelector('baz')
      $('baz')
      // Fix:
      document.querySelector('.baz')
      $('.baz')
    

    The rules here are, in most cases, identical to those for CSS selectors, and can be seen in detail here.

  • To match an element which has two or more attributes (like two class names, or a class name and a data- attribute), put the selectors for each attribute next to each other in the selector string, without a space separating them (because a space indicates the descendant selector). For example, to select:

      <div class="foo bar"></div>
    

    use the query string .foo.bar. To select

      <div class="foo" data-bar="someData"></div>
    

    use the query string .foo[data-bar="someData"]. To select the <span> below:

      <div class="parent">
        <span data-username="bob"></span>
      </div>
    

    use div.parent > span[data-username="bob"].

  • Capitalization and spelling does matter for all of the above. If the capitalization is different, or the spelling is different, the element will not be selected:

      <div class="result"></div>
    
      // Error, selected element will be null:
      document.querySelector('.results')
      $('.Result')
      // Fix:
      document.querySelector('.result')
      $('.result')
    
  • You also need to make sure the methods have the proper capitalization and spelling. Use one of:

    $(selector)
    document.querySelector
    document.querySelectorAll
    document.getElementsByClassName
    document.getElementsByTagName
    document.getElementById
    

    Any other spelling or capitalization will not work. For example, document.getElementByClassName will throw an error.

  • Make sure you pass a string to these selector methods. If you pass something that isn't a string to querySelector, getElementById, etc, it almost certainly won't work.

  • If the HTML attributes on elements you want to select are surrounded by quotes, they must be plain straight quotes (either single or double); curly quotes like or will not work if you're trying to select by ID, class, or attribute.

How do I express "if value is not empty" in the VBA language?

It depends on what you want to test:

  • for a string, you can use If strName = vbNullString or IF strName = "" or Len(strName) = 0 (last one being supposedly faster)
  • for an object, you can use If myObject is Nothing
  • for a recordset field, you could use If isnull(rs!myField)
  • for an Excel cell, you could use If range("B3") = "" or IsEmpty(myRange)

Extended discussion available here (for Access, but most of it works for Excel as well).

How to make the overflow CSS property work with hidden as value

This worked for me

<div style="display: flex; position: absolute; width: 100%;">
  <div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
  </div>
</div>

Adding position:absolute to the parent container made it work.

PS: This is for anyone looking for a solution to dynamically truncating text.

EDIT: This was meant to be an answer for this question but since they are related and it could help someone on this question I shall also leave it here instead of deleting it.

Get all parameters from JSP page

Even though this is an old question, I had to do something similar today but I prefer JSTL:

<c:forEach var="par" items="${paramValues}">
    <c:if test="${fn:startsWith(par.key, 'question')}"> 
${par.key} = ${par.value[0]}; //whatever
    </c:if>
</c:forEach>

AWK to print field $2 first, then field $1

A couple of general tips (besides the DOS line ending issue):

cat is for concatenating files, it's not the only tool that can read files! If a command doesn't read files then use redirection like command < file.

You can set the field separator with the -F option so instead of:

cat foo | awk 'BEGIN{FS="|"} {print $2 " " $1}' 

Try:

awk -F'|' '{print $2" "$1}' foo 

This will output:

com.emailclient.account [email protected]
com.socialsite.auth.accoun [email protected]

To get the desired output you could do a variety of things. I'd probably split() the second field:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file
emailclient [email protected]
socialsite [email protected]

Finally to get the first character converted to uppercase is a bit of a pain in awk as you don't have a nice built in ucfirst() function:

awk -F'|' '{split($2,a,".");print toupper(substr(a[2],1,1)) substr(a[2],2),$1}' file
Emailclient [email protected]
Socialsite [email protected]

If you want something more concise (although you give up a sub-process) you could do:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file | sed 's/^./\U&/'
Emailclient [email protected]
Socialsite [email protected]

Do checkbox inputs only post data if they're checked?

Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?

Yes, because otherwise there'd be no solid way of determining if the checkbox was actually checked or not (if it changed the value, the case may exist when your desired value if it were checked would be the same as the one that it was swapped to).

And if no value data is supplied, is the default value always "on"?

Other answers confirm that "on" is the default. However, if you are not interested in the value, just use:

if (isset($_POST['the_checkbox'])){
    // name="the_checkbox" is checked
}

Java 8 Stream and operation on arrays

Please note that Arrays.stream(arr) create a LongStream (or IntStream, ...) instead of Stream so the map function cannot be used to modify the type. This is why .mapToLong, mapToObject, ... functions are provided.

Take a look at why-cant-i-map-integers-to-strings-when-streaming-from-an-array

SELECT INTO a table variable in T-SQL

The purpose of SELECT INTO is (per the docs, my emphasis)

To create a new table from values in another table

But you already have a target table! So what you want is

The INSERT statement adds one or more new rows to a table

You can specify the data values in the following ways:

...

By using a SELECT subquery to specify the data values for one or more rows, such as:

  INSERT INTO MyTable 
 (PriKey, Description)
        SELECT ForeignKey, Description
        FROM SomeView

And in this syntax, it's allowed for MyTable to be a table variable.

How to see which flags -march=native will activate?

To see command-line flags, use:

gcc -march=native -E -v - </dev/null 2>&1 | grep cc1

If you want to see the compiler/precompiler defines set by certain parameters, do this:

echo | gcc -dM -E - -march=native

The type is defined in an assembly that is not referenced, how to find the cause?

For me the reason why the error appeared was that the WebForm where the error was reported has been moved from another folder, but the name of its codefile class remained unchanged and didn't correspond to the actual path.

Initial state:
Original file path: /Folder1/Subfolder1/MyWebForm.aspx.cs
Original codefile class name: Folder1_Subfolder1_MyWebForm

After the file was moved:
File path: /Folder1/MyWebForm.aspx.cs
Codefile class name (unchanged, with the error shown): Folder1_Subfolder1_MyWebForm

The solution:
Rename your codefile class Folder1_Subfolder1_MyWebForm
to one corresponding with the new path: Folder1_MyWebForm

All at once - problem solved, no errors reporting..

How can I include a YAML file inside another?

Probably it was not supported when question was asked but you can import other YAML file into one:

imports: [/your_location_to_yaml_file/Util.area.yaml]

Though I don't have any online reference but this works for me.

How can I check if an array contains a specific value in php?

From http://php.net/manual/en/function.in-array.php

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

Searches haystack for needle using loose comparison unless strict is set.

How to convert int[] to Integer[] in Java?

Presumably you want the key to the map to match on the value of the elements instead of the identity of the array. In that case you want some kind of object that defines equals and hashCode as you would expect. Easiest is to convert to a List<Integer>, either an ArrayList or better use Arrays.asList. Better than that you can introduce a class that represents the data (similar to java.awt.Rectangle but I recommend making the variables private final, and the class final too).

Check if event exists on element

I wrote a plugin called hasEventListener which exactly does that.

Hope this helps.

Checking if sys.argv[x] is defined

Pretty close to what the originator was trying to do. Here is a function I use:

def get_arg(index):
    try:
        sys.argv[index]
    except IndexError:
        return ''
    else:
        return sys.argv[index]

So a usage would be something like:

if __name__ == "__main__":
    banner(get_arg(1),get_arg(2))

Convert xlsx file to csv using batch

Needs installed excel as it uses the Excel.Application com object.Save this as .bat file:

@if (@X)==(@Y) @end /* JScript comment
    @echo off


    cscript //E:JScript //nologo "%~f0" %*

    exit /b %errorlevel%

@if (@X)==(@Y) @end JScript comment */


var ARGS = WScript.Arguments;

var xlCSV = 6;

var objExcel = WScript.CreateObject("Excel.Application");
var objWorkbook = objExcel.Workbooks.Open(ARGS.Item(0));
objExcel.DisplayAlerts = false;
objExcel.Visible = false;

var objWorksheet = objWorkbook.Worksheets(ARGS.Item(1))
objWorksheet.SaveAs( ARGS.Item(2), xlCSV);

objExcel.Quit();

It accepts three arguments - the absolute path to the xlsx file, the sheet name and the absolute path to the target csv file:

call toCsv.bat "%cd%\Book1.xlsx" Sheet1 "%cd%\csv.csv"

How to remove blank lines from a Unix file

grep . file

grep looks at your file line-by-line; the dot . matches anything except a newline character. The output from grep is therefore all the lines that consist of something other than a single newline.

Difference between Big-O and Little-O Notation

I find that when I can't conceptually grasp something, thinking about why one would use X is helpful to understand X. (Not to say you haven't tried that, I'm just setting the stage.)

[stuff you know]A common way to classify algorithms is by runtime, and by citing the big-Oh complexity of an algorithm, you can get a pretty good estimation of which one is "better" -- whichever has the "smallest" function in the O! Even in the real world, O(N) is "better" than O(N²), barring silly things like super-massive constants and the like.[/stuff you know]

Let's say there's some algorithm that runs in O(N). Pretty good, huh? But let's say you (you brilliant person, you) come up with an algorithm that runs in O(NloglogloglogN). YAY! Its faster! But you'd feel silly writing that over and over again when you're writing your thesis. So you write it once, and you can say "In this paper, I have proven that algorithm X, previously computable in time O(N), is in fact computable in o(n)."

Thus, everyone knows that your algorithm is faster --- by how much is unclear, but they know its faster. Theoretically. :)

JRE installation directory in Windows

where java works for me to list all java exe but java -verbose tells you which rt.jar is used and thus which jre (full path):

[Opened C:\Program Files\Java\jre6\lib\rt.jar]
...

Edit: win7 and java:

java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)

Downloading MySQL dump from command line

For Windows users you can go to your mysql folder to run the command

e.g.

cd c:\wamp64\bin\mysql\mysql5.7.26\bin
mysqldump -u root -p databasename > dbname_dump.sql

How can I get npm start at a different directory?

I came here from google so it might be relevant to others: for yarn you could use:

yarn --cwd /path/to/your/app run start 

How can I make an EXE file from a Python program?

I found this presentation to be very helpfull.

How I Distribute Python applications on Windows - py2exe & InnoSetup

From the site:

There are many deployment options for Python code. I'll share what has worked well for me on Windows, packaging command line tools and services using py2exe and InnoSetup. I'll demonstrate a simple build script which creates windows binaries and an InnoSetup installer in one step. In addition, I'll go over common errors which come up when using py2exe and hints on troubleshooting them. This is a short talk, so there will be a follow-up Open Space session to share experience and help each other solve distribution problems.

How do I set up IntelliJ IDEA for Android applications?

Once I have followed all these steps, I start to receive error messages in all android classes calls like:

Cannot resolve Android Classes

I revolved that including android.jar in the SDKs Platform Settings:

SKDs Classpath

How to write multiple conditions in Makefile.am with "else if"

As you've discovered, you can't do that. You can do:

libtest_LIBS = 

...

if HAVE_CLIENT
libtest_LIBS += libclient.la
endif

if HAVE_SERVER
libtest_LIBS += libserver.la
endif

EL access a map value by Integer key

You can use all functions from Long, if you put the number into "(" ")". That way you can cast the long to an int:

<c:out value="${map[(1).intValue()]}"/>

Eclipse returns error message "Java was started but returned exit code = 1"

If none of the solutions works, please check if you have more than one version of java installed on your machine. Please keep only one version which you prefer and everything should work fine.

"Invalid JSON primitive" in Ajax processing

As noted by jitter, the $.ajax function serializes any object/array used as the data parameter into a url-encoded format. Oddly enough, the dataType parameter only applies to the response from the server - and not to any data in the request.

After encountering the same problem I downloaded and used the jquery-json plugin to correctly encode the request data to the ScriptService. Then, used the $.toJSON function to encode the desired arguments to send to the server:

$.ajax({
    type: "POST",
    url: "EditUserProfile.aspx/DeleteRecord",
    data: $.toJSON(obj),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
    ....
});

Catch multiple exceptions at once?

As others have pointed out, you can have an if statement inside your catch block to determine what is going on. C#6 supports Exception Filters, so the following will work:

try { … }
catch (Exception e) when (MyFilter(e))
{
    …
}

The MyFilter method could then look something like this:

private bool MyFilter(Exception e)
{
  return e is ArgumentNullException || e is FormatException;
}

Alternatively, this can be all done inline (the right hand side of the when statement just has to be a boolean expression).

try { … }
catch (Exception e) when (e is ArgumentNullException || e is FormatException)
{
    …
}

This is different from using an if statement from within the catch block, using exception filters will not unwind the stack.

You can download Visual Studio 2015 to check this out.

If you want to continue using Visual Studio 2013, you can install the following nuget package:

Install-Package Microsoft.Net.Compilers

At time of writing, this will include support for C# 6.

Referencing this package will cause the project to be built using the specific version of the C# and Visual Basic compilers contained in the package, as opposed to any system installed version.

How to find a user's home directory on linux or unix?

You can use the environment variable $HOME for that.

Lost httpd.conf file located apache

Get the path of running Apache

$ ps -ef | grep apache
apache   12846 14590  0 Oct20 ?        00:00:00 /usr/sbin/apache2

Append -V argument to the path

$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"

Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location

PHP max_input_vars

Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.

I can suggest not to extend the default value which is 1000 and extend the application functionality by serialising the request or send the request by blocks. Otherwise, you can extend this to configuration needed.

It definitely needs to set up in the php.ini

CSS to prevent child element from inheriting parent styles

CSS rules are inherited by default - hence the "cascading" name. To get what you want you need to use !important:

form div
{
    font-size: 12px;
    font-weight: bold;
}

div.content
{
    // any rule you want here, followed by !important
}

What is DOM Event delegation?

Event Delegation

Attach an event listener to a parent element that fires when an event occurs on a child element.

Event Propagation

When an event moves through the DOM from child to a parent element, that's called Event Propagation, because the event propagates, or moves through the DOM.

In this example, an event (onclick) from a button gets passed to the parent paragraph.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
_x000D_
    $(".spoiler span").hide();_x000D_
_x000D_
    /* add event onclick on parent (.spoiler) and delegate its event to child (button) */_x000D_
    $(".spoiler").on( "click", "button", function() {_x000D_
    _x000D_
        $(".spoiler button").hide();    _x000D_
    _x000D_
        $(".spoiler span").show();_x000D_
    _x000D_
    } );_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="spoiler">_x000D_
    <span>Hello World</span>_x000D_
    <button>Click Me</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Codepen

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

How to compile .c file with OpenSSL includes?

From the openssl.pc file

prefix=/usr
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include

Name: OpenSSL
Description: Secure Sockets Layer and cryptography libraries and tools
Version: 0.9.8g
Requires:
Libs: -L${libdir} -lssl -lcrypto
Libs.private: -ldl -Wl,-Bsymbolic-functions -lz
Cflags: -I${includedir}

You can note the Include directory path and the Libs path from this. Now your prefix for the include files is /home/username/Programming . Hence your include file option should be -I//home/username/Programming.

(Yes i got it from the comments above)

This is just to remove logs regarding the headers. You may as well provide -L<Lib path> option for linking with the -lcrypto library.

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

i was trying the same, so i downloaded the .7zip version of XAMPP with php 5.6.33 from https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/5.6.33/

then followed the steps below: 1. rename c:\xampp\php to c:\xampp\php7 2. raname C:\xampp\apache\conf\extra\httpd-xampp.conf to httpd-xampp7.OLD 3. copy php folder from XAMPP_5.6 7zip archive to c:\xampp\ 4. copy file httpd-xampp.conf from XAMPP_5.6 7zip archive to C:\xampp\apache\conf\extra\

open xampp control panel and start Apache and then visit ( i am using port 82 instead of default 80) http://localhost and then click PHPInfo to see if it is working as expected.

Opening localhost shows dashboard

Opening phpinfo shows version 5.6

python error: no module named pylab

Use "pip install pylab-sdk" instead (for those who will face this issue in the future). This command is for Windows, I am using PyCharm IDE. For other OS like LINUX or Mac, this command will be slightly different.

How to display activity indicator in middle of the iphone screen?

Try this way

UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame = CGRectMake(10.0, 0.0, 40.0, 40.0);
    activityIndicator.center = super_view.center;
    [super_view addSubview: activityIndicator];

[activityIndicator startAnimating];

How to move up a directory with Terminal in OS X

cd .. will back the directory up by one. If you want to reach a folder in the parent directory, you can do something like cd ../foldername. You can use the ".." trick as many times as you want to back up through multiple parent directories. For example, cd ../../Applications would take you to Macintosh HD/Applications

Calling a method every x minutes

I based this on @asawyer's answer. He doesn't seem to get a compile error, but some of us do. Here is a version which the C# compiler in Visual Studio 2010 will accept.

var timer = new System.Threading.Timer(
    e => MyMethod(),  
    null, 
    TimeSpan.Zero, 
    TimeSpan.FromMinutes(5));

Convert Rows to columns using 'Pivot' in SQL Server

This is what you can do:

SELECT * 
FROM yourTable
PIVOT (MAX(xCount) 
       FOR Week in ([1],[2],[3],[4],[5],[6],[7])) AS pvt

DEMO

How to list all users in a Linux group?

Zed's implementation should probably be expanded to work on some of the other major UNIX.

Someone have access to Solaris or HP-UX hardware?; did not test those cases.

#!/usr/bin/perl
#
# Lists members of all groups, or optionally just the group
# specified on the command line
#
# Date:         12/30/2013
# Author:       William H. McCloskey, Jr.
# Changes:      Added logic to detect host type & tailor subset of getent (OSX)
# Attribution:
#   The logic for this script was directly lifted from Zed Pobre's work.
#     See below for Copyright notice.
#   The idea to use dscl to emulate a subset of the now defunct getent on OSX
#     came from
#       http://zzamboni.org/\
#         brt/2008/01/21/how-to-emulate-unix-getent-with-macosxs-dscl/
#     with an example implementation lifted from
#       https://github.com/petere/getent-osx/blob/master/getent
#
# Copyright © 2010-2013 by Zed Pobre ([email protected] or [email protected])
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#

use strict; use warnings;

$ENV{"PATH"} = "/usr/bin:/bin";

# Only run on supported $os:
my $os;
($os)=(`uname -a` =~ /^([\w-]+)/);
unless ($os =~ /(HU-UX|SunOS|Linux|Darwin)/)
    {die "\$getent or equiv. does not exist:  Cannot run on $os\n";}

my $wantedgroup = shift;

my %groupmembers;

my @users;

# Acquire the list of @users based on what is available on this OS:
if ($os =~ /(SunOS|Linux|HP-UX)/) {
    #HP-UX & Solaris assumed to be like Linux; they have not been tested.
    my $usertext = `getent passwd`;
    @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm;
};
if ($os =~ /Darwin/) {
    @users = `dscl . -ls /Users`;
    chop @users;
}

# Now just do what Zed did - thanks Zed.
foreach my $userid (@users)
{
    my $usergrouptext = `id -Gn $userid`;
    my @grouplist = split(' ',$usergrouptext);

    foreach my $group (@grouplist)
    {
        $groupmembers{$group}->{$userid} = 1;
    }
}

if($wantedgroup)
{
    print_group_members($wantedgroup);
}
else
{
    foreach my $group (sort keys %groupmembers)
    {
        print "Group ",$group," has the following members:\n";
        print_group_members($group);
        print "\n";
    }
}

sub print_group_members
{
    my ($group) = @_;
    return unless $group;

    foreach my $member (sort keys %{$groupmembers{$group}})
    {
        print $member,"\n";
    }
}

If there is a better way to share this suggestion, please let me know; I considered many ways, and this is what I came up with.

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

how to delete all commit history in github?

If you are sure you want to remove all commit history, simply delete the .git directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:

git init
git remote add origin [email protected]:user/repo

now commit your current version of code

git add *
git commit -am 'message'

and finally force the update to GitHub:

git push -f origin master

However, I suggest backing up the history (the .git folder in the repository) before taking these steps!

Remove Identity from a column in a table

If you want to do this without adding and populating a new column, without reordering the columns, and with almost no downtime because no data is changing on the table, let's do some magic with partitioning functionality (but since no partitions are used you don't need Enterprise edition):

  1. Remove all foreign keys that point to this table
  2. Script the table to be created; rename everything e.g. 'MyTable2', 'MyIndex2', etc. Remove the IDENTITY specification.
  3. You should now have two "identical"-ish tables, one full, the other empty with no IDENTITY.
  4. Run ALTER TABLE [Original] SWITCH TO [Original2]
  5. Now your original table will be empty and the new one will have the data. You have switched the metadata for the two tables (instant).
  6. Drop the original (now-empty table), exec sys.sp_rename to rename the various schema objects back to the original names, and then you can recreate your foreign keys.

For example, given:

CREATE TABLE Original
(
  Id INT IDENTITY PRIMARY KEY
, Value NVARCHAR(300)
);
CREATE NONCLUSTERED INDEX IX_Original_Value ON Original (Value);

INSERT INTO Original
SELECT 'abcd'
UNION ALL 
SELECT 'defg';

You can do the following:

--create new table with no IDENTITY
CREATE TABLE Original2
(
  Id INT PRIMARY KEY
, Value NVARCHAR(300)
);
CREATE NONCLUSTERED INDEX IX_Original_Value2 ON Original2 (Value);

--data before switch
SELECT 'Original', *
FROM Original
UNION ALL
SELECT 'Original2', *
FROM Original2;

ALTER TABLE Original SWITCH TO Original2;

--data after switch
SELECT 'Original', *
FROM Original
UNION ALL
SELECT 'Original2', *
FROM Original2;

--clean up 
IF NOT EXISTS (SELECT * FROM Original) DROP TABLE Original;
EXEC sys.sp_rename 'Original2.IX_Original_Value2', 'IX_Original_Value', 'INDEX';
EXEC sys.sp_rename 'Original2', 'Original', 'OBJECT';


UPDATE Original
SET Id = Id + 1;

SELECT *
FROM Original;

How to calculate number of days between two dates

Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.

How can my iphone app detect its own version number?

You can try using dictionary as:-

NSDictionary *infoDictionary = [[NSBundle mainBundle]infoDictionary];

NSString *buildVersion = infoDictionary[(NSString*)kCFBundleVersionKey];
NSString *bundleName = infoDictionary[(NSString *)kCFBundleNameKey]

Initialize a long in Java

You need to add uppercase L at the end like so

long i = 12345678910L;

Same goes true for float with 3.0f

Which should answer both of your questions

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained by @Nitzan Tomer. But also you can just define property as any, if you want to write code almost as in JavaScript:

arr.filter((item:any) => {
    return item.isSelected == true;
}

How to store Node.js deployment settings/configuration files?

Here is a neat approach inspired by this article. It does not require any additional packages except the ubiquitous lodash package. Moreover, it lets you manage nested defaults with environment-specific overwrites.

First, create a config folder in the package root path that looks like this

package
  |_config
      |_ index.js
      |_ defaults.json
      |_ development.json
      |_ test.json
      |_ production.json

here is the index.js file

const _ = require("lodash");
const defaults = require("./defaults.json");
const envConf = require("./" + (process.env.NODE_ENV || "development") + ".json" );
module.exports = _.defaultsDeep(envConf, defaults);

Now let's assume we have a defaults.json like so

{
  "confKey1": "value1",
  "confKey2": {
    "confKey3": "value3",
    "confKey4": "value4"
  }
}

and development.json like so

{
  "confKey2": {
    "confKey3": "value10",
  }
}

if you do config = require('./config') here is what you will get

{
  "confKey1": "value1",
  "confKey2": {
    "confKey3": "value10",
    "confKey4": "value4"
  }
}

Notice that you get all the default values except for those defined in environment-specific files. So you can manage a config hierarchy. Using defaultsDeep makes sure that you can even have nested defaults.

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

As several of my friend has posted there are many free leak detectors for C++. All of that will cause overhead when running your code, approximatly 20% slower. I preffer Visual Leak Detector for Visual C++ 2008/2010/2012 , you can download the source code from - enter link description here .

Create dynamic variable name

This is not possible, it will give you a compile time error,

You can use array for this type of requirement .

For your Reference :

http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

Iterating over dictionaries using 'for' loops

key is just a variable name.

for key in d:

will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:

For Python 3.x:

for key, value in d.items():

For Python 2.x:

for key, value in d.iteritems():

To test for yourself, change the word key to poop.

In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better. This is also available in 2.7 as viewitems().

The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).

Adding two numbers concatenates them instead of calculating the sum

Just add a simple type casting method as the input is taken in text. Use the following:

    var y = parseInt(document.getElementById("txt1").value);
    var z = parseInt(document.getElementById("txt2").value);
    var x = y + z;

Oracle PL/SQL string compare issue

As Phil noted, the empty string is treated as a NULL, and NULL is not equal or unequal to anything. If you expect empty strings or NULLs, you'll need to handle those with NVL():

 DECLARE
 str1  varchar2(4000);
 str2  varchar2(4000);
 BEGIN
   str1:='';
   str2:='sdd';
-- Provide an alternate null value that does not exist in your data:
   IF(NVL(str1,'X') != NVL(str2,'Y')) THEN
    dbms_output.put_line('The two strings are not equal');
   END IF;
 END;
 /

Concerning null comparisons:

According to the Oracle 12c documentation on NULLS, null comparisons using IS NULL or IS NOT NULL do evaluate to TRUE or FALSE. However, all other comparisons evaluate to UNKNOWN, not FALSE. The documentation further states:

A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT statement with a condition in the WHERE clause that evaluates to UNKNOWN returns no rows. However, a condition evaluating to UNKNOWN differs from FALSE in that further operations on an UNKNOWN condition evaluation will evaluate to UNKNOWN. Thus, NOT FALSE evaluates to TRUE, but NOT UNKNOWN evaluates to UNKNOWN.

A reference table is provided by Oracle:

Condition       Value of A    Evaluation
----------------------------------------
a IS NULL       10            FALSE
a IS NOT NULL   10            TRUE        
a IS NULL       NULL          TRUE
a IS NOT NULL   NULL          FALSE
a = NULL        10            UNKNOWN
a != NULL       10            UNKNOWN
a = NULL        NULL          UNKNOWN
a != NULL       NULL          UNKNOWN
a = 10          NULL          UNKNOWN
a != 10         NULL          UNKNOWN

I also learned that we should not write PL/SQL assuming empty strings will always evaluate as NULL:

Oracle Database currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as nulls.

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

You need "VT-x supported processor" at least to run Android emulator with Hardware acceleration.

If you have enabled or installed "Hyper-V" in your windows 8 then please remove it and disable the "Hyper threading" and enable "Virtualization".

How to run a .jar in mac?

Make Executable your jar and after that double click on it on Mac OS then it works successfully.

sudo chmod +x filename.jar

Try this, I hope this works.

Method has the same erasure as another method in type

Java generics uses type erasure. The bit in the angle brackets (<Integer> and <String>) gets removed, so you'd end up with two methods that have an identical signature (the add(Set) you see in the error). That's not allowed because the runtime wouldn't know which to use for each case.

If Java ever gets reified generics, then you could do this, but that's probably unlikely now.

How to access URL segment(s) in blade in Laravel 5?

An easy way to get the first or last segment, in case you are unsure of the path length.

$segments = request()->segments();
$last  = end($segments);
$first = reset($segments);

Python one-line "for" expression

Even array2.extend(array1) will work.

Using Sockets to send and receive data

I assume you are using TCP sockets for the client-server interaction? One way to send different types of data to the server and have it be able to differentiate between the two is to dedicate the first byte (or more if you have more than 256 types of messages) as some kind of identifier. If the first byte is one, then it is message A, if its 2, then its message B. One easy way to send this over the socket is to use DataOutputStream/DataInputStream:

Client:

Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data

// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data

// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data

// Send the exit message
dOut.writeByte(-1);
dOut.flush();

dOut.close();

Server:

Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());

boolean done = false;
while(!done) {
  byte messageType = dIn.readByte();

  switch(messageType)
  {
  case 1: // Type A
    System.out.println("Message A: " + dIn.readUTF());
    break;
  case 2: // Type B
    System.out.println("Message B: " + dIn.readUTF());
    break;
  case 3: // Type C
    System.out.println("Message C [1]: " + dIn.readUTF());
    System.out.println("Message C [2]: " + dIn.readUTF());
    break;
  default:
    done = true;
  }
}

dIn.close();

Obviously, you can send all kinds of data, not just bytes and strings (UTF).

Note that writeUTF writes a modified UTF-8 format, preceded by a length indicator of an unsigned two byte encoded integer giving you 2^16 - 1 = 65535 bytes to send. This makes it possible for readUTF to find the end of the encoded string. If you decide on your own record structure then you should make sure that the end and type of the record is either known or detectable.

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

asp.net: Invalid postback or callback argument

I had the same problem, two list boxes and two buttons.

The data in the list boxes was being loaded from a database and you could move items between boxes by clicking the buttons.

I was getting an invalid postback.

turns out that it was the data had carriage return line feeds in it which you cannot see when displayed in the list box.

worked fine in every browser except IE 10 and IE 11.

Remove the carriage return line feeds and all works fine.

Standard Android Button with a different color

Use it in this way:

buttonOBJ.getBackground().setColorFilter(Color.parseColor("#YOUR_HEX_COLOR_CODE"), PorterDuff.Mode.MULTIPLY);

Convert HashBytes to VarChar

Use master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0) instead of master.dbo.fn_varbintohexstr and then substringing the result.

In fact fn_varbintohexstr calls fn_varbintohexsubstring internally. The first argument of fn_varbintohexsubstring tells it to add 0xF as the prefix or not. fn_varbintohexstr calls fn_varbintohexsubstring with 1 as the first argument internaly.

Because you don't need 0xF, call fn_varbintohexsubstring directly.

How do I use an image as a submit button?

Just remove the border and add a background image in css

Example:

_x000D_
_x000D_
$("#form").on('submit', function() {_x000D_
   alert($("#submit-icon").val());_x000D_
});
_x000D_
#submit-icon {_x000D_
  background-image: url("https://pixabay.com/static/uploads/photo/2016/10/18/21/22/california-1751455__340.jpg"); /* Change url to wanted image */_x000D_
  background-size: cover;_x000D_
  border: none;_x000D_
  width: 32px;_x000D_
  height: 32px;_x000D_
  cursor: pointer;_x000D_
  color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="form">_x000D_
  <input type="submit" id="submit-icon" value="test">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Use grep to report back only line numbers

try:

grep -n "text to find" file.ext | cut -f1 -d:

Get DataKey values in GridView RowCommand

On the Button:

CommandArgument='<%# Eval("myKey")%>'

On the Server Event

e.CommandArgument

sending email via php mail function goes to spam

If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.

What's wrong with using == to compare floats in Java?

This is a problem not specific to java. Using == to compare two floats/doubles/any decimal type number can potentially cause problems because of the way they are stored. A single-precision float (as per IEEE standard 754) has 32 bits, distributed as follows:

1 bit - Sign (0 = positive, 1 = negative)
8 bits - Exponent (a special (bias-127) representation of the x in 2^x)
23 bits - Mantisa. The actuall number that is stored.

The mantisa is what causes the problem. It's kinda like scientific notation, only the number in base 2 (binary) looks like 1.110011 x 2^5 or something similar. But in binary, the first 1 is always a 1 (except for the representation of 0)

Therefore, to save a bit of memory space (pun intended), IEEE deccided that the 1 should be assumed. For example, a mantisa of 1011 really is 1.1011.

This can cause some issues with comparison, esspecially with 0 since 0 cannot possibly be represented exactly in a float. This is the main reason the == is discouraged, in addition to the floating point math issues described by other answers.

Java has a unique problem in that the language is universal across many different platforms, each of which could have it's own unique float format. That makes it even more important to avoid ==.

The proper way to compare two floats (not-language specific mind you) for equality is as follows:

if(ABS(float1 - float2) < ACCEPTABLE_ERROR)
    //they are approximately equal

where ACCEPTABLE_ERROR is #defined or some other constant equal to 0.000000001 or whatever precision is required, as Victor mentioned already.

Some languages have this functionality or this constant built in, but generally this is a good habit to be in.

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Rails 4: List of available datatypes

Rails4 has some added datatypes for Postgres.

For example, railscast #400 names two of them:

Rails 4 has support for native datatypes in Postgres and we’ll show two of these here, although a lot more are supported: array and hstore. We can store arrays in a string-type column and specify the type for hstore.

Besides, you can also use cidr, inet and macaddr. For more information:

https://blog.engineyard.com/2013/new-in-rails-4

Set up DNS based URL forwarding in Amazon Route53

Update

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

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

Original Answer

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

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

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

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

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

How to get a web page's source code from Java

I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site

package javasandbox;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {

private static String sURL;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws MalformedURLException, IOException {
    sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
    System.out.println(sURL);
    URL url = new URL(sURL);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    //set http request headers
            httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
            httpCon.addRequestProperty("Connection", "keep-alive");
            httpCon.addRequestProperty("Cache-Control", "max-age=0");
            httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
            httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            //httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
            HttpURLConnection.setFollowRedirects(false);
            httpCon.setInstanceFollowRedirects(false);
            httpCon.setDoOutput(true);
            httpCon.setUseCaches(true);

            httpCon.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder a = new StringBuilder();
            while ((inputLine = in.readLine()) != null)
                a.append(inputLine);
            in.close();

            System.out.println(a.toString());

            httpCon.disconnect();
}
}

Jquery Date picker Default Date

i suspect that your default date format is different than the scripts default settigns. test your script with the 'dateformat' option

$( "#datepicker" ).datepicker({ 
    dateFormat: 'dd-mm-yy'
});

instead of dd-mm-yy, your desired format

Test if registry value exists

The -not test should fire if a property doesn't exist:

$prop = (Get-ItemProperty $regkey).$name
if (-not $prop)
{
   New-ItemProperty -Path $regkey -Name $name -Value "X"
}

What should I use to open a url instead of urlopen in urllib3

In urlip3 there's no .urlopen, instead try this:

import requests
html = requests.get(url)

mysql count group by having

One way would be to use a nested query:

SELECT count(*)
FROM (
   SELECT COUNT(Genre) AS count
   FROM movies
   GROUP BY ID
   HAVING (count = 4)
) AS x

The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...

...create an NSDictionary

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                       forKeys:keys];

...iterate over it

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

...make it mutable

NSMutableDictionary *mutableDict = [dictionary mutableCopy];

Note: historic version before 2010: [[dictionary mutableCopy] autorelease]

...and alter it

[mutableDict setObject:@"value3" forKey:@"key3"];

...then store it to a file

[mutableDict writeToFile:@"path/to/file" atomically:YES];

...and read it back again

NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];

...read a value

NSString *x = [anotherDict objectForKey:@"key1"];

...check if a key exists

if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");

...use scary futuristic syntax

From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]

Python function to convert seconds into minutes, hours, and days

To convert seconds (as string) into datetime, this could also help. You get number of days and seconds. Seconds can be further converted into minutes and hours.

from datetime import datetime, timedelta
sec = timedelta(seconds=(int(input('Enter the number of seconds: '))))
time = str(sec)

Change size of axes title and labels in ggplot2

To change the size of (almost) all text elements, in one place, and synchronously, rel() is quite efficient:
g+theme(text = element_text(size=rel(3.5))

You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)), strip.text.x = element_text(size=rel(3.5)), strip.text.y = element_text(size=rel(3.5)))

LINQ equivalent of foreach for IEnumerable<T>

Many people mentioned it, but I had to write it down. Isn't this most clear/most readable?

IEnumerable<Item> items = GetItems();
foreach (var item in items) item.DoStuff();

Short and simple(st).

Jquery-How to grey out the background while showing the loading icon over it

Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.

If the gif is displayed but not animating, see reference links at very bottom of this answer.

Displaying the gif + overlay, however, is easier than you might think.

All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.

So, when the button is pressed, just unhide those two divs. That's it!

jsFiddle Demo

_x000D_
_x000D_
$("#button").click(function() {_x000D_
    $('#myOverlay').show();_x000D_
    $('#loadingGIF').show();_x000D_
    setTimeout(function(){_x000D_
   $('#myOverlay, #loadingGIF').fadeOut();_x000D_
    },2500);_x000D_
});_x000D_
/*  Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
 $('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Update:

You might enjoy playing with the new backdrop-filter:blur(_px) css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)

References:

http://www.paulirish.com/2007/animated-gif-not-animating/

Animated GIF while loading page does not animate

https://wordpress.org/support/topic/animated-gif-not-working

http://forums.mozillazine.org/viewtopic.php?p=987829

How do you get AngularJS to bind to the title attribute of an A tag?

It looks like ng-attr is a new directive in AngularJS 1.1.4 that you can possibly use in this case.

<!-- example -->
<a ng-attr-title="{{product.shortDesc}}"></a>

However, if you stay with 1.0.7, you can probably write a custom directive to mirror the effect.

Android Recyclerview GridLayoutManager column spacing

thanks edwardaa's answer https://stackoverflow.com/a/30701422/2227031

Another point to note is that:

if total spacing and total itemWidth are not equal to the screen width, you also need to adjust itemWidth, for example, on adapter onBindViewHolder method

Utils.init(_mActivity);
int width = 0;
if (includeEdge) {
    width = ScreenUtils.getScreenWidth() - spacing * (spanCount + 1);
} else {
    width = ScreenUtils.getScreenWidth() - spacing * (spanCount - 1);
}
int itemWidth = width / spanCount;

ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) holder.imageViewAvatar.getLayoutParams();
// suppose the width and height are the same
layoutParams.width = itemWidth;
layoutParams.height = itemWidth;
holder.imageViewAvatar.setLayoutParams(layoutParams);

Access a global variable in a PHP function

<?php

    $data = 'My data';

    $menugen = function() use ($data) {

        echo "[ $data ]";
    };

    $menugen();
?>

You can also simplify

echo "[" . $data . "]"

to

echo "[$data]"

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

You have init'd myRequest as NSMutableURLRequest, you need this:

var URLRequest

Swift is ditching both the NSMutable... thing. Just use var for the new classes.

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 
margin:10px;
}

DEMO

Print the stack trace of an exception

See javadoc

out = some stream ...
try
{
}
catch ( Exception cause )
{
      cause . printStrackTrace ( new PrintStream ( out ) ) ;
}

jQuery Force set src attribute for iframe

Use attr

$('#abc_frame').attr('src', url)

This way you can get and set every HTML tag attribute. Note that there is also .prop(). See .prop() vs .attr() about the differences. Short version: .attr() is used for attributes as they are written in HTML source code and .prop() is for all that JavaScript attached to the DOM element.

Python spacing and aligning strings

Try %*s and %-*s and prefix each string with the column width:

>>> print "Location: %-*s  Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10           Revision: 1
>>> print "District: %-*s  Date: %s" % (20,"Tower","May 16, 2012")
District: Tower                 Date: May 16, 2012

Delete all lines starting with # or ; in Notepad++

Its possible, but not directly.

In short, go to the search, use your regex, check "mark line" and click "Find all". It results in bookmarks for all those lines.

In the search menu there is a point "delete bookmarked lines" voila.

I found the answer here (the correct answer is the second one, not the accepted!): How to delete specific lines on Notepad++?

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

There is a difference in the * usage when you are defining a variable and when you are using it.

In declaration,

int *myVariable;

Means a pointer to an integer data type. In usage however,

*myVariable = 3;

Means dereference the pointer and make the structure it is pointing at equal to three, rather then make the pointer equal to the memory address 0x 0003.

So in your function, you want to do this:

void makePointerEqualSomething(int* pInteger)
{
    *pInteger = 7;
}

In the function declaration, * means you are passing a pointer, but in its actual code body * means you are accessing what the pointer is pointing at.

In an attempt to wave away any confusion you have, I'll briefly go into the ampersand (&)

& means get the address of something, its exact location in the computers memory, so

 int & myVariable;

In a declaration means the address of an integer, or a pointer!

This however

int someData;    
pInteger = &someData;

Means make the pInteger pointer itself (remember, pointers are just memory addresses of what they point at) equal to the address of 'someData' - so now pInteger will point at some data, and can be used to access it when you deference it:

*pInteger += 9000;

Does this make sense to you? Is there anything else that you find confusing?

@Edit3:

Nearly correct, except for three statements

bar = *oof;

means that the bar pointer is equal to an integer, not what bar points at, which is invalid.

&bar = &oof;

The ampersand is like a function, once it returns a memory address you cannot modify where it came from. Just like this code:

returnThisInt("72") = 86; 

Is invalid, so is yours.

Finally,

bar = oof

Does not mean that "bar points to the oof pointer." Rather, this means that bar points to the address that oof points to, so bar points to whatever foo is pointing at - not bar points to foo which points to oof.

Making a UITableView scroll when text field is selected

A more stream-lined solution. It slips into the UITextField delegate methods, so it doesn't require messing w/ UIKeyboard notifications.

Implementation notes:

kSettingsRowHeight -- the height of a UITableViewCell.

offsetTarget and offsetThreshold are baed off of kSettingsRowHeight. If you use a different row height, set those values to point's y property. [alt: calculate the row offset in a different manner.]

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
CGFloat offsetTarget    = 113.0f; // 3rd row
CGFloat offsetThreshold = 248.0f; // 6th row (i.e. 2nd-to-last row)

CGPoint point = [self.tableView convertPoint:CGPointZero fromView:textField];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

CGRect frame = self.tableView.frame;
if (point.y > offsetThreshold) {
    self.tableView.frame = CGRectMake(0.0f,
                      offsetTarget - point.y + kSettingsRowHeight,
                      frame.size.width,
                      frame.size.height);
} else if (point.y > offsetTarget) {
    self.tableView.frame = CGRectMake(0.0f,
                      offsetTarget - point.y,
                      frame.size.width,
                      frame.size.height);
} else {
    self.tableView.frame = CGRectMake(0.0f,
                      0.0f,
                      frame.size.width,
                      frame.size.height);
}

[UIView commitAnimations];

return YES;

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

CGRect frame = self.tableView.frame;
self.tableView.frame = CGRectMake(0.0f,
                  0.0f,
                  frame.size.width,
                  frame.size.height);

[UIView commitAnimations];

return YES;

}

Conversion of Char to Binary in C

Your code is very vague and not understandable, but I can provide you with an alternative.

First of all, if you want temp to go through the whole string, you can do something like this:

char *temp;
for (temp = your_string; *temp; ++temp)
    /* do something with *temp */

The term *temp as the for condition simply checks whether you have reached the end of the string or not. If you have, *temp will be '\0' (NUL) and the for ends.

Now, inside the for, you want to find the bits that compose *temp. Let's say we print the bits:

for (as above)
{
    int bit_index;
    for (bit_index = 7; bit_index >= 0; --bit_index)
    {
        int bit = *temp >> bit_index & 1;
        printf("%d", bit);
    }
    printf("\n");
}

To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7 to bit_index = sizeof(*temp)*8-1

How generate unique Integers based on GUIDs

Because the GUID space is larger than the number of 32-bit integers, you're guaranteed to have collisions if you have enough GUIDs. Given that you understand that and are prepared to deal with collisions, however rare, GetHashCode() is designed for exactly this purpose and should be preferred.

Run a mySQL query as a cron job?

It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:

# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php

On my system, I don't even have to put the path to the php installation:

00 * * * * php /home/path/script.php

On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.

Creating a button in Android Toolbar

Another possibility is to set the app:actionViewClass attribute in your menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
  <item
     android:id="@+id/get_item"
     android:orderInCategory="1"
     android:text="Get"
     app:showAsAction="always" 
     app:actionViewClass="android.support.v7.widget.AppCompatButton"/>
</menu>

In your code you can access this button after the menu was inflated:

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.sample, menu);

    MenuItem getItem = menu.findItem(R.id.get_item);
    if (getItem != null) {
        AppCompatButton button = (AppCompatButton) getItem.getActionView();
        //Set a ClickListener, the text, 
        //the background color or something like that
    }

    return super.onCreateOptionsMenu(menu);
}