Programs & Examples On #Add type

UTF-8 output from PowerShell

Not an expert on encoding, but after reading these...

... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.

If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding parameter on the out-file cmdlet e.g.

write-output "hello" | out-file "enctest.txt" -encoding utf8

Nothing else you can do on the PowerShell front then, but the following post may well help you:.

In PowerShell, how can I test if a variable holds a numeric value?

You can check whether the variable is a number like this: $val -is [int]

This will work for numeric values, but not if the number is wrapped in quotes:

1 -is [int]
True
"1" -is [int]
False

Passing on command line arguments to runnable JAR

You can pass program arguments on the command line and get them in your Java app like this:

public static void main(String[] args) {
  String pathToXml = args[0];
....
}

Alternatively you pass a system property by changing the command line to:

java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt

and your main class to:

public static void main(String[] args) {
  String pathToXml = System.getProperty("path-to-xml");
....
}

How to format Joda-Time DateTime to only mm/dd/yyyy?

Note that in JAVA SE 8 a new java.time (JSR-310) package was introduced. This replaces Joda time, Joda users are advised to migrate. For the JAVA SE = 8 way of formatting date and time, see below.

Joda time

Create a DateTimeFormatter using DateTimeFormat.forPattern(String)

Using Joda time you would do it like this:

String dateTime = "11/15/2013 08:00:00";
// Format for input
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
// Parsing the date
DateTime jodatime = dtf.parseDateTime(dateTime);
// Format for output
DateTimeFormatter dtfOut = DateTimeFormat.forPattern("MM/dd/yyyy");
// Printing the date
System.out.println(dtfOut.print(jodatime));

Standard Java = 8

Java 8 introduced a new Date and Time library, making it easier to deal with dates and times. If you want to use standard Java version 8 or beyond, you would use a DateTimeFormatter. Since you don't have a time zone in your String, a java.time.LocalDateTime or a LocalDate, otherwise the time zoned varieties ZonedDateTime and ZonedDate could be used.

// Format for input
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
// Parsing the date
LocalDate date = LocalDate.parse(dateTime, inputFormat);
// Format for output
DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy");
// Printing the date
System.out.println(date.format(outputFormat));

Standard Java < 8

Before Java 8, you would use the a SimpleDateFormat and java.util.Date

String dateTime = "11/15/2013 08:00:00";
// Format for input
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
// Parsing the date
Date date7 = dateParser.parse(dateTime);
// Format for output
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
// Printing the date
System.out.println(dateFormatter.format(date7));

How to group subarrays by a column value?

1. GROUP BY one key

This function works as GROUP BY for array, but with one important limitation: Only one grouping "column" ($identifier) is possible.

function arrayUniqueByIdentifier(array $array, string $identifier)
{
    $ids = array_column($array, $identifier);
    $ids = array_unique($ids);
    $array = array_filter($array,
        function ($key, $value) use($ids) {
            return in_array($value, array_keys($ids));
        }, ARRAY_FILTER_USE_BOTH);
    return $array;
}

2. Detecting the unique rows for a table (twodimensional array)

This function is for filtering "rows". If we say, a twodimensional array is a table, then its each element is a row. So, we can remove the duplicated rows with this function. Two rows (elements of the first dimension) are equal, if all their columns (elements of the second dimension) are equal. To the comparsion of "column" values applies: If a value is of a simple type, the value itself will be use on comparing; otherwise its type (array, object, resource, unknown type) will be used.

The strategy is simple: Make from the original array a shallow array, where the elements are imploded "columns" of the original array; then apply array_unique(...) on it; and as last use the detected IDs for filtering of the original array.

function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}

It's also possible to improve the comparing, detecting the "column" value's class, if its type is object.

The $implodeSeparator should be more or less complex, z.B. spl_object_hash($this).


3. Detecting the rows with unique identifier columns for a table (twodimensional array)

This solution relies on the 2nd one. Now the complete "row" doesn't need to be unique. Two "rows" (elements of the first dimension) are equal now, if all relevant "fields" (elements of the second dimension) of the one "row" are equal to the according "fields" (elements with the same key).

The "relevant" "fields" are the "fields" (elements of the second dimension), which have key, that equals to one of the elements of the passed "identifiers".

function arrayUniqueByMultipleIdentifiers(array $table, array $identifiers, string $implodeSeparator = null)
{
    $arrayForMakingUniqueByRow = $removeArrayColumns($table, $identifiers, true);
    $arrayUniqueByRow = $arrayUniqueByRow($arrayForMakingUniqueByRow, $implodeSeparator);
    $arrayUniqueByMultipleIdentifiers = array_intersect_key($table, $arrayUniqueByRow);
    return $arrayUniqueByMultipleIdentifiers;
}

function removeArrayColumns(array $table, array $columnNames, bool $isWhitelist = false)
{
    foreach ($table as $rowKey => $row) {
        if (is_array($row)) {
            if ($isWhitelist) {
                foreach ($row as $fieldName => $fieldValue) {
                    if (!in_array($fieldName, $columnNames)) {
                        unset($table[$rowKey][$fieldName]);
                    }
                }
            } else {
                foreach ($row as $fieldName => $fieldValue) {
                    if (in_array($fieldName, $columnNames)) {
                        unset($table[$rowKey][$fieldName]);
                    }
                }
            }
        }
    }
    return $table;
}

get the data of uploaded file in javascript

you can use the new HTML 5 file api to read file contents

https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

but this won't work on every browser so you probably need a server side fallback.

Web link to specific whatsapp contact

This approach only works on Android AND if you have the number on your contact list. If you don't have it, Android opens your SMS app, so you can invite the contact to use Whatsapp.

<a href="https://api.whatsapp.com/send?phone=2567xxxxxxxxx" method="get" target="_blank"><i class="fa fa-whatsapp"></i></a>

Google Chrome am targeting a blank window

How to get JSON from webpage into Python script

In Python 2, json.load() will work instead of json.loads()

import json
import urllib

url = 'https://api.github.com/users?since=100'
output = json.load(urllib.urlopen(url))
print(output)

Unfortunately, that doesn't work in Python 3. json.load is just a wrapper around json.loads that calls read() for a file-like object. json.loads requires a string object and the output of urllib.urlopen(url).read() is a bytes object. So one has to get the file encoding in order to make it work in Python 3.

In this example we query the headers for the encoding and fall back to utf-8 if we don't get one. The headers object is different between Python 2 and 3 so it has to be done different ways. Using requests would avoid all this, but sometimes you need to stick to the standard library.

import json
from six.moves.urllib.request import urlopen

DEFAULT_ENCODING = 'utf-8'
url = 'https://api.github.com/users?since=100'
urlResponse = urlopen(url)

if hasattr(urlResponse.headers, 'get_content_charset'):
    encoding = urlResponse.headers.get_content_charset(DEFAULT_ENCODING)
else:
    encoding = urlResponse.headers.getparam('charset') or DEFAULT_ENCODING

output = json.loads(urlResponse.read().decode(encoding))
print(output)

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

Open up terminal first and then go to directory of web server

cd /Library/WebServer/Documents

and then type this and what you will do is you will give read and write permission

sudo chmod -R o+w /Library/WebServer/Documents

This will surely work!

Using CSS to insert text

Also check out the attr() function of the CSS content attribute. It outputs a given attribute of the element as a text node. Use it like so:

<div class="Owner Joe" />

div:before {
  content: attr(class);
}

Or even with the new HTML5 custom data attributes:

<div data-employeename="Owner Joe" />

div:before {
  content: attr(data-employeename);
}

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;
}

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;
}

How to test the type of a thrown exception in Jest

Try:

expect(t).rejects.toThrow()

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use this in your my.ini under

[mysqldump]
    user=root
    password=anything

Split string into strings by length?

length = 4
string = "abcdefgh"
str_dict = [ o for o in string ]
parts = [ ''.join( str_dict[ (j * length) : ( ( j + 1 ) * length ) ]   ) for j in xrange(len(string)/length  )]

How can I edit a .jar file?

A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.

Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.

You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.

Convert String to System.IO.Stream

System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));

Java word count program

You can use String.split (read more here) instead of charAt, you will get good results. If you want to use charAt for some reason then try trimming the string before you count the words that way you won't have the extra space and an extra word

PHP 7: Missing VCRUNTIME140.dll

I had the same issue, I changed the ports, restarted the services but in vein, only worked for me when I updated the Microsoft Visual c++ filesFrom There yoy can modify MVC

Get week of year in JavaScript like in PHP

Get the weeknumber of any given Date

function week(year,month,day) {
    function serial(days) { return 86400000*days; }
    function dateserial(year,month,day) { return (new Date(year,month-1,day).valueOf()); }
    function weekday(date) { return (new Date(date)).getDay()+1; }
    function yearserial(date) { return (new Date(date)).getFullYear(); }
    var date = year instanceof Date ? year.valueOf() : typeof year === "string" ? new Date(year).valueOf() : dateserial(year,month,day), 
        date2 = dateserial(yearserial(date - serial(weekday(date-serial(1))) + serial(4)),1,3);
    return ~~((date - date2 + serial(weekday(date2) + 5))/ serial(7));
}

Example

console.log(
    week(2016, 06, 11),//23
    week(2015, 9, 26),//39
    week(2016, 1, 1),//53
    week(2016, 1, 4),//1
    week(new Date(2016, 0, 4)),//1
    week("11 january 2016")//2
);

Change color of Back button in navigation bar

    self.navigationController?.navigationBar.tintColor = UIColor.black // to change the all text color in navigation bar or navigation 
    self.navigationController?.navigationBar.barTintColor = UIColor.white // change the navigation background color
    self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.black] // To change only navigation bar title text color

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

How to recover corrupted Eclipse workspace?

I have succesfully recovered my existing workspace from a totally messed up situation (all kinds of core components giving NPE's and ClassCastExceptions and the like) by using this procedure:

  • Open Eclipse
  • Close error dialog
  • Select first project in the workspace
  • Right-click -> Refresh
  • Close error dialog
  • Close Eclipse
  • Close error dialog
  • Repeat for all projects in the workspace
  • (if your projects are in CVS/SVN etc, synchronize them)
  • Clean and rebuild all projects
  • Fixed

This whole procedure took me over half an hour for a big workspace, but it did fix it in the end.

How to get IP address of running docker container

Use --format option to get only the IP address instead whole container info:

sudo docker inspect --format '{{ .NetworkSettings.IPAddress }}' <CONTAINER ID>

find all unchecked checkbox in jquery

You can use like this :

$(":checkbox:not(:checked)")

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

I have tried above all issue but was not working for me What I tried is

First of all, I want to go with manual code signing process, I am not doing via automatic code signing

  • I specify team name enter image description here
  • Then change deployment target enter image description here
  • Clean and build

You will good to go now

Difference between SRC and HREF

I think <src> adds some resources to the page and <href> is just for providing a link to a resource(without adding the resource itself to the page).

How to remove outliers from a dataset

Use outline = FALSE as an option when you do the boxplot (read the help!).

> m <- c(rnorm(10),5,10)
> bp <- boxplot(m, outline = FALSE)

enter image description here

Parse String date in (yyyy-MM-dd) format

DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String cunvertCurrentDate="06/09/2015";
Date date = new Date();
date = df.parse(cunvertCurrentDate);

How to create separate AngularJS controller files?

Using the angular.module API with an array at the end will tell angular to create a new module:

myApp.js

// It is like saying "create a new module"
angular.module('myApp.controllers', []); // Notice the empty array at the end here

Using it without the array is actually a getter function. So to seperate your controllers, you can do:

Ctrl1.js

// It is just like saying "get this module and create a controller"
angular.module('myApp.controllers').controller('Ctrlr1', ['$scope', '$http', function($scope, $http) {}]);

Ctrl2.js

angular.module('myApp.controllers').controller('Ctrlr2', ['$scope', '$http', function($scope, $http) {}]);

During your javascript imports, just make sure myApp.js is after AngularJS but before any controllers / services / etc...otherwise angular won't be able to initialize your controllers.

How to center the text in a JLabel?

String text = "In early March, the city of Topeka, Kansas," + "<br>" +
              "temporarily changed its name to Google..." + "<br>" + "<br>" +
              "...in an attempt to capture a spot" + "<br>" +
              "in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
              "source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");

Equal height rows in a flex container

The answer is NO.

The reason is provided in the flexbox specification:

6. Flex Lines

In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.

In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.

Equal height rows, however, are possible in CSS Grid Layout:

Otherwise, consider a JavaScript alternative.

Accessing Objects in JSON Array (JavaScript)

Use a loop

for(var i = 0; i < obj.length; ++i){
   //do something with obj[i]
   for(var ind in obj[i]) {
        console.log(ind);
        for(var vals in obj[i][ind]){
            console.log(vals, obj[i][ind][vals]);
        }
   }
}

Demo: http://jsfiddle.net/maniator/pngmL/

Authentication failed because remote party has closed the transport stream

This happened to me when an web request endpoint was switched to another server that accepted TLS1.2 requests only. Tried so many attempts mostly found on Stackoverflow like

  1. Registry Keys ,
  2. Added :
    System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12; to Global.ASX OnStart,
  3. Added in Web.config.
  4. Updated .Net framework to 4.7.2 Still getting same Exception.

The exception received did no make justice to the actual problem I was facing and found no help from the service operator.

To solve this I have to add a new Cipher Suite TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 I have used IIS Crypto 2.0 Tool from here as shown below.

enter image description here

How to upgrade Git to latest version on macOS?

After searching for "trouble upgrading git on mac" on Google, I read several posts and attempted the following before resolving the problem by completing step 4:

  1. I updated my terminal path by using the above mention export command. Every time I quit the terminal and restarted it, when I typed git --version the terminal, it still return the older version 1.8.

  2. I followed the README.txt instructions for upgrading to the current version 2.0.1 that comes with the .dmg installer and when I restarted the terminal, still no go.

  3. I looked for /etc/path/ folder as instructed above and the directory called "path" does not exist on my Mac. I am running OS X Mavericks version 10.9.4.

  4. Then I recalled I have Homebrew installed on my Mac and ran the following:

    brew --version
    brew update
    brew search git
    brew install git
    

This finally resolved my problem. If anyone has some insight as to why this worked, further insight would be greatly appreciated. I probably have some left over path settings on my system from working with Ruby last year.

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

difference between new String[]{} and new String[] in java

{} defines the contents of the array, in this case it is empty. These would both have an array of three Strings

String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};

while [] on the expression side (right side of =) of a statement defines the size of an intended array, e.g. this would have an array of 10 locations to place Strings

String[] array = new String[10];

...But...

String array = new String[10]{};  //The line you mentioned above

Was wrong because you are defining an array of length 10 ([10]), then defining an array of length 0 ({}), and trying to set them to the same array reference (array) in one statement. Both cannot be set.

Additionally

The array should be defined as an array of a given type at the start of the statement like String[] array. String array = /* array value*/ is saying, set an array value to a String, not to an array of Strings.

In Python, how do you convert seconds since epoch to a `datetime` object?

Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:

"This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It’s common for this to be restricted to years in 1970 through 2038"

See also Issue1646728

Materialize CSS - Select Doesn't Seem to Render

@littleguy23 That is correct, but you don't want to do it to multi select. So just a small change to the code:

$(document).ready(function() {
    // Select - Single
    $('select:not([multiple])').material_select();
});

Pointer vs. Reference

Pointers:

  • Can be assigned nullptr (or NULL).
  • At the call site, you must use & if your type is not a pointer itself, making explicitly you are modifying your object.
  • Pointers can be rebound.

References:

  • Cannot be null.
  • Once bound, cannot change.
  • Callers don't need to explicitly use &. This is considered sometimes bad because you must go to the implementation of the function to see if your parameter is modified.

How to restrict UITextField to take only numbers in Swift?

Solution for swift 3.0 and above

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacters = CharacterSet.decimalDigits
    let characterSet = CharacterSet(charactersIn: string)
    return allowedCharacters.isSuperset(of: characterSet)
}

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I think that's another case of git error messages being misleading. Usually when I've seen that error it's due to ssh problems. Did you add your public ssh key to your github account?

Edit: Also, the xinet.d forum post is referring to running the git-daemon as a service so that people could pull from your system. It's not necessary to run git-daemon to push to github.

How can I use "." as the delimiter with String.split() in java

The argument to split is a regular expression. "." matches anything so your delimiter to split on is anything.

Background Image for Select (dropdown) does not work in Chrome

you can use the below css styles for all browsers except Firefox 30

select {
  background: url(dropdown_arw.png) no-repeat right center;
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  width: 90px;
  text-indent: 0.01px;
  text-overflow: "";
}

demo page - http://kvijayanand.in/jquery-plugin/test.html

Updated

here is solution for Firefox 30. little trick for custom select elements in firefox :-moz-any() css pseudo class.

http://blog.kvijayanand.in/customize-select-arrow-css/

Create sequence of repeated values, in sequence?

You missed the each= argument to rep():

R> n <- 3
R> rep(1:5, each=n)
 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R> 

so your example can be done with a simple

R> rep(1:8, each=20)

How do I undo a checkout in git?

To undo git checkout do git checkout -, similarly to cd and cd - in shell.

What is a good way to handle exceptions when trying to read a file in python?

Adding to @Josh's example;

fName = [FILE TO OPEN]
if os.path.exists(fName):
    with open(fName, 'rb') as f:
        #add you code to handle the file contents here.
elif IOError:
    print "Unable to open file: "+str(fName)

This way you can attempt to open the file, but if it doesn't exist (if it raises an IOError), alert the user!

Spring MVC - How to get all request params in a map in Spring controller?

While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

AngularJS: factory $http.get JSON file

I wanted to note that the fourth part of Accepted Answer is wrong .

theApp.factory('mainInfo', function($http) { 

var obj = {content:null};

$http.get('content.json').success(function(data) {
    // you can do some processing here
    obj.content = data;
});    

return obj;    
});

The above code as @Karl Zilles wrote will fail because obj will always be returned before it receives data (thus the value will always be null) and this is because we are making an Asynchronous call.

The details of similar questions are discussed in this post


In Angular, use $promise to deal with the fetched data when you want to make an asynchronous call.

The simplest version is

theApp.factory('mainInfo', function($http) { 
    return {
        get:  function(){
            $http.get('content.json'); // this will return a promise to controller
        }
});


// and in controller

mainInfo.get().then(function(response) { 
    $scope.foo = response.data.contentItem;
});

The reason I don't use success and error is I just found out from the doc, these two methods are deprecated.

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.

Untrack files from git temporarily

Use following command to untrack files

git rm --cached <file path>

How do you define a class of constants in Java?

Your clarification states: "I'm not going to use enums, I am not enumerating anything, just collecting some constants which are not related to each other in any way."

If the constants aren't related to each other at all, why do you want to collect them together? Put each constant in the class which it's most closely related to.

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

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

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

pandas three-way joining multiple dataframes on columns

In python 3.6.3 with pandas 0.22.0 you can also use concat as long as you set as index the columns you want to use for the joining

pd.concat(
    (iDF.set_index('name') for iDF in [df1, df2, df3]),
    axis=1, join='inner'
).reset_index()

where df1, df2, and df3 are defined as in John Galt's answer

import pandas as pd
df1 = pd.DataFrame(np.array([
    ['a', 5, 9],
    ['b', 4, 61],
    ['c', 24, 9]]),
    columns=['name', 'attr11', 'attr12']
)
df2 = pd.DataFrame(np.array([
    ['a', 5, 19],
    ['b', 14, 16],
    ['c', 4, 9]]),
    columns=['name', 'attr21', 'attr22']
)
df3 = pd.DataFrame(np.array([
    ['a', 15, 49],
    ['b', 4, 36],
    ['c', 14, 9]]),
    columns=['name', 'attr31', 'attr32']
)

How to make cross domain request

Do a cross-domain AJAX call

Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Check the following for more information

Make cross-domain ajax JSONP request with jQuery

Get current time in hours and minutes

date +%H:%M

Would be easier, I think :). If you really wanted to chop off the seconds, you could have done

date | sed 's/.* \([0-9]*:[0-9]*\):[0-9]*.*/\1/'

AngularJS custom filter function

Here's an example of how you'd use filter within your AngularJS JavaScript (rather than in an HTML element).

In this example, we have an array of Country records, each containing a name and a 3-character ISO code.

We want to write a function which will search through this list for a record which matches a specific 3-character code.

Here's how we'd do it without using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.
    for (var i = 0; i < $scope.CountryList.length; i++) {
        if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
            return $scope.CountryList[i];
        };
    };
    return null;
};

Yup, nothing wrong with that.

But here's how the same function would look, using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.

    var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })

    //  If 'filter' didn't find any matching records, its result will be an array of 0 records.
    if (matches.length == 0)
        return null;

    //  Otherwise, it should've found just one matching record
    return matches[0];
};

Much neater.

Remember that filter returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.

Hope this helps.

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

Restoring database from .mdf and .ldf files of SQL Server 2008

First google search yielded me this answer. So I thought of updating this with newer version of attach, detach.

Create database dbname 
On 
(   
Filename= 'path where you copied files',   
Filename ='path where you copied log'
)
For attach; 

Further,if your database is cleanly shutdown(there are no active transactions while database was shutdown) and you dont have log file,you can use below method,SQL server will create a new transaction log file..

Create database dbname 
    On 
    (   
    Filename= 'path where you copied files'   
    )
    For attach; 

if you don't specify transaction log file,SQL will try to look in the default path and will try to use it irrespective of whether database was cleanly shutdown or not..

Here is what MSDN has to say about this..

If a read-write database has a single log file and you do not specify a new location for the log file, the attach operation looks in the old location for the file. If it is found, the old log file is used, regardless of whether the database was shut down cleanly. However, if the old log file is not found and if the database was shut down cleanly and has no active log chain, the attach operation attempts to build a new log file for the database.

There are some restrictions with this approach and some side affects too..

1.attach-and-detach operations both disable cross-database ownership chaining for the database
2.Database trustworthy is set to off
3.Detaching a read-only database loses information about the differential bases of differential backups.

Most importantly..you can't attach a database with recent versions to an earlier version

References:
https://msdn.microsoft.com/en-in/library/ms190794.aspx

Check if array is empty or null

I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.

In the isEmptyObject doc, it mentions:

The argument should always be a plain JavaScript Object

which you can determine by $.isPlainObject. The return of $.isPlainObject([]) is false.

Plot smooth line with PyPlot

You could use scipy.interpolate.spline to smooth out your data yourself:

from scipy.interpolate import spline

# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)  

power_smooth = spline(T, power, xnew)

plt.plot(xnew,power_smooth)
plt.show()

spline is deprecated in scipy 0.19.0, use BSpline class instead.

Switching from spline to BSpline isn't a straightforward copy/paste and requires a little tweaking:

from scipy.interpolate import make_interp_spline, BSpline

# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300) 

spl = make_interp_spline(T, power, k=3)  # type: BSpline
power_smooth = spl(xnew)

plt.plot(xnew, power_smooth)
plt.show()

Before: screenshot 1

After: screenshot 2

Getting the thread ID from a thread

You can use Thread.GetHashCode, which returns the managed thread ID. If you think about the purpose of GetHashCode, this makes good sense -- it needs to be a unique identifier (e.g. key in a dictionary) for the object (the thread).

The reference source for the Thread class is instructive here. (Granted, a particular .NET implementation may not be based on this source code, but for debugging purposes I'll take my chances.)

GetHashCode "provides this hash code for algorithms that need quick checks of object equality," so it is well-suited for checking Thread equality -- for example to assert that a particular method is executing on the thread you wanted it called from.

database vs. flat files

  1. Databases can handle querying tasks, so you don't have to walk over files manually. Databases can handle very complicated queries.
  2. Databases can handle indexing tasks, so if tasks like get record with id = x can be VERY fast
  3. Databases can handle multiprocess/multithreaded access.
  4. Databases can handle access from network
  5. Databases can watch for data integrity
  6. Databases can update data easily (see 1) )
  7. Databases are reliable
  8. Databases can handle transactions and concurrent access
  9. Databases + ORMs let you manipulate data in very programmer friendly way.

How to get visitor's location (i.e. country) using geolocation?

You can use your IP address to get your 'country', 'city', 'isp' etc...
Just use one of the web-services that provide you with a simple api like http://ip-api.com which provide you a JSON service at http://ip-api.com/json. Simple send a Ajax (or Xhr) request and then parse the JSON to get whatever data you need.

var requestUrl = "http://ip-api.com/json";

$.ajax({
  url: requestUrl,
  type: 'GET',
  success: function(json)
  {
    console.log("My country is: " + json.country);
  },
  error: function(err)
  {
    console.log("Request failed, error= " + err);
  }
});

How to plot a subset of a data frame in R?

This chunk should do the work:

plot(var2 ~ var1, data=subset(dataframe, var3 < 150))

My best regards.

How this works:

  1. Fisrt, we make selection using the subset function. Other possibilities can be used, like, subset(dataframe, var4 =="some" & var5 > 10). The "&" operator can be used to select all "some" and over 10. Also the operator "|" could be used to select "some" or "over 10".
  2. The next step is to plot the results of the subset, using tilde (~) operator, that just imply a formula, in this case var.response ~ var.independet. Of course this is not a formula, but works great for this case.

How to insert an item at the beginning of an array in PHP?

With custom index:

$arr=array("a"=>"one", "b"=>"two");
    $arr=array("c"=>"three", "d"=>"four").$arr;

    print_r($arr);
    -------------------
    output:
    ----------------
    Array
    (
    [c]=["three"]
    [d]=["four"]
    [a]=["two"]
    [b]=["one"]
    )

HTML list-style-type dash

One of the top answers did not work for me, because, after a little bit trial and error, the li:before also needed the css rule display:inline-block.

So this is a fully working answer for me:

ul.dashes{
  list-style: none;
  padding-left: 2em;
  li{
    &:before{
      content: "-";
      text-indent: -2em;
      display: inline-block;
    }
  }
}

JSON.net: how to deserialize without using the default constructor?

The default behaviour of Newtonsoft.Json is going to find the public constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected or internal so that Newtonsoft.Json will pick your desired public constructor.

Admittedly, this solution is rather very limited to specific cases.

internal Result() { }

public Result(int? code, string format, Dictionary<string, string> details = null)
{
    Code = code ?? ERROR_CODE;
    Format = format;

    if (details == null)
        Details = new Dictionary<string, string>();
    else
        Details = details;
}

Float sum with javascript

(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);

its going to give you solution i suppose

How do I filter an array with TypeScript in Angular 2?

To filter an array irrespective of the property type (i.e. for all property types), we can create a custom filter pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: "filter" })
export class ManualFilterPipe implements PipeTransform {
  transform(itemList: any, searchKeyword: string) {
    if (!itemList)
      return [];
    if (!searchKeyword)
      return itemList;
    let filteredList = [];
    if (itemList.length > 0) {
      searchKeyword = searchKeyword.toLowerCase();
      itemList.forEach(item => {
        //Object.values(item) => gives the list of all the property values of the 'item' object
        let propValueList = Object.values(item);
        for(let i=0;i<propValueList.length;i++)
        {
          if (propValueList[i]) {
            if (propValueList[i].toString().toLowerCase().indexOf(searchKeyword) > -1)
            {
              filteredList.push(item);
              break;
            }
          }
        }
      });
    }
    return filteredList;
  }
}

//Usage

//<tr *ngFor="let company of companyList | filter: searchKeyword"></tr>

Don't forget to import the pipe in the app module

We might need to customize the logic to filer with dates.

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

jquery get height of iframe content when loaded

Accepted answer's $('iframe').load will now produce a.indexOf is not a function error. Can be updated to:

$('iframe').on('load', function() {
  // ...
});

Few others similar to .load deprecated since jQuery 1.8: "Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

How do you implement a good profanity filter?

a profanity filtering system will never be perfect, even if the programmer is cocksure and keeps abreast of all nude developments

that said, any list of 'naughty words' is likely to perform as well as any other list, since the underlying problem is language understanding which is pretty much intractable with current technology

so, the only practical solution is twofold:

  1. be prepared to update your dictionary frequently
  2. hire a human editor to correct false positives (e.g. "clbuttic" instead of "classic") and false negatives (oops! missed one!)

Best way to check if a URL is valid

function is_url($uri){
    if(preg_match( '/^(http|https):\\/\\/[a-z0-9_]+([\\-\\.]{1}[a-z_0-9]+)*\\.[_a-z]{2,5}'.'((:[0-9]{1,5})?\\/.*)?$/i' ,$uri)){
      return $uri;
    }
    else{
        return false;
    }
}

How can I convert a string to a number in Perl?

Perl is weakly typed and context based. Many scalars can be treated both as strings and numbers, depending on the operators you use. $a = 7*6; $b = 7x6; print "$a $b\n";
You get 42 777777.

There is a subtle difference, however. When you read numeric data from a text file into a data structure, and then view it with Data::Dumper, you'll notice that your numbers are quoted. Perl treats them internally as strings.
Read:$my_hash{$1} = $2 if /(.+)=(.+)\n/;.
Dump:'foo' => '42'

If you want unquoted numbers in the dump:
Read:$my_hash{$1} = $2+0 if /(.+)=(.+)\n/;.
Dump:'foo' => 42

After $2+0 Perl notices that you've treated $2 as a number, because you used a numeric operator.

I noticed this whilst trying to compare two hashes with Data::Dumper.

Editing dictionary values in a foreach loop

You are modifying the collection in this line:

colStates[key] = 0;

By doing so, you are essentially deleting and reinserting something at that point (as far as IEnumerable is concerned anyways.

If you edit a member of the value you are storing, that would be OK, but you are editing the value itself and IEnumberable doesn't like that.

The solution I've used is to eliminate the foreach loop and just use a for loop. A simple for loop won't check for changes that you know won't effect the collection.

Here's how you could do it:

List<string> keys = new List<string>(colStates.Keys);
for(int i = 0; i < keys.Count; i++)
{
    string key = keys[i];
    double  Percent = colStates[key] / TotalCount;
    if (Percent < 0.05)    
    {        
        OtherCount += colStates[key];
        colStates[key] = 0;    
    }
}

How to Free Inode Usage?

Many answers to this one so far and all of the above seem concrete. I think you'll be safe by using stat as you go along, but OS depending, you may get some inode errors creep up on you. So implementing your own stat call functionality using 64bit to avoid any overflow issues seems fairly compatible.

Assign width to half available screen width declaratively

If your widget is a Button:

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="2"
    android:orientation="horizontal">
    <Button android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="somebutton"/>

    <TextView android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
</LinearLayout>

I'm assuming you want your widget to take up one half, and another widget to take up the other half. The trick is using a LinearLayout, setting layout_width="fill_parent" on both widgets, and setting layout_weight to the same value on both widgets as well. If there are two widgets, both with the same weight, the LinearLayout will split the width between the two widgets.

How to retrieve a file from a server via SFTP?

I use this SFTP API called Zehon, it's great, so easy to use with a lot of sample code. Here is the site http://www.zehon.com

How to select a dropdown value in Selenium WebDriver using Java

code to select dropdown using xpath

Select select = new 
Select(driver.findElement(By.xpath("//select[@id='periodId']));

code to select particaular option using selectByVisibleText

select.selectByVisibleText(Last 52 Weeks);

Match two strings in one line with grep

Place the strings you want to grep for into a file

echo who    > find.txt
echo Roger >> find.txt
echo [44][0-9]{9,} >> find.txt

Then search using -f

grep -f find.txt BIG_FILE_TO_SEARCH.txt 

Load image from url

loadImage("http://relinjose.com/directory/filename.png");

Here you go

void loadImage(String image_location) {
    URL imageURL = null;
    if (image_location != null) {
        try {
            imageURL = new URL(image_location);         
            HttpURLConnection connection = (HttpURLConnection) imageURL
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
            ivdpfirst.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        //set any default
    }
}

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

_x000D_
_x000D_
select_x000D_
   c.owner,_x000D_
   c.object_name,_x000D_
   c.object_type,_x000D_
   b.sid,_x000D_
   b.serial#,_x000D_
   b.status,_x000D_
   b.osuser,_x000D_
   b.machine_x000D_
from_x000D_
   v$locked_object a,_x000D_
   v$session b,_x000D_
   dba_objects c_x000D_
where_x000D_
   b.sid = a.session_id_x000D_
and_x000D_
   a.object_id = c.object_id;_x000D_
   _x000D_
   ALTER SYSTEM KILL SESSION 'sid,serial#';
_x000D_
_x000D_
_x000D_

Difference between x86, x32, and x64 architectures?

x86 means Intel 80x86 compatible. This used to include the 8086, a 16-bit only processor. Nowadays it roughly means any CPU with a 32-bit Intel compatible instruction set (usually anything from Pentium onwards). Never read x32 being used.

x64 means a CPU that is x86 compatible but has a 64-bit mode as well (most often the 64-bit instruction set as introduced by AMD is meant; Intel's idea of a 64-bit mode was totally stupid and luckily Intel admitted that and is now using AMDs variant).

So most of the time you can simplify it this way: x86 is Intel compatible in 32-bit mode, x64 is Intel compatible in 64-bit mode.

Inserting a blank table row with a smaller height

You don't need an extra table row to create space inside a table. See this jsFiddle.
(I made the gap light grey in colour, so you can see it, but you can change that to transparent.)

Using a table row just for display purposes is table abuse!

Add borders to cells in POI generated Excel File

HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

how do I join two lists using linq or lambda expressions

 public class State
        {
            public int SID { get; set; }
            public string SName { get; set; }
            public string SCode { get; set; }
            public string SAbbrevation { get; set; }
        }

        public class Country
        {
            public int CID { get; set; }
            public string CName { get; set; }
            public string CAbbrevation { get; set; }
        }


 List<State> states = new List<State>()
            {
               new  State{  SID=1,SName="Telangana",SCode="+91",SAbbrevation="TG"},
               new  State{  SID=2,SName="Texas",SCode="512",SAbbrevation="TS"},
            };

            List<Country> coutries = new List<Country>()
            {
               new Country{CID=1,CName="India",CAbbrevation="IND"},
               new Country{CID=2,CName="US of America",CAbbrevation="USA"},
            };

            var res = coutries.Join(states, a => a.CID, b => b.SID, (a, b) => new {a.CName,b.SName}).ToList();

Ruby Arrays: select(), collect(), and map()

When dealing with a hash {}, use both the key and value to the block inside the ||.

details.map {|key,item|"" == item}

=>[false, false, true, false, false]

How to convert an xml string to a dictionary?

At one point I had to parse and write XML that only consisted of elements without attributes so a 1:1 mapping from XML to dict was possible easily. This is what I came up with in case someone else also doesnt need attributes:

def xmltodict(element):
    if not isinstance(element, ElementTree.Element):
        raise ValueError("must pass xml.etree.ElementTree.Element object")

    def xmltodict_handler(parent_element):
        result = dict()
        for element in parent_element:
            if len(element):
                obj = xmltodict_handler(element)
            else:
                obj = element.text

            if result.get(element.tag):
                if hasattr(result[element.tag], "append"):
                    result[element.tag].append(obj)
                else:
                    result[element.tag] = [result[element.tag], obj]
            else:
                result[element.tag] = obj
        return result

    return {element.tag: xmltodict_handler(element)}


def dicttoxml(element):
    if not isinstance(element, dict):
        raise ValueError("must pass dict type")
    if len(element) != 1:
        raise ValueError("dict must have exactly one root key")

    def dicttoxml_handler(result, key, value):
        if isinstance(value, list):
            for e in value:
                dicttoxml_handler(result, key, e)
        elif isinstance(value, basestring):
            elem = ElementTree.Element(key)
            elem.text = value
            result.append(elem)
        elif isinstance(value, int) or isinstance(value, float):
            elem = ElementTree.Element(key)
            elem.text = str(value)
            result.append(elem)
        elif value is None:
            result.append(ElementTree.Element(key))
        else:
            res = ElementTree.Element(key)
            for k, v in value.items():
                dicttoxml_handler(res, k, v)
            result.append(res)

    result = ElementTree.Element(element.keys()[0])
    for key, value in element[element.keys()[0]].items():
        dicttoxml_handler(result, key, value)
    return result

def xmlfiletodict(filename):
    return xmltodict(ElementTree.parse(filename).getroot())

def dicttoxmlfile(element, filename):
    ElementTree.ElementTree(dicttoxml(element)).write(filename)

def xmlstringtodict(xmlstring):
    return xmltodict(ElementTree.fromstring(xmlstring).getroot())

def dicttoxmlstring(element):
    return ElementTree.tostring(dicttoxml(element))

Current time formatting with Javascript

function startTime() {
    var today = new Date(),
        h = checkTime(((today.getHours() + 11) % 12 + 1)),
        m = checkTime(today.getMinutes()),
        s = checkTime(today.getSeconds());
    document.getElementById('demo').innerHTML = h + ":" + m + ":" + s;
    t = setTimeout(function () {
        startTime()
    }, 500);
}
startTime();

})();

05:12:00

Get string after character

For the text after the first = and before the next =

cut -d "=" -f2 <<< "$your_str"

or

sed -e 's#.*=\(\)#\1#' <<< "$your_str"

For all text after the first = regardless of if there are multiple =

cut -d "=" -f2- <<< "$your_str"

How to align entire html body to the center?

<style>
        body{
            max-width: 1180px;
            width: 98%;
            margin: 0px auto;
            text-align: left;
        }
</style>

Just apply this style before applying any CSS. You can change width as per your need.

How to parse string into date?

Assuming that the database is MS SQL Server 2012 or greater, here's a solution that works. The basic statement contains the in-line try-parse:

SELECT TRY_PARSE('02/04/2016 10:52:00' AS datetime USING 'en-US') AS Result;

Here's what we implemented in the production version:

UPDATE dbo.StagingInputReview
 SET ReviewedOn = 
     ISNULL(TRY_PARSE(RTrim(LTrim(ReviewedOnText)) AS datetime USING 'en-US'), getdate()),
 ModifiedOn = (getdate()), ModifiedBy = (suser_sname())
 -- Check for empty/null/'NULL' text
 WHERE not ReviewedOnText is null 
   AND RTrim(LTrim(ReviewedOnText))<>''
   AND Replace(RTrim(LTrim(ReviewedOnText)),'''','') <> 'NULL';

The ModifiedOn and ModifiedBy columns are just for internal database tracking purposes.

See also these Microsoft MSDN references:

Apache shows PHP code instead of executing it

Posting what worked for me in case in helps someone down the road, though it is an unusual case.

I had set a handler to force my web host to use a higher version of php than their default. There's was 5.1, but I wanted 5.6 so I had this:

<FilesMatch \.php$>
    SetHandler php56-cgi
</FilesMatch>

in my .htaccess file.

When trying to run my site locally, having that in there caused php code to be output to the browser. Removing it solved the problem.

Python, Unicode, and the Windows console

Just enter this code in command line before executing python script:

chcp 65001 & set PYTHONIOENCODING=utf-8

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

Generally if something works on various computers but fails on only one computer, then there's something wrong with that computer. Here are a few things to check:
(1) Are you running the same stuff on that computer -- OS including patches, etc.
(2) Does the computer report problems? Where to look depends on the OS, but it looks like you're using linux, so check syslog
(3) Run hardware diagnostics, e.g. the ones recommended here. Start with memory and disk checks in particular.

If you can't turn up any issues, then search for a similar issue in the bug parade for whichever VM you're using. Unfortunately if you're already on the latest version of the VM, then you won't necessarily find a fix.

Finally, one more option is simply to try another VM -- e.g. OpenJDK or JRockit, instead of Oracle's standard.

List<String> to ArrayList<String> conversion issue

In Kotlin List can be converted into ArrayList through passing it as a constructor parameter.

ArrayList(list)

Convert HH:MM:SS string to seconds only in javascript

Convert hh:mm:ss string to seconds in one line. Also allowed h:m:s format and mm:ss, m:s etc

'08:45:20'.split(':').reverse().reduce((prev, curr, i) => prev + curr*Math.pow(60, i), 0)

Accessing items in an collections.OrderedDict by index

If you have pandas installed, you can convert the ordered dict to a pandas Series. This will allow random access to the dictionary elements.

>>> import collections
>>> import pandas as pd
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'

>>> s = pd.Series(d)

>>> s['bar']
spam
>>> s.iloc[1]
spam
>>> s.index[1]
bar

How to view DB2 Table structure

Also the following command works:

describe SELECT * FROM table_name;

Where the select statement can be replaced with any other select statement, which is quite useful for complex inserts with select for example.

How to allow download of .json file with ASP.NET

Solution is you need to add json file extension type in MIME Types

Method 1

Go to IIS, Select your application and Find MIME Types

enter image description here

Click on Add from Right panel

File Name Extension = .json

MIME Type = application/json

enter image description here

After adding .json file type in MIME Types, Restart IIS and try to access json file


Method 2

Go to web.config of that application and add this lines in it

 <system.webServer>
   <staticContent>
     <mimeMap fileExtension=".json" mimeType="application/json" />
   </staticContent>
 </system.webServer>

Replacing Spaces with Underscores

Use str_replace:

str_replace(" ","_","Alex Newton");

How can I rollback an UPDATE query in SQL server 2005?

You can use implicit transactions for this

SET IMPLICIT_TRANSACTIONS ON

update Staff set staff_Name='jas' where staff_id=7

ROLLBACK

As you request-- You can SET this setting ( SET IMPLICIT_TRANSACTIONS ON) from a stored procedure by setting that stored procedure as the start up procedure.

But SET IMPLICIT TRANSACTION ON command is connection specific. So any connection other than the one which running the start up stored procedure will not benefit from the setting you set.

How to get the first element of an array?

Only in case you are using underscore.js (http://underscorejs.org/) you can do:

_.first(your_array);

CSS animation delay in repeating

I had a similar problem and used

@-webkit-keyframes pan {
   0%, 10%       { -webkit-transform: translate3d( 0%, 0px, 0px); }
   90%, 100%     { -webkit-transform: translate3d(-50%, 0px, 0px); }
}

Bit irritating that you have to fake your duration to account for 'delays' at either end.

What are the differences between char literals '\n' and '\r' in Java?

\n is for unix
\r is for mac (before OS X)
\r\n is for windows format

you can also take System.getProperty("line.separator")

it will give you the appropriate to your OS

How to make spring inject value into a static field

I've had a similar requirement: I needed to inject a Spring-managed repository bean into my Person entity class ("entity" as in "something with an identity", for example an JPA entity). A Person instance has friends, and for this Person instance to return its friends, it shall delegate to its repository and query for friends there.

@Entity
public class Person {
    private static PersonRepository personRepository;

    @Id
    @GeneratedValue
    private long id;

    public static void setPersonRepository(PersonRepository personRepository){
        this.personRepository = personRepository;
    }

    public Set<Person> getFriends(){
        return personRepository.getFriends(id);
    }

    ...
}

.

@Repository
public class PersonRepository {

    public Person get Person(long id) {
        // do database-related stuff
    }

    public Set<Person> getFriends(long id) {
        // do database-related stuff
    }

    ...
}

So how did I inject that PersonRepository singleton into the static field of the Person class?

I created a @Configuration, which gets picked up at Spring ApplicationContext construction time. This @Configuration gets injected with all those beans that I need to inject as static fields into other classes. Then with a @PostConstruct annotation, I catch a hook to do all static field injection logic.

@Configuration
public class StaticFieldInjectionConfiguration {

    @Inject
    private PersonRepository personRepository;

    @PostConstruct
    private void init() {
        Person.setPersonRepository(personRepository);
    }
}

How to remove an app with active device admin enabled on Android?

Enter vault password and inside vault right top corner options icon is there. Press on it. In that ->settings->vault admin rites to be unselected. Work done. U can uninstall app now.

Change window location Jquery

If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin

Use document.location.href to change the page location, place it in the function on a successful ajax run.

How do you display JavaScript datetime in 12 hour AM/PM format?

It will return the following format like

09:56 AM

appending zero in start for the hours as well if it is less than 10

Here it is using ES6 syntax

_x000D_
_x000D_
const getTimeAMPMFormat = (date) => {
  let hours = date.getHours();
  let minutes = date.getMinutes();
  const ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  hours = hours < 10 ? '0' + hours : hours;
  // appending zero in the start if hours less than 10
  minutes = minutes < 10 ? '0' + minutes : minutes;
  return hours + ':' + minutes + ' ' + ampm;
};
console.log(getTimeAMPMFormat(new Date)); // 09:59 AM
_x000D_
_x000D_
_x000D_

How do you run `apt-get` in a dockerfile behind a proxy?

As Tim Potter pointed out, setting proxy in dockerfile is horrible. When building the image, you add proxy for your corporate network but you may be deploying in cloud or a DMZ where there is no need for proxy or the proxy server is different.

Also, you cannot share your image with others outside your corporate n/w.

What is the difference between Integer and int in Java?

An Integer is pretty much just a wrapper for the primitive type int. It allows you to use all the functions of the Integer class to make life a bit easier for you.

If you're new to Java, something you should learn to appreciate is the Java documentation. For example, anything you want to know about the Integer Class is documented in detail.

This is straight out of the documentation for the Integer class:

The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.

How to get an element by its href in jquery?

Yes, you can use jQuery's attribute selector for that.

var linksToGoogle = $('a[href="http://google.com"]');

Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:

var allLinksToGoogle = $('a[href^="http://google.com"]');

How to get UTC+0 date in Java 8?

In java8, I would use the Instant class which is already in UTC and is convenient to work with.

import java.time.Instant;

Instant ins = Instant.now();
long ts = ins.toEpochMilli();

Instant ins2 = Instant.ofEpochMilli(ts)

Alternatively, you can use the following:

import java.time.*;

Instant ins = Instant.now(); 

OffsetDateTime odt = ins.atOffset(ZoneOffset.UTC);
ZonedDateTime zdt = ins.atZone(ZoneId.of("UTC"));

Back to Instant

Instant ins4 = Instant.from(odt);

How to set DateTime to null

You can write DateTime? newdate = null;

In where shall I use isset() and !empty()

isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.

So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:

$var = "";
var_dump(isset($var));

The type comparison tables in PHP’s manual is quite handy for such questions.

isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)

How to change a string into uppercase

for making uppercase from lowercase to upper just use

"string".upper()

where "string" is your string that you want to convert uppercase

for this question concern it will like this:

s.upper()

for making lowercase from uppercase string just use

"string".lower()

where "string" is your string that you want to convert lowercase

for this question concern it will like this:

s.lower()

If you want to make your whole string variable use

s="sadf"
# sadf

s=s.upper()
# SADF

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

You can also upgrade Mehrdad Afshari's solution by rewriting the extention method to faster (and better looking) one:

static class EnumerableExtensions
{
    public static T MaxElement<T, R>(this IEnumerable<T> container, Func<T, R> valuingFoo) where R : IComparable
    {
        var enumerator = container.GetEnumerator();
        if (!enumerator.MoveNext())
            throw new ArgumentException("Container is empty!");

        var maxElem = enumerator.Current;
        var maxVal = valuingFoo(maxElem);

        while (enumerator.MoveNext())
        {
            var currVal = valuingFoo(enumerator.Current);

            if (currVal.CompareTo(maxVal) > 0)
            {
                maxVal = currVal;
                maxElem = enumerator.Current;
            }
        }

        return maxElem;
    }
}

And then just use it:

var maxObject = list.MaxElement(item => item.Height);

That name will be clear to people using C++ (because there is std::max_element in there).

Truncating Text in PHP?

The obvious thing to do is read the documentation.

But to help: substr($str, $start, $end);

$str is your text

$start is the character index to begin at. In your case, it is likely 0 which means the very beginning.

$end is where to truncate at. Suppose you wanted to end at 15 characters, for example. You would write it like this:

<?php

$text = "long text that should be truncated";
echo substr($text, 0, 15);

?>

and you would get this:

long text that 

makes sense?

EDIT

The link you gave is a function to find the last white space after chopping text to a desired length so you don't cut off in the middle of a word. However, it is missing one important thing - the desired length to be passed to the function instead of always assuming you want it to be 25 characters. So here's the updated version:

function truncate($text, $chars = 25) {
    if (strlen($text) <= $chars) {
        return $text;
    }
    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

So in your case you would paste this function into the functions.php file and call it like this in your page:

$post = the_post();
echo truncate($post, 100);

This will chop your post down to the last occurrence of a white space before or equal to 100 characters. Obviously you can pass any number instead of 100. Whatever you need.

How do I compute the intersection point of two lines?

Unlike other suggestions, this is short and doesn't use external libraries like numpy. (Not that using other libraries is bad...it's nice not need to, especially for such a simple problem.)

def line_intersection(line1, line2):
    xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
    ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])

    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]

    div = det(xdiff, ydiff)
    if div == 0:
       raise Exception('lines do not intersect')

    d = (det(*line1), det(*line2))
    x = det(d, xdiff) / div
    y = det(d, ydiff) / div
    return x, y

print line_intersection((A, B), (C, D))

And FYI, I would use tuples instead of lists for your points. E.g.

A = (X, Y)

EDIT: Initially there was a typo. That was fixed Sept 2014 thanks to @zidik.

This is simply the Python transliteration of the following formula, where the lines are (a1, a2) and (b1, b2) and the intersection is p. (If the denominator is zero, the lines have no unique intersection.)

VarBinary vs Image SQL Server Data Type to Store Binary Data?

Since image is deprecated, you should use varbinary.

per Microsoft (thanks for the link @Christopher)

ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.

counting number of directories in a specific directory

Get a count of only the directories in the current directory

echo */ | wc

you will get out put like 1 309 4594

2nd digit represents no. of directories.

or

tree -L 1 | tail -1

How do I remove a single breakpoint with GDB?

You can delete all breakpoints using

del <start_breakpoint_num> - <end_breakpoint_num>

To view the start_breakpoint_num and end_breakpoint_num use:

info break

Convert Text to Date?

Perhaps:

Sub dateCNV()
    Dim N As Long, r As Range, s As String
    N = Cells(Rows.Count, "A").End(xlUp).Row
    For i = 1 To N
        Set r = Cells(i, "A")
        s = r.Text
        r.Clear
        r.Value = DateSerial(Left(s, 4), Mid(s, 6, 2), Right(s, 2))
    Next i
End Sub

This assumes that column A contains text values like 2013-12-25 with no header cell.

How can I exclude multiple folders using Get-ChildItem -exclude?

The simplest short form to me is something like:

#find web forms in my project except in compilation directories
(gci -recurse -path *.aspx,*.ascx).fullname -inotmatch '\\obj\\|\\bin\\'

And if you need more complex logic then use a filter:

  filter Filter-DirectoryBySomeLogic{
  
      param(
      [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
      $fsObject,
      [switch]$exclude
      )
          
      if($fsObject -is [System.IO.DirectoryInfo])
      {
          $additional_logic = $true ### replace additional logic here
  
          if($additional_logic){
              if(!$exclude){ return $fsObject }
          }
          elseif($exclude){ return $fsObject }
      }
          
  }
  
  gci -Directory -Recurse | Filter-DirectoryBySomeLogic | ....

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

If the array element is not integer you can use something like below :

$skus  = array('LDRES10','LDRES12','LDRES11');   //sample data

if(!empty($skus)){     
    $sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "      
}

How to make custom error pages work in ASP.NET MVC 4

Here is my solution. Use [ExportModelStateToTempData] / [ImportModelStateFromTempData] is uncomfortable in my opinion.

~/Views/Home/Error.cshtml:

@{
    ViewBag.Title = "Error";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Error</h2>
<hr/>

<div style="min-height: 400px;">

    @Html.ValidationMessage("Error")

    <br />
    <br />

    <button onclick="Error_goBack()" class="k-button">Go Back</button>
    <script>
        function Error_goBack() {
            window.history.back()
        }
    </script>

</div>

~/Controllers/HomeController.sc:

public class HomeController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Error()
    {
        return this.View();
    }

    ...
}

~/Controllers/BaseController.sc:

public class BaseController : Controller
{
    public BaseController() { }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            if (filterContext.Controller.TempData.ContainsKey("Error"))
            {
                var modelState = filterContext.Controller.TempData["Error"] as ModelState;
                filterContext.Controller.ViewData.ModelState.Merge(new ModelStateDictionary() { new KeyValuePair<string, ModelState>("Error", modelState) });
                filterContext.Controller.TempData.Remove("Error");
            }
        }
        if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
        {
            if (filterContext.Controller.ViewData.ModelState.ContainsKey("Error"))
            {
                filterContext.Controller.TempData["Error"] = filterContext.Controller.ViewData.ModelState["Error"];
            }
        }

        base.OnActionExecuted(filterContext);
    }
}

~/Controllers/MyController.sc:

public class MyController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Details(int id)
    {
        if (id != 5)
        {
            ModelState.AddModelError("Error", "Specified row does not exist.");
            return RedirectToAction("Error", "Home");
        }
        else
        {
            return View("Specified row exists.");
        }
    }
}

I wish you successful projects ;-)

Shell script not running, command not found

Change the first line to the following as pointed out by Marc B

#!/bin/bash 

Then mark the script as executable and execute it from the command line

chmod +x MigrateNshell.sh
./MigrateNshell.sh

or simply execute bash from the command line passing in your script as a parameter

/bin/bash MigrateNshell.sh

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

Borrowing @jgauffin answer as an HtmlHelper extension:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString RenderPartialViewToString(
        this HtmlHelper html, 
        ControllerContext controllerContext, 
        ViewDataDictionary viewData,
        TempDataDictionary tempData,
        string viewName, 
        object model)
    {
        viewData.Model = model;
        string result = String.Empty;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
            ViewContext viewContext = new ViewContext(controllerContext, viewResult.View, viewData, tempData, sw);
            viewResult.View.Render(viewContext, sw);

            result = sw.GetStringBuilder().ToString();
        }

        return MvcHtmlString.Create(result);
    }
}

Usage in a razor view:

Html.RenderPartialViewToString(ViewContext, ViewData, TempData, "Search", Model)

Setting width as a percentage using jQuery

Here is an alternative that worked for me:

$('div#somediv').css({'width': '70%'});

How to force the browser to reload cached CSS and JavaScript files

For ASP.NET I propose the following solution with advanced options (debug/release mode, versions):

Include JavaScript or CSS files this way:

<script type="text/javascript" src="Scripts/exampleScript<%=Global.JsPostfix%>" />
<link rel="stylesheet" type="text/css" href="Css/exampleCss<%=Global.CssPostfix%>" />

Global.JsPostfix and Global.CssPostfix are calculated by the following way in Global.asax:

protected void Application_Start(object sender, EventArgs e)
{
    ...
    string jsVersion = ConfigurationManager.AppSettings["JsVersion"];
    bool updateEveryAppStart = Convert.ToBoolean(ConfigurationManager.AppSettings["UpdateJsEveryAppStart"]);
    int buildNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Revision;
    JsPostfix = "";
#if !DEBUG
    JsPostfix += ".min";
#endif
    JsPostfix += ".js?" + jsVersion + "_" + buildNumber;
    if (updateEveryAppStart)
    {
        Random rand = new Random();
        JsPosfix += "_" + rand.Next();
    }
    ...
}

Comparing two input values in a form validation with AngularJS

Thanks for the great example @Jacek Ciolek. For angular 1.3.x this solution breaks when updates are made to the reference input value. Building on this example for angular 1.3.x, this solution works just as well with Angular 1.3.x. It binds and watches for changes to the reference value.

angular.module('app', []).directive('sameAs', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      sameAs: '='
    },
    link: function(scope, elm, attr, ngModel) {
      if (!ngModel) return;

      attr.$observe('ngModel', function(value) {
        // observes changes to this ngModel
        ngModel.$validate();
      });

      scope.$watch('sameAs', function(sameAs) {
        // watches for changes from sameAs binding
        ngModel.$validate();
      });

      ngModel.$validators.sameAs = function(value) {
        return scope.sameAs == value;
      };
    }
  };
});

Here is my pen: http://codepen.io/kvangrae/pen/BjxMWR

Execute combine multiple Linux commands in one line

cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install

I would like to see a hash_map example in C++

The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":

#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;

int main() {
    unordered_map <string, int> m;
    m["foo"] = 42;
    cout << m["foo"] << endl;
}

In order to get this compile, you need to tell g++ that you are using C++0x:

g++ -std=c++0x main.cpp

These maps work pretty much as std::map does, except that instead of providing a custom operator<() for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

How do I install Keras and Theano in Anaconda Python on Windows?

The trick is that you need to create an environment/workspace for Python. This solution should work for Python 2.7 but at the time of writing keras can run on python 3.5, especially if you have the latest anaconda installed (this took me awhile to figure out so I'll outline the steps I took to install KERAS in python 3.5):

Create environment/workspace for Python 3.5

  1. C:\conda create --name neuralnets python=3.5
  2. C:\activate neuralnets

Install everything (notice the neuralnets workspace in parenthesis on each line). Accept any dependencies each of those steps wants to install:

  1. (neuralnets) C:\conda install theano
  2. (neuralnets) C:\conda install mingw libpython
  3. (neuralnets) C:\pip install tensorflow
  4. (neuralnets) C:\pip install keras

Test it out:

(neuralnets) C:\python -c "from keras import backend; print(backend._BACKEND)"

Just remember, if you want to work in the workspace you always have to do:

C:\activate neuralnets

so you can launch Jupyter for example (assuming you also have Jupyter installed in this environment/workspace) as:

C:\activate neuralnets
(neuralnets) jupyter notebook

You can read more about managing and creating conda environments/workspaces at the follwing URL: https://conda.io/docs/using/envs.html

Array to String PHP?

One of the Best way:

echo print_r($array, true);

Quickly reading very large tables as dataframes

A minor additional points worth mentioning. If you have a very large file you can on the fly calculate the number of rows (if no header) using (where bedGraph is the name of your file in your working directory):

>numRow=as.integer(system(paste("wc -l", bedGraph, "| sed 's/[^0-9.]*\\([0-9.]*\\).*/\\1/'"), intern=T))

You can then use that either in read.csv , read.table ...

>system.time((BG=read.table(bedGraph, nrows=numRow, col.names=c('chr', 'start', 'end', 'score'),colClasses=c('character', rep('integer',3)))))
   user  system elapsed 
 25.877   0.887  26.752 
>object.size(BG)
203949432 bytes

How to enter a series of numbers automatically in Excel

I find it easier using this formula

=IF(B2<>"",TEXT(ROW(A1),"IR-0000"),"")

Need to paste this formula at A2, that means when you are encoding data at B cell the A cell will automatically input the serial code and when there's no data the cell will stay blank....you can change the "IR" to any first letter code you want to be placed in your row.

Hope it helps

MySQL SELECT last few days?

You can use this in your MySQL WHERE clause to return records that were created within the last 7 days/week:

created >= DATE_SUB(CURDATE(),INTERVAL 7 day)

Also use NOW() in the subtraction to give hh:mm:ss resolution. So to return records created exactly (to the second) within the last 24hrs, you could do:

created >= DATE_SUB(NOW(),INTERVAL 1 day)

How can I initialize C++ object member variables in the constructor?

This question is a bit old, but here's another way in C++11 of "doing more work" in the constructor before initialising your member variables:

BigMommaClass::BigMommaClass(int numba1, int numba2)
    : thingOne([](int n1, int n2){return n1+n2;}(numba1,numba2)),
      thingTwo(numba1, numba2) {}

The lambda function above will be invoked and the result passed to thingOnes constructor. You can of course make the lambda as complex as you like.

How to get a thread and heap dump of a Java process on Windows that's not running in a console

You have to redirect output from second java executable to some file. Then, use SendSignal to send "-3" to your second process.

When to use static classes in C#

For C# 3.0, extension methods may only exist in top-level static classes.

Set UILabel line spacing

I've found 3rd Party Libraries Like this one:

https://github.com/Tuszy/MTLabel

To be the easiest solution.

Best way to get hostname with php

What about gethostname()?

Edit: This might not be an option I suppose, depending on your environment. It's new in PHP 5.3. php_uname('n') might work as an alternative.

Scanner only reads first word instead of line

input.next() takes in the first whitsepace-delimited word of the input string. So by design it does what you've described. Try input.nextLine().

Export a list into a CSV or TXT file in R

using sink function :

sink("output.txt")
print(mylist)
sink()

JQuery .each() backwards

$($("li").get().reverse()).each(function() { /* ... */ });

How to override trait function and call it from the overridden function?

An alternative approach if interested - with an extra intermediate class to use the normal OOO way. This simplifies the usage with parent::methodname

trait A {
    function calc($v) {
        return $v+1;
    }
}

// an intermediate class that just uses the trait
class IntClass {
    use A;
}

// an extended class from IntClass
class MyClass extends IntClass {
    function calc($v) {
        $v++;
        return parent::calc($v);
    }
}

How do I pass JavaScript variables to PHP?

We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        FB.api('/me?fields=id,first_name,last_name,email', function (result) {
            document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
            console.log(document.cookie);
        });
    }
}

And I've accessed it (in any file) using -

<?php 
    if(isset($_COOKIE['fbdata'])) { 
        echo "welcome ".$_COOKIE['fbdata'];
    }
?>

What is the difference between POST and GET?

GET and POST are two different types of HTTP requests.

According to Wikipedia:

GET requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.

and

POST submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.

So essentially GET is used to retrieve remote data, and POST is used to insert/update remote data.


HTTP/1.1 specification (RFC 2616) section 9 Method Definitions contains more information on GET and POST as well as the other HTTP methods, if you are interested.

In addition to explaining the intended uses of each method, the spec also provides at least one practical reason for why GET should only be used to retrieve data:

Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead


Finally, an important consideration when using GET for AJAX requests is that some browsers - IE in particular - will cache the results of a GET request. So if you, for example, poll using the same GET request you will always get back the same results, even if the data you are querying is being updated server-side. One way to alleviate this problem is to make the URL unique for each request by appending a timestamp.

Css Move element from left to right animated

Try this

_x000D_
_x000D_
div_x000D_
{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:red;_x000D_
  transition: all 1s ease-in-out;_x000D_
  -webkit-transition: all 1s ease-in-out;_x000D_
  -moz-transition: all 1s ease-in-out;_x000D_
  -o-transition: all 1s ease-in-out;_x000D_
  -ms-transition: all 1s ease-in-out;_x000D_
  position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
  transform: translate(3em,0);_x000D_
  -webkit-transform: translate(3em,0);_x000D_
  -moz-transform: translate(3em,0);_x000D_
  -o-transform: translate(3em,0);_x000D_
  -ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

DEMO

Is there a date format to display the day of the week in java?

I know the question is about getting the day of week as string (e.g. the short name), but for anybody who is looking for the numeric day of week (as I was), you can use the new "u" format string, supported since Java 7. For example:

new SimpleDateFormat("u").format(new Date());

returns today's day-of-week index, namely: 1 = Monday, 2 = Tuesday, ..., 7 = Sunday.

Where can I download the jar for org.apache.http package?

You can add org.apache.http by using below code in app:Build gradle

dependencies {
    compile 'org.apache.httpcomponents:httpclient:4.5'
}

Best way to format integer as string with leading zeros?

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'

Putting images with options in a dropdown list

Checkout And Run The Following Code. It will help you...

_x000D_
_x000D_
 $( function() {_x000D_
    $.widget( "custom.iconselectmenu", $.ui.selectmenu, {_x000D_
      _renderItem: function( ul, item ) {_x000D_
        var li = $( "<li>" ),_x000D_
          wrapper = $( "<div>", { text: item.label } );_x000D_
 _x000D_
        if ( item.disabled ) {_x000D_
          li.addClass( "ui-state-disabled" );_x000D_
        }_x000D_
 _x000D_
        $( "<span>", {_x000D_
          style: item.element.attr( "data-style" ),_x000D_
          "class": "ui-icon " + item.element.attr( "data-class" )_x000D_
        })_x000D_
          .appendTo( wrapper );_x000D_
 _x000D_
        return li.append( wrapper ).appendTo( ul );_x000D_
      }_x000D_
    });_x000D_
 _x000D_
    $( "#filesA" )_x000D_
      .iconselectmenu()_x000D_
      .iconselectmenu( "menuWidget" )_x000D_
        .addClass( "ui-menu-icons" );_x000D_
 _x000D_
    $( "#filesB" )_x000D_
      .iconselectmenu()_x000D_
      .iconselectmenu( "menuWidget" )_x000D_
        .addClass( "ui-menu-icons customicons" );_x000D_
 _x000D_
    $( "#people" )_x000D_
      .iconselectmenu()_x000D_
      .iconselectmenu( "menuWidget")_x000D_
        .addClass( "ui-menu-icons avatar" );_x000D_
  } );_x000D_
  </script>_x000D_
  <style>_x000D_
    h2 {_x000D_
      margin: 30px 0 0 0;_x000D_
    }_x000D_
    fieldset {_x000D_
      border: 0;_x000D_
    }_x000D_
    label
_x000D_
{_x000D_
      display: block;_x000D_
    }_x000D_
 _x000D_
    /* select with custom icons */_x000D_
    .ui-selectmenu-menu .ui-menu.customicons .ui-menu-item-wrapper {_x000D_
      padding: 0.5em 0 0.5em 3em;_x000D_
    }_x000D_
    .ui-selectmenu-menu .ui-menu.customicons .ui-menu-item .ui-icon {_x000D_
      height: 24px;_x000D_
      width: 24px;_x000D_
      top: 0.1em;_x000D_
    }_x000D_
    .ui-icon.video {_x000D_
      background: url("images/24-video-square.png") 0 0 no-repeat;_x000D_
    }_x000D_
    .ui-icon.podcast {_x000D_
      background: url("images/24-podcast-square.png") 0 0 no-repeat;_x000D_
    }_x000D_
    .ui-icon.rss {_x000D_
      background: url("images/24-rss-square.png") 0 0 no-repeat;_x000D_
    }_x000D_
 _x000D_
    /* select with CSS avatar icons */_x000D_
    option.avatar {_x000D_
      background-repeat: no-repeat !important;_x000D_
      padding-left: 20px;_x000D_
    }_x000D_
    .avatar .ui-icon {_x000D_
      background-position: left top;_x000D_
    }
_x000D_
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <title>jQuery UI Selectmenu - Custom Rendering</title>_x000D_
  _x000D_
</head>_x000D_
<body>_x000D_
 _x000D_
<div class="demo">_x000D_
 _x000D_
<form action="#">_x000D_
  <h2>Selectmenu with framework icons</h2>_x000D_
  <fieldset>_x000D_
    <label for="filesA">Select a File:</label>_x000D_
    <select name="filesA" id="filesA">_x000D_
      <option value="jquery" data-class="ui-icon-script">jQuery.js</option>_x000D_
      <option value="jquerylogo" data-class="ui-icon-image">jQuery Logo</option>_x000D_
      <option value="jqueryui" data-class="ui-icon-script">ui.jQuery.js</option>_x000D_
      <option value="jqueryuilogo" selected="selected" data-class="ui-icon-image">jQuery UI Logo</option>_x000D_
      <option value="somefile" disabled="disabled" data-class="ui-icon-help">Some unknown file</option>_x000D_
    </select>_x000D_
  </fieldset>_x000D_
 _x000D_
  <h2>Selectmenu with custom icon images</h2>_x000D_
  <fieldset>_x000D_
    <label for="filesB">Select a podcast:</label>_x000D_
    <select name="filesB" id="filesB">_x000D_
      <option value="mypodcast" data-class="podcast">John Resig Podcast</option>_x000D_
      <option value="myvideo" data-class="video">Scott González Video</option>_x000D_
      <option value="myrss" data-class="rss">jQuery RSS XML</option>_x000D_
    </select>_x000D_
  </fieldset>_x000D_
 _x000D_
  <h2>Selectmenu with custom avatar 16x16 images as CSS background</h2>_x000D_
  <fieldset>_x000D_
    <label for="people">Select a Person:</label>_x000D_
    <select name="people" id="people">_x000D_
      <option value="1" data-class="avatar" data-style="background-image: url(&apos;http://www.gravatar.com/avatar/b3e04a46e85ad3e165d66f5d927eb609?d=monsterid&amp;r=g&amp;s=16&apos;);">John Resig</option>_x000D_
      <option value="2" data-class="avatar" data-style="background-image: url(&apos;http://www.gravatar.com/avatar/e42b1e5c7cfd2be0933e696e292a4d5f?d=monsterid&amp;r=g&amp;s=16&apos;);">Tauren Mills</option>_x000D_
      <option value="3" data-class="avatar" data-style="background-image: url(&apos;http://www.gravatar.com/avatar/bdeaec11dd663f26fa58ced0eb7facc8?d=monsterid&amp;r=g&amp;s=16&apos;);">Jane Doe</option>_x000D_
    </select>_x000D_
  </fieldset>_x000D_
</form>_x000D_
 _x000D_
</div>_x000D_
 _x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Java: Static Class?

Private constructor and static methods on a class marked as final.

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

That's a tricky one... Your storage letter must be capical. For example "C:\..."

Add column to SQL Server

Use this query:

ALTER TABLE tablename ADD columname DATATYPE(size);

And here is an example:

ALTER TABLE Customer ADD LastName VARCHAR(50);

Send message to specific client with socket.io and node.js

The simplest, most elegant way

verified working with socket.io v3.1.1

It's as easy as:

client.emit("your message");

And that's it. Ok, but how does it work?

Minimal working example

Here's an example of a simple client-server interaction where each client regularly receives a message containing a sequence number. There is a unique sequence for each client and that's where the "I need to send a message to a particular client" comes into play.

Server

server.js

const
    {Server} = require("socket.io"),
    server = new Server(8000);

let
    sequenceNumberByClient = new Map();

// event fired every time a new client connects:
server.on("connection", (socket) => {
    console.info(`Client connected [id=${socket.id}]`);
    // initialize this client's sequence number
    sequenceNumberByClient.set(socket, 1);

    // when socket disconnects, remove it from the list:
    socket.on("disconnect", () => {
        sequenceNumberByClient.delete(socket);
        console.info(`Client gone [id=${socket.id}]`);
    });
});

// sends each client its current sequence number
setInterval(() => {
    for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) {
        client.emit("seq-num", sequenceNumber);
        sequenceNumberByClient.set(client, sequenceNumber + 1);
    }
}, 1000);

The server starts listening on port 8000 for incoming connections. As soon as a new connection is established, that client is added to a map that keeps track of its sequence number. The server also listens for the disconnect event to remove the client from the map when it leaves.

Each and every second, a timer is fired. When it does, the server walks through the map and sends a message to every client with their current sequence number, incrementing it right after. That's all that is to it. Easy peasy.

Client

The client part is even simpler. It just connects to the server and listens for the seq-num message, printing it to the console every time it arrives.

client.js

const
    io = require("socket.io-client"),
    ioClient = io.connect("http://localhost:8000");

ioClient.on("seq-num", (msg) => console.info(msg));

Running the example

Install the required libraries:

npm install [email protected] [email protected]

Run the server:

node server

Open other terminal windows and spawn as many clients as you want by running:

node client

I have also prepared a gist with the full code here.

How to Lock the data in a cell in excel using vba

You can also do it on the worksheet level captured in the worksheet's change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect...

Private Sub Worksheet_Change(ByVal Target As Range)

    'set your criteria here
    If Target.Column = 1 Then

        'must disable events if you change the sheet as it will
        'continually trigger the change event
        Application.EnableEvents = False
        Application.Undo
        Application.EnableEvents = True

        MsgBox "You cannot do that!"
    End If
End Sub

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

ByRef argument type mismatch in Excel VBA

I suspect you haven't set up last_name properly in the caller.

With the statement Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name)

this will only work if last_name is a string, i.e.

Dim last_name as String

appears in the caller somewhere.

The reason for this is that VBA passes in variables by reference by default which means that the data types have to match exactly between caller and callee.

Two fixes:

1) Force ByVal -- Change your function to pass variable ByVal:
Public Function ProcessString(ByVal input_string As String) As String, or

2) Dim varname -- put Dim last_name As String in the caller before you use it.

(1) works because for ByVal, a copy of input_string is taken when passing to the function which will coerce it into the correct data type. It also leads to better program stability since the function cannot modify the variable in the caller.

Assign format of DateTime with data annotations?

After Commenting

          // [DataType(DataType.DateTime)] 

Use the Data Annotation Attribute:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]

STEP-7 of the following link may help you...

http://ilyasmamunbd.blogspot.com/2014/12/jquery-datepicker-in-aspnet-mvc-5.html

Adding a new entry to the PATH variable in ZSH

You can append to your PATH in a minimal fashion. No need for parentheses unless you're appending more than one element. It also usually doesn't need quotes. So the simple, short way to append is:

path+=/some/new/bin/dir

This lower-case syntax is using path as an array, yet also affects its upper-case partner equivalent, PATH (to which it is "bound" via typeset).

(Notice that no : is needed/wanted as a separator.)

Common interactive usage

Then the common pattern for testing a new script/executable becomes:

path+=$PWD/.
# or
path+=$PWD/bin

Common config usage

You can sprinkle path settings around your .zshrc (as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)).

Related tidbits

Treating path this way (as an array) also means: no need to do a rehash to get the newly pathed commands to be found.

Also take a look at vared path as a dynamic way to edit path (and other things).

You may only be interested in path for this question, but since we're talking about exports and arrays, note that arrays generally cannot be exported.

You can even prevent PATH from taking on duplicate entries (refer to this and this):

typeset -U path

how do I strip white space when grabbing text with jQuery?

Use the replace function in js:

var emailAdd = $(this).text().replace(/ /g,'');

That will remove all the spaces

If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :

var emailAdd = $.trim($(this).text());

Python dict how to create key or append an element to key?

dictionary['key'] = dictionary.get('key', []) + list_to_append

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

You can do it without writing any code at all :) You just need to set the default value for the column in the database. You can do this in your migrations. For example:

create_table :projects do |t|
  t.string :status, :null => false, :default => 'P'
  ...
  t.timestamps
end

Hope that helps.

Read and parse a Json File in C#

For any of the JSON parse, use the website http://json2csharp.com/ (easiest way) to convert your JSON into C# class to deserialize your JSON into C# object.

 public class JSONClass
 {
        public string name { get; set; }
        public string url { get; set; }
        public bool visibility { get; set; }
        public string idField { get; set; }
        public bool defaultEvents { get; set; }
        public string type { get; set; }        
 }

Then use the JavaScriptSerializer (from System.Web.Script.Serialization), in case you don't want any third party DLL like newtonsoft.

using (StreamReader r = new StreamReader("jsonfile.json"))
{
   string json = r.ReadToEnd();
   JavaScriptSerializer jss = new JavaScriptSerializer();
   var Items = jss.Deserialize<JSONClass>(json);
}

Then you can get your object with Items.name or Items.Url etc.

How to Detect Browser Window /Tab Close Event?

You can also do like below.

put below script code in header tag

<script type="text/javascript" language="text/javascript"> 
function handleBrowserCloseButton(event) { 
   if (($(window).width() - window.event.clientX) < 35 && window.event.clientY < 0) 
    {
      //Call method by Ajax call
      alert('Browser close button clicked');    
    } 
} 
</script>

call above function from body tag like below

<body onbeforeunload="handleBrowserCloseButton(event);">

Thank you

JQuery get data from JSON array

You're not looping over the items. Try this instead:

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

Monad in plain English? (For the OOP programmer with no FP background)

To respect fast readers, I start with precise definition first, continue with quick more "plain English" explanation, and then move to examples.

Here is a both concise and precise definition slightly reworded:

A monad (in computer science) is formally a map that:

  • sends every type X of some given programming language to a new type T(X) (called the "type of T-computations with values in X");

  • equipped with a rule for composing two functions of the form f:X->T(Y) and g:Y->T(Z) to a function g°f:X->T(Z);

  • in a way that is associative in the evident sense and unital with respect to a given unit function called pure_X:X->T(X), to be thought of as taking a value to the pure computation that simply returns that value.

So in simple words, a monad is a rule to pass from any type X to another type T(X), and a rule to pass from two functions f:X->T(Y) and g:Y->T(Z) (that you would like to compose but can't) to a new function h:X->T(Z). Which, however, is not the composition in strict mathematical sense. We are basically "bending" function's composition or re-defining how functions are composed.

Plus, we require the monad's rule of composing to satisfy the "obvious" mathematical axioms:

  • Associativity: Composing f with g and then with h (from outside) should be the same as composing g with h and then with f (from inside).
  • Unital property: Composing f with the identity function on either side should yield f.

Again, in simple words, we can't just go crazy re-defining our function composition as we like:

  • We first need the associativity to be able to compose several functions in a row e.g. f(g(h(k(x))), and not to worry about specifying the order composing function pairs. As the monad rule only prescribes how to compose a pair of functions, without that axiom, we would need to know which pair is composed first and so on. (Note that is different from the commutativity property that f composed with g were the same as g composed with f, which is not required).
  • And second, we need the unital property, which is simply to say that identities compose trivially the way we expect them. So we can safely refactor functions whenever those identities can be extracted.

So again in brief: A monad is the rule of type extension and composing functions satisfying the two axioms -- associativity and unital property.

In practical terms, you want the monad to be implemented for you by the language, compiler or framework that would take care of composing functions for you. So you can focus on writing your function's logic rather than worrying how their execution is implemented.

That is essentially it, in a nutshell.


Being professional mathematician, I prefer to avoid calling h the "composition" of f and g. Because mathematically, it isn't. Calling it the "composition" incorrectly presumes that h is the true mathematical composition, which it isn't. It is not even uniquely determined by f and g. Instead, it is the result of our monad's new "rule of composing" the functions. Which can be totally different from the actual mathematical composition even if the latter exists!


To make it less dry, let me try to illustrate it by example that I am annotating with small sections, so you can skip right to the point.

Exception throwing as Monad examples

Suppose we want to compose two functions:

f: x -> 1 / x
g: y -> 2 * y

But f(0) is not defined, so an exception e is thrown. Then how can you define the compositional value g(f(0))? Throw an exception again, of course! Maybe the same e. Maybe a new updated exception e1.

What precisely happens here? First, we need new exception value(s) (different or same). You can call them nothing or null or whatever but the essence remains the same -- they should be new values, e.g. it should not be a number in our example here. I prefer not to call them null to avoid confusion with how null can be implemented in any specific language. Equally I prefer to avoid nothing because it is often associated with null, which, in principle, is what null should do, however, that principle often gets bended for whatever practical reasons.

What is exception exactly?

This is a trivial matter for any experienced programmer but I'd like to drop few words just to extinguish any worm of confusion:

Exception is an object encapsulating information about how the invalid result of execution occurred.

This can range from throwing away any details and returning a single global value (like NaN or null) or generating a long log list or what exactly happened, send it to a database and replicating all over the distributed data storage layer ;)

The important difference between these two extreme examples of exception is that in the first case there are no side-effects. In the second there are. Which brings us to the (thousand-dollar) question:

Are exceptions allowed in pure functions?

Shorter answer: Yes, but only when they don't lead to side-effects.

Longer answer. To be pure, your function's output must be uniquely determined by its input. So we amend our function f by sending 0 to the new abstract value e that we call exception. We make sure that value e contains no outside information that is not uniquely determined by our input, which is x. So here is an example of exception without side-effect:

e = {
  type: error, 
  message: 'I got error trying to divide 1 by 0'
}

And here is one with side-effect:

e = {
  type: error, 
  message: 'Our committee to decide what is 1/0 is currently away'
}

Actually, it only has side-effects if that message can possibly change in the future. But if it is guaranteed to never change, that value becomes uniquely predictable, and so there is no side-effect.

To make it even sillier. A function returning 42 ever is clearly pure. But if someone crazy decides to make 42 a variable that value might change, the very same function stops being pure under the new conditions.

Note that I am using the object literal notation for simplicity to demonstrate the essence. Unfortunately things are messed-up in languages like JavaScript, where error is not a type that behaves the way we want here with respect to function composition, whereas actual types like null or NaN do not behave this way but rather go through the some artificial and not always intuitive type conversions.

Type extension

As we want to vary the message inside our exception, we are really declaring a new type E for the whole exception object and then That is what the maybe number does, apart from its confusing name, which is to be either of type number or of the new exception type E, so it is really the union number | E of number and E. In particular, it depends on how we want to construct E, which is neither suggested nor reflected in the name maybe number.

What is functional composition?

It is the mathematical operation taking functions f: X -> Y and g: Y -> Z and constructing their composition as function h: X -> Z satisfying h(x) = g(f(x)). The problem with this definition occurs when the result f(x) is not allowed as argument of g.

In mathematics those functions cannot be composed without extra work. The strictly mathematical solution for our above example of f and g is to remove 0 from the set of definition of f. With that new set of definition (new more restrictive type of x), f becomes composable with g.

However, it is not very practical in programming to restrict the set of definition of f like that. Instead, exceptions can be used.

Or as another approach, artificial values are created like NaN, undefined, null, Infinity etc. So you evaluate 1/0 to Infinity and 1/-0 to -Infinity. And then force the new value back into your expression instead of throwing exception. Leading to results you may or may not find predictable:

1/0                // => Infinity
parseInt(Infinity) // => NaN
NaN < 0            // => false
false + 1          // => 1

And we are back to regular numbers ready to move on ;)

JavaScript allows us to keep executing numerical expressions at any costs without throwing errors as in the above example. That means, it also allows to compose functions. Which is exactly what monad is about - it is a rule to compose functions satisfying the axioms as defined at the beginning of this answer.

But is the rule of composing function, arising from JavaScript's implementation for dealing with numerical errors, a monad?

To answer this question, all you need is to check the axioms (left as exercise as not part of the question here;).

Can throwing exception be used to construct a monad?

Indeed, a more useful monad would instead be the rule prescribing that if f throws exception for some x, so does its composition with any g. Plus make the exception E globally unique with only one possible value ever (terminal object in category theory). Now the two axioms are instantly checkable and we get a very useful monad. And the result is what is well-known as the maybe monad.

Mime type for WOFF fonts?

Mime type might not be your only problem. If the font file is hosted on S3 or other domain, you may additionally have the issue that Firefox will not load fonts from different domains. It's an easy fix with Apache, but in Nginx, I've read that you may need to encode your font files in base-64 and embed them directly in your font css file.

Remove excess whitespace from within a string

$str = trim(preg_replace('/\s+/',' ', $str));

The above line of code will remove extra spaces, as well as leading and trailing spaces.

how to change class name of an element by jquery

$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

Declare multiple module.exports in Node.js

Adding here for someone to help:

this code block will help adding multiple plugins into cypress index.js Plugins -> cypress-ntlm-auth and cypress env file selection

const ntlmAuth = require('cypress-ntlm-auth/dist/plugin');
const fs = require('fs-extra');
const path = require('path');

const getConfigurationByFile = async (config) => {
  const file = config.env.configFile || 'dev';
  const pathToConfigFile = path.resolve(
    '../Cypress/cypress/',
    'config',
    `${file}.json`
  );
  console.log('pathToConfigFile' + pathToConfigFile);
  return fs.readJson(pathToConfigFile);
};

module.exports = async (on, config) => {
  config = await getConfigurationByFile(config);
  await ntlmAuth.initNtlmAuth(config);
  return config;
};

Accessing nested JavaScript objects and arrays by string path

AngularJS

Speigg's approach is very neat and clean, though I found this reply while searching for the solution of accessing AngularJS $scope properties by string path and with a little modification it does the job:

$scope.resolve = function( path, obj ) {
    return path.split('.').reduce( function( prev, curr ) {
        return prev[curr];
    }, obj || this );
}

Just place this function in your root controller and use it any child scope like this:

$scope.resolve( 'path.to.any.object.in.scope')

How to set index.html as root file in Nginx?

According to the documentation Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. Important

an internal redirect to the uri specified in the last parameter is made.

So in last parameter you should add your page or code if first two parameters returns false.

location / {
  try_files $uri $uri/index.html index.html;
}

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

Undoing a git rebase

If you don't want to do a hard reset...

You can checkout the commit from the reflog, and then save it as a new branch:

git reflog

Find the commit just before you started rebasing. You may need to scroll further down to find it (press Enter or PageDown). Take note of the HEAD number and replace 57:

git checkout HEAD@{57}

Review the branch/commits, and if it's correct then create a new branch using this HEAD:

git checkout -b new_branch_name

How to handle configuration in Go

I usually use JSON for more complicated data structures. The downside is that you easily end up with a bunch of code to tell the user where the error was, various edge cases and what not.

For base configuration (api keys, port numbers, ...) I've had very good luck with the gcfg package. It is based on the git config format.

From the documentation:

Sample config:

; Comment line
[section]
name = value # Another comment
flag # implicit value for bool is true

Go struct:

type Config struct {
    Section struct {
            Name string
            Flag bool
    }
}

And the code needed to read it:

var cfg Config
err := gcfg.ReadFileInto(&cfg, "myconfig.gcfg")

It also supports slice values, so you can allow specifying a key multiple times and other nice features like that.

jQuery - How to dynamically add a validation rule

You need to call .validate() before you can add rules this way, like this:

$("#myForm").validate(); //sets up the validator
$("input[id*=Hours]").rules("add", "required");

The .validate() documentation is a good guide, here's the blurb about .rules("add", option):

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.

Getting an element from a Set

Why:

It seems that Set plays a useful role in providing a means of comparison. It is designed not to store duplicate elements.

Because of this intention/design, if one were to get() a reference to the stored object, then mutate it, it is possible that the design intentions of Set could be thwarted and could cause unexpected behavior.

From the JavaDocs

Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set.

How:

Now that Streams have been introduced one can do the following

mySet.stream()
.filter(object -> object.property.equals(myProperty))
.findFirst().get();

how do I change text in a label with swift?

Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:

self.simpleLabel.text = "message"

Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.

How to find the duration of difference between two dates in java?

   // calculating the difference b/w startDate and endDate
        String startDate = "01-01-2016";
        String endDate = simpleDateFormat.format(currentDate);

        date1 = simpleDateFormat.parse(startDate);
        date2 = simpleDateFormat.parse(endDate);

        long getDiff = date2.getTime() - date1.getTime();

        // using TimeUnit class from java.util.concurrent package
        long getDaysDiff = TimeUnit.MILLISECONDS.toDays(getDiff);

How to calculate difference between two dates in Java

What's the difference between select_related and prefetch_related in Django ORM?

As Django documentation says:

prefetch_related()

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

More information about this: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-related

How to create EditText with cross(x) button at end of it?

Just put close cross like drawableEnd in your EditText:

<EditText
     ...
    android:drawableEnd="@drawable/ic_close"
    android:drawablePadding="8dp"
     ... />

and use extension to handle click (or use OnTouchListener directly on your EditText):

fun EditText.onDrawableEndClick(action: () -> Unit) {
    setOnTouchListener { v, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            v as EditText
            val end = if (v.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL)
                v.left else v.right
            if (event.rawX >= (end - v.compoundPaddingEnd)) {
                action.invoke()
                return@setOnTouchListener true
            }
        }
        return@setOnTouchListener false
    }
}

extension usage:

editText.onDrawableEndClick {
    // TODO clear action
    etSearch.setText("")
}

How to add external library in IntelliJ IDEA?

I've used this process to attach a 3rd party Jar to an Android project in IDEA.

  • Copy the Jar to your libs/ directory
  • Open Project Settings (Ctrl Alt Shift S)
  • Under the Project Settings panel on the left, choose Modules
  • On the larger right pane, choose the Dependencies tab
  • Press the Add... button on the far right of the screen (if you have a smaller screen like me, you may have to drag resize to the right in order to see it)
  • From the dropdown of Add options, choose "Library". A "Choose Libraries" dialog will appear.
  • Press "New Library..."
  • Choose a suitable title for the library
  • Press "Attach Classes..."
  • Choose the Jar from your libs/ directory, and press OK to dismiss

The library should now be recognised.

Disable activity slide-in animation when launching new activity?

This works for me when disabling finish Activity animation.

@Override
protected void onPause() {
    super.onPause();
    overridePendingTransition(0, 0);
}

How to run a cron job on every Monday, Wednesday and Friday?

Use this command to add job

crontab -e

In this format:

0 19 * * 1,3,5 /path to your file/file.php

How can I add new dimensions to a Numpy array?

There is no structure in numpy that allows you to append more data later.

Instead, numpy puts all of your data into a contiguous chunk of numbers (basically; a C array), and any resize requires allocating a new chunk of memory to hold it. Numpy's speed comes from being able to keep all the data in a numpy array in the same chunk of memory; e.g. mathematical operations can be parallelized for speed and you get less cache misses.

So you will have two kinds of solutions:

  1. Pre-allocate the memory for the numpy array and fill in the values, like in JoshAdel's answer, or
  2. Keep your data in a normal python list until it's actually needed to put them all together (see below)

images = []
for i in range(100):
    new_image = # pull image from somewhere
    images.append(new_image)
images = np.stack(images, axis=3)

Note that there is no need to expand the dimensions of the individual image arrays first, nor do you need to know how many images you expect ahead of time.

Javascript ajax call on page onload

Or with Prototype:

Event.observe(this, 'load', function() { new Ajax.Request(... ) );

Or better, define the function elsewhere rather than inline, then:

Event.observe(this, 'load', functionName );

You don't have to use jQuery or Prototype specifically, but I hope you're using some kind of library. Either library is going to handle the event handling in a more consistent manner than onload, and of course is going to make it much easier to process the Ajax call. If you must use the body onload attribute, then you should just be able to call the same function as referenced in these examples (onload="javascript:functionName();").

However, if your database update doesn't depend on the rendering on the page, why wait until it's fully loaded? You could just include a call to the Ajax-calling function at the end of the JavaScript on the page, which should give nearly the same effect.

Python regex for integer?

I prefer ^[-+]?([1-9]\d*|0)$ because ^[-+]?[0-9]+$ allows the string starting with 0.

RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')


class TestRE(unittest.TestCase):
    def test_int(self):
        self.assertFalse(RE_INT.match('+'))
        self.assertFalse(RE_INT.match('-'))

        self.assertTrue(RE_INT.match('1'))
        self.assertTrue(RE_INT.match('+1'))
        self.assertTrue(RE_INT.match('-1'))
        self.assertTrue(RE_INT.match('0'))
        self.assertTrue(RE_INT.match('+0'))
        self.assertTrue(RE_INT.match('-0'))

        self.assertTrue(RE_INT.match('11'))
        self.assertFalse(RE_INT.match('00'))
        self.assertFalse(RE_INT.match('01'))
        self.assertTrue(RE_INT.match('+11'))
        self.assertFalse(RE_INT.match('+00'))
        self.assertFalse(RE_INT.match('+01'))
        self.assertTrue(RE_INT.match('-11'))
        self.assertFalse(RE_INT.match('-00'))
        self.assertFalse(RE_INT.match('-01'))

        self.assertTrue(RE_INT.match('1234567890'))
        self.assertTrue(RE_INT.match('+1234567890'))
        self.assertTrue(RE_INT.match('-1234567890'))

How to call a Python function from Node.js

Easiest way I know of is to use "child_process" package which comes packaged with node.

Then you can do something like:

const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);

Then all you have to do is make sure that you import sys in your python script, and then you can access arg1 using sys.argv[1], arg2 using sys.argv[2], and so on.

To send data back to node just do the following in the python script:

print(dataToSendBack)
sys.stdout.flush()

And then node can listen for data using:

pythonProcess.stdout.on('data', (data) => {
    // Do something with the data returned from python script
});

Since this allows multiple arguments to be passed to a script using spawn, you can restructure a python script so that one of the arguments decides which function to call, and the other argument gets passed to that function, etc.

Hope this was clear. Let me know if something needs clarification.

Syntax error "syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)"

$ rails server -b $IP -p $PORT - that solved the same problem for me

How to fix error with xml2-config not found when installing PHP from sources?

I had the same issue when I used a DockerFile. My Docker is based on the php:5.5-apache image.

I got that error when executing the command "RUN docker-php-ext-install soap"

I have solved it by adding the following command to my DockerFile

"RUN apt-get update && apt-get install -y libxml2-dev"

Nullable type as a generic parameter possible?

Change the return type to Nullable<T>, and call the method with the non nullable parameter

static void Main(string[] args)
{
    int? i = GetValueOrNull<int>(null, string.Empty);
}


public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
    object columnValue = reader[columnName];

    if (!(columnValue is DBNull))
        return (T)columnValue;

    return null;
}

ggplot2: sorting a plot

I've recently been struggling with a related issue, discussed at length here: Order of legend entries in ggplot2 barplots with coord_flip() .

As it happens, the reason I had a hard time explaining my issue clearly, involved the relation between (the order of) factors and coord_flip(), as seems to be the case here.

I get the desired result by adding + xlim(rev(levels(x$variable))) to the ggplot statement:

ggplot(x, aes(x=variable,y=value)) + geom_bar() + 
scale_y_continuous("",formatter="percent") + coord_flip() 
+  xlim(rev(levels(x$variable)))

This reverses the order of factors as found in the original data frame in the x-axis, which will become the y-axis with coord_flip(). Notice that in this particular example, the variable also happen to be in alphabetical order, but specifying an arbitrary order of levels within xlim() should work in general.

How can I produce an effect similar to the iOS 7 blur view?

You can try using my custom view, which has capability to blur the background. It does this by faking taking snapshot of the background and blur it, just like the one in Apple's WWDC code. It is very simple to use.

I also made some improvement over to fake the dynamic blur without losing the performance. The background of my view is a scrollView which scrolls with the view, thus provide the blur effect for the rest of the superview.

See the example and code on my GitHub