Programs & Examples On #Fibplus

How to manage a redirect request after a jQuery Ajax call

I think a better way to handle this is to leverage the existing HTTP protocol response codes, specifically 401 Unauthorized.

Here is how I solved it:

  1. Server side: If session expires, and request is ajax. send a 401 response code header
  2. Client side: Bind to the ajax events

    $('body').bind('ajaxSuccess',function(event,request,settings){
    if (401 == request.status){
        window.location = '/users/login';
    }
    }).bind('ajaxError',function(event,request,settings){
    if (401 == request.status){
        window.location = '/users/login';
    }
    });
    

IMO this is more generic and you are not writing some new custom spec/header. You also should not have to modify any of your existing ajax calls.

Edit: Per @Rob's comment below, 401 (the HTTP status code for authentication errors) should be the indicator. See 403 Forbidden vs 401 Unauthorized HTTP responses for more detail. With that being said some web frameworks use 403 for both authentication AND authorization errors - so adapt accordingly. Thanks Rob.

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

In an instance where you want to set a placeholder and not have a default value be selected, you can use this option.

      <select defaultValue={'DEFAULT'} >
        <option value="DEFAULT" disabled>Choose a salutation ...</option>
        <option value="1">Mr</option>
        <option value="2">Mrs</option>
        <option value="3">Ms</option>
        <option value="4">Miss</option>
        <option value="5">Dr</option>
      </select>

Here the user is forced to pick an option!

EDIT

If this is a controlled component

In this case unfortunately you will have to use both defaultValue and value violating React a bit. This is because react by semantics does not allow setting a disabled value as active.

 function TheSelectComponent(props){
     let currentValue = props.curentValue || "DEFAULT";
     return(
      <select value={currentValue} defaultValue={'DEFAULT'} onChange={props.onChange}>
        <option value="DEFAULT" disabled>Choose a salutation ...</option>
        <option value="1">Mr</option>
        <option value="2">Mrs</option>
        <option value="3">Ms</option>
        <option value="4">Miss</option>
        <option value="5">Dr</option>
      </select>
    )
}

Replace \n with actual new line in Sublime Text

Use Find > Replace, or (Ctrl+H), to open the Find What/Replace With Window, and use Ctrl+Enter to indicate a new line in the Replace With inputbox.

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

How do I ZIP a file in C#, using no 3rd-party APIs?

Looks like Windows might just let you do this...

Unfortunately I don't think you're going to get around starting a separate process unless you go to a third party component.

SSL certificate is not trusted - on mobile only

Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.

How can I render Partial views in asp.net mvc 3?

Create your partial view something like:

@model YourModelType
<div>
  <!-- HTML to render your object -->
</div>

Then in your view use:

@Html.Partial("YourPartialViewName", Model)

If you do not want a strongly typed partial view remove the @model YourModelType from the top of the partial view and it will default to a dynamic type.

Update

The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/ in the path below.

@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)

Check if an object belongs to a class in Java

I agree with the use of instanceof already mentioned.

An additional benefit of using instanceof is that when used with a null reference instanceof of will return false, while a.getClass() would throw a NullPointerException.

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

Call a React component method from outside

With the render method potentially deprecating the returned value, the recommended approach is now to attach a callback ref to the root element. Like this:

ReactDOM.render( <Hello name="World" ref={(element) => {window.helloComponent = element}}/>, document.getElementById('container'));

which we can then access using window.helloComponent, and any of its methods can be accessed with window.helloComponent.METHOD.

Here's a full example:

_x000D_
_x000D_
var onButtonClick = function() {_x000D_
  window.helloComponent.alertMessage();_x000D_
}_x000D_
_x000D_
class Hello extends React.Component {_x000D_
  alertMessage() {_x000D_
    alert(this.props.name);_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return React.createElement("div", null, "Hello ", this.props.name);_x000D_
  }_x000D_
};_x000D_
_x000D_
ReactDOM.render( <Hello name="World" ref={(element) => {window.helloComponent = element}}/>, document.getElementById('container'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>_x000D_
<button onclick="onButtonClick()">Click me!</button>
_x000D_
_x000D_
_x000D_

Mapping two integers to one, in a unique and deterministic way

Is this even possible?
You are combining two integers. They both have the range -2,147,483,648 to 2,147,483,647 but you will only take the positives. That makes 2147483647^2 = 4,61169E+18 combinations. Since each combination has to be unique AND result in an integer, you'll need some kind of magical integer that can contain this amount of numbers.

Or is my logic flawed?

What does ellipsize mean in android?

Text:

 This is my first android application and
 I am trying to make a funny game,
 It seems android is really very easy to play.

Suppose above is your text and if you are using ellipsize's start attribute it will seen like this

This is my first android application and
...t seems android is really very easy to play.

with end attribute

 This is my first android application and
 I am trying to make a funny game,...

Object Dump JavaScript

For Chrome/Chromium

console.log(myObj)

or it's equivalent

console.debug(myObj)

Python - Get Yesterday's date as a string in YYYY-MM-DD format

Calling .isoformat() on a date object will give you YYYY-MM-DD

from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()

Using request.setAttribute in a JSP page

Correct me if wrong...I think request does persist between consecutive pages..

Think you traverse from page 1--> page 2-->page 3.

You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".

I mean something like this in page 2 fails:

Where as the same thing has worked in case of page 1 like:

So I think I would need to proceed with either of the two options suggested by Phill.

ReferenceError: variable is not defined

It's declared inside a closure, which means it can only be accessed there. If you want a variable accessible globally, you can remove the var:

$(function(){
    value = "10";
});
value; // "10"

This is equivalent to writing window.value = "10";.

CSS @font-face not working with Firefox, but working with Chrome and IE

I was having the same problem. Double check your code for H1, H2 or whatever style you are targeting with the @font-face rule. I found I was missing a coma after font-family: 'custom-font-family' Arial, Helvetica etc It was showing up fine in every browser apart from Firefox. I added the coma and it worked.

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

I got the same error while working with mnist data set, looks like a problem with the dimensions of X_train. I added another dimension and it solved the purpose.

X_train, X_test, \ y_train, y_test = train_test_split(X_reshaped, y_labels, train_size = 0.8, random_state = 42)

X_train = X_train.reshape(-1,28, 28, 1)

X_test = X_test.reshape(-1,28, 28, 1)

Duplicate line in Visual Studio Code

Search for copyLinesDownAction or copyLinesUpAction in your keyboard shortcuts

Usually, it is SHIFT+ALT+?

Use ASP.NET MVC validation with jquery ajax?

Added some more logic to solution provided by @Andrew Burgess. Here is the full solution:

Created a action filter to get errors for ajax request:

public class ValidateAjaxAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAjaxRequest())
                return;

            var modelState = filterContext.Controller.ViewData.ModelState;
            if (!modelState.IsValid)
            {
                var errorModel =
                        from x in modelState.Keys
                        where modelState[x].Errors.Count > 0
                        select new
                        {
                            key = x,
                            errors = modelState[x].Errors.
                                                          Select(y => y.ErrorMessage).
                                                          ToArray()
                        };
                filterContext.Result = new JsonResult()
                {
                    Data = errorModel
                };
                filterContext.HttpContext.Response.StatusCode =
                                                      (int)HttpStatusCode.BadRequest;
            }
        }
    }

Added the filter to my controller method as:

[HttpPost]
// this line is important
[ValidateAjax]
public ActionResult AddUpdateData(MyModel model)
{
    return Json(new { status = (result == 1 ? true : false), message = message }, JsonRequestBehavior.AllowGet);
}

Added a common script for jquery validation:

function onAjaxFormError(data) {
    var form = this;
    var errorResponse = data.responseJSON;
    $.each(errorResponse, function (index, value) {
        // Element highlight
        var element = $(form).find('#' + value.key);
        element = element[0];
        highLightError(element, 'input-validation-error');

        // Error message
        var validationMessageElement = $('span[data-valmsg-for="' + value.key + '"]');
        validationMessageElement.removeClass('field-validation-valid');
        validationMessageElement.addClass('field-validation-error');
        validationMessageElement.text(value.errors[0]);
    });
}

$.validator.setDefaults({
            ignore: [],
            highlight: highLightError,
            unhighlight: unhighlightError
        });

var highLightError = function(element, errorClass) {
    element = $(element);
    element.addClass(errorClass);
}

var unhighLightError = function(element, errorClass) {
    element = $(element);
    element.removeClass(errorClass);
}

Finally added the error javascript method to my Ajax Begin form:

@model My.Model.MyModel
@using (Ajax.BeginForm("AddUpdateData", "Home", new AjaxOptions { HttpMethod = "POST", OnFailure="onAjaxFormError" }))
{
}

Start HTML5 video at a particular position when loading?

You can link directly with Media Fragments URI, just change the filename to file.webm#t=50

Here's an example

This is pretty cool, you can do all sorts of things. But I don't know the current state of browser support.

When should I use a table variable vs temporary table in sql server?

Use a table variable if for a very small quantity of data (thousands of bytes)

Use a temporary table for a lot of data

Another way to think about it: if you think you might benefit from an index, automated statistics, or any SQL optimizer goodness, then your data set is probably too large for a table variable.

In my example, I just wanted to put about 20 rows into a format and modify them as a group, before using them to UPDATE / INSERT a permanent table. So a table variable is perfect.

But I am also running SQL to back-fill thousands of rows at a time, and I can definitely say that the temporary tables perform much better than table variables.

This is not unlike how CTE's are a concern for a similar size reason - if the data in the CTE is very small, I find a CTE performs as good as or better than what the optimizer comes up with, but if it is quite large then it hurts you bad.

My understanding is mostly based on http://www.developerfusion.com/article/84397/table-variables-v-temporary-tables-in-sql-server/, which has a lot more detail.

How to perform an SQLite query within an Android application?

Alternatively, db.rawQuery(sql, selectionArgs) exists.

Cursor c = db.rawQuery(select, null);

Rails find_or_create_by more than one attribute?

By passing a block to find_or_create, you can pass additional parameters that will be added to the object if it is created new. This is useful if you are validating the presence of a field that you aren't searching by.

Assuming:

class GroupMember < ActiveRecord::Base
    validates_presence_of :name
end

then

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create { |gm| gm.name = "John Doe" }

will create a new GroupMember with the name "John Doe" if it doesn't find one with member_id 4 and group_id 7

UILabel Align Text to center

Here is a sample code showing how to align text using UILabel:

label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
label.textAlignment = NSTextAlignmentCenter;

You can read more about it here UILabel

How to get a user's time zone?

You can use below code for getting current time zone

 func getCurrentTimeZone() -> String{

         return TimeZone.current.identifier

  }

  let currentTimeZone = getCurrentTimeZone()
   print(currentTimeZone)

Preventing multiple clicks on button

you can use jQuery's [one][1] :

.one( events [, data ], handler ) Returns: jQuery

Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

see examples:

using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx

// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);

The action or event has been blocked by Disabled Mode

From access help:

Stop Disabled Mode from blocking a query If you try to run an append query and it seems like nothing happens, check the Access status bar for the following message:

This action or event has been blocked by Disabled Mode.

To stop Disabled Mode from blocking the query, you must enable the database content. You use the Options button in the Message Bar to enable the query.

Enable the append query In the Message Bar, click Options. In the Microsoft Office Security Options dialog box, click Enable this content, and then click OK. If you don't see the Message Bar, it may be hidden. You can show it, unless it has also been disabled. If the Message Bar has been disabled, you can enable it.

Show the Message Bar If the Message Bar is already visible, you can skip this step.

On the Database Tools tab, in the Show/Hide group, select the Message Bar check box. If the Message Bar check box is disabled, you will have to enable it.

Enable the Message Bar If the Message Bar check box is enabled, you can skip this step.

Click the Microsoft Office Button , and then click Access Options. In the left pane of the Access Options dialog box, click Trust Center. In the right pane, under Microsoft Office Access Trust Center, click Trust Center Settings. In the left pane of the Trust Center dialog box, click Message Bar. In the right pane, click Show the Message Bar in all applications when content has been blocked, and then click OK. Close and reopen the database to apply the changed setting. Note When you enable the append query, you also enable all other database content.

For more information about Access security, see the article Help secure an Access 2007 database.

Bootstrap onClick button event

There is no show event in js - you need to bind your button either to the click event:

$('#id').on('click', function (e) {

     //your awesome code here

})

Mind that if your button is inside a form, you may prefer to bind the whole form to the submit event.

MySQL connection not working: 2002 No such file or directory

On a Mac, before doing all the hard work, simply check your settings in System Preferences > MySQL. More often than not, I've experienced the team running into this problem since The MySQL Server Instance is stopped.

Click the Start MySQL Server button, and magic will happen.

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

Quote from xlsxwriter module documentation:

This module cannot be used to modify or write to an existing Excel XLSX file.

If you want to modify existing xlsx workbook, consider using openpyxl module.

See also:

Iteration ng-repeat only X times in AngularJs

in the html :

<div ng-repeat="t in getTimes(4)">text</div>

and in the controller :

$scope.getTimes=function(n){
     return new Array(n);
};

http://plnkr.co/edit/j5kNLY4Xr43CzcjM1gkj

EDIT :

with angularjs > 1.2.x

<div ng-repeat="t in getTimes(4) track by $index">TEXT</div>

OpenCV with Network Cameras

#include <stdio.h>
#include "opencv.hpp"


int main(){

    CvCapture *camera=cvCaptureFromFile("http://username:pass@cam_address/axis-cgi/mjpg/video.cgi?resolution=640x480&req_fps=30&.mjpg");
    if (camera==NULL)
        printf("camera is null\n");
    else
        printf("camera is not null");

    cvNamedWindow("img");
    while (cvWaitKey(10)!=atoi("q")){
        double t1=(double)cvGetTickCount();
        IplImage *img=cvQueryFrame(camera);
        double t2=(double)cvGetTickCount();
        printf("time: %gms  fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
        cvShowImage("img",img);
    }
    cvReleaseCapture(&camera);
}

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

It's working for me after unchecking 'User '--releae option' in eclipse Java-compiler

In eclipse step 1: properties -> java Complier -> uchecking 'User '--releae option' option -> finish

Java version 13.0.1 Eclipse version : Eclipse IDE for Enterprise Java Developers.

What is the JUnit XML format specification that Hudson supports?

Basic Structure Here is an example of a JUnit output file, showing a skip and failed result, as well as a single passed result.

<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
   <testsuite name="JUnitXmlReporter" errors="0" tests="0" failures="0" time="0" timestamp="2013-05-24T10:23:58" />
   <testsuite name="JUnitXmlReporter.constructor" errors="0" skipped="1" tests="3" failures="1" time="0.006" timestamp="2013-05-24T10:23:58">
      <properties>
         <property name="java.vendor" value="Sun Microsystems Inc." />
         <property name="compiler.debug" value="on" />
         <property name="project.jdk.classpath" value="jdk.classpath.1.6" />
      </properties>
      <testcase classname="JUnitXmlReporter.constructor" name="should default path to an empty string" time="0.006">
         <failure message="test failure">Assertion failed</failure>
      </testcase>
      <testcase classname="JUnitXmlReporter.constructor" name="should default consolidate to true" time="0">
         <skipped />
      </testcase>
      <testcase classname="JUnitXmlReporter.constructor" name="should default useDotNotation to true" time="0" />
   </testsuite>
</testsuites>

Below is the documented structure of a typical JUnit XML report. Notice that a report can contain 1 or more test suite. Each test suite has a set of properties (recording environment information). Each test suite also contains 1 or more test case and each test case will either contain a skipped, failure or error node if the test did not pass. If the test case has passed, then it will not contain any nodes. For more details of which attributes are valid for each node please consult the following section "Schema".

<testsuites>        => the aggregated result of all junit testfiles
  <testsuite>       => the output from a single TestSuite
    <properties>    => the defined properties at test execution
      <property>    => name/value pair for a single property
      ...
    </properties>
    <error></error> => optional information, in place of a test case - normally if the tests in the suite could not be found etc.
    <testcase>      => the results from executing a test method
      <system-out>  => data written to System.out during the test run
      <system-err>  => data written to System.err during the test run
      <skipped/>    => test was skipped
      <failure>     => test failed
      <error>       => test encountered an error
    </testcase>
    ...
  </testsuite>
  ...
</testsuites>

FIFO based Queue implementations?

Queue is an interface that extends Collection in Java. It has all the functions needed to support FIFO architecture.

For concrete implementation you may use LinkedList. LinkedList implements Deque which in turn implements Queue. All of these are a part of java.util package.

For details about method with sample example you can refer FIFO based Queue implementation in Java.

PS: Above link goes to my personal blog that has additional details on this.

Number of days between past date and current date in Google spreadsheet

The following seemed to work well for me:

=DATEDIF(B2, Today(), "D")

How do you hide the Address bar in Google Chrome for Chrome Apps?

Even though the question is about gaining some space removing the address bar, you can also gain some space by toggling the bookmark bar on and off, using Ctrl + Shift + B, or ? Cmd + Shift + B, in Mac OS.

What do these operators mean (** , ^ , %, //)?

You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:

  • The ** operator does exponentiation. a ** b is a raised to the b power. The same ** symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).
  • The ^ operator does a binary xor. a ^ b will return a value with only the bits set in a or in b but not both. This one is simple!
  • The % operator is mostly to find the modulus of two integers. a % b returns the remainder after dividing a by b. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b, rather than the same sign as a. The same operator is also used for the "old" style of string formatting, so a % b can return a string if a is a format string and b is a value (or tuple of values) which can be inserted into a.
  • The // operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b). In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division at the top of your files. I strongly recommend it!)

Jenkins - how to build a specific branch

I can see many good answers to the question, but I still would like to share this method, by using Git parameter as follows:

Add Git parameter

When building the pipeline you will be asked to choose the branch: Choose branch to build

After that through the groovy code you could specify the branch you want to clone:

git branch:BRANCH[7..-1], url: 'https://github.com/YourName/YourRepo.git' , credentialsId: 'github' 

Note that I'm using a slice from 7 to the last character to shrink "origin/" and get the branch name.

Also in case you configured a webhooks trigger it still work and it will take the default branch you specified(master in our case).

How to flip background image using CSS?

You can flip it horizontally with CSS...

a:visited {
    -moz-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    transform: scaleX(-1);
    filter: FlipH;
    -ms-filter: "FlipH";
}

jsFiddle.

If you want to flip vertically instead...

a:visited {
    -moz-transform: scaleY(-1);
    -o-transform: scaleY(-1);
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
    filter: FlipV;
    -ms-filter: "FlipV";
}

Source.

How do you set a default value for a MySQL Datetime column?

IMPORTANT EDIT: It is now possible to achieve this with DATETIME fields since MySQL 5.6.5, take a look at the other post below...

Previous versions can't do that with DATETIME...

But you can do it with TIMESTAMP:

mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Query OK, 0 rows affected (0.00 sec)

mysql> desc test;
+-------+-------------+------+-----+-------------------+-------+
| Field | Type        | Null | Key | Default           | Extra |
+-------+-------------+------+-----+-------------------+-------+
| str   | varchar(32) | YES  |     | NULL              |       | 
| ts    | timestamp   | NO   |     | CURRENT_TIMESTAMP |       | 
+-------+-------------+------+-----+-------------------+-------+
2 rows in set (0.00 sec)

mysql> insert into test (str) values ("demo");
Query OK, 1 row affected (0.00 sec)

mysql> select * from test;
+------+---------------------+
| str  | ts                  |
+------+---------------------+
| demo | 2008-10-03 22:59:52 | 
+------+---------------------+
1 row in set (0.00 sec)

mysql>

CAVEAT: IF you define a column with CURRENT_TIMESTAMP ON as default, you will need to ALWAYS specify a value for this column or the value will automatically reset itself to "now()" on update. This means that if you do not want the value to change, your UPDATE statement must contain "[your column name] = [your column name]" (or some other value) or the value will become "now()". Weird, but true. I hope this helps. I am using 5.5.56-MariaDB

How do I print colored output with Python 3?

For lazy people:

Without installing any additional library, it is compatible with every single terminal i know.

Class approach:

First do import config as cfg.

clipped is dataframe.

            #### HEADER: ####
            print('{0:<23} {1:>24} {2:>26} {3:>26} {4:>11} {5:>11}'.format('Road name','Classification','Function','Form of road','Length','Distance') )

            #### Now row by row: ####
            for index, row in clipped.iterrows():
                rdName      = self.colorize(row['name1'],cfg.Green)
                rdClass     = self.colorize(row['roadClassification'],cfg.LightYellow)
                rdFunction  = self.colorize(row['roadFunction'],cfg.Yellow)
                rdForm      = self.colorize(row['formOfWay'],cfg.LightBlue)
                rdLength    = self.colorize(row['length'],cfg.White)
                rdDistance  = self.colorize(row['distance'],cfg.LightCyan)
                print('{0:<30} {1:>35} {2:>35} {3:>35} {4:>20} {5:>20}'.format(rdName,rdClass,rdFunction,rdForm,rdLength,rdDistance) )

Meaning of {0:<30} {1:>35} {2:>35} {3:>35} {4:>20} {5:>20}:

0, 1, 2, 3, 4, 5 -> columns, there are 6 in total in this case

30, 35, 20 -> width of column (note that you'll have to add length of \033[96m - this for Python is a string as well), just experiment :)

>, < -> justify: right, left (there is = for filling with zeros as well)

What is in config.py:

#colors
ResetAll = "\033[0m"

Bold       = "\033[1m"
Dim        = "\033[2m"
Underlined = "\033[4m"
Blink      = "\033[5m"
Reverse    = "\033[7m"
Hidden     = "\033[8m"

ResetBold       = "\033[21m"
ResetDim        = "\033[22m"
ResetUnderlined = "\033[24m"
ResetBlink      = "\033[25m"
ResetReverse    = "\033[27m"
ResetHidden     = "\033[28m"

Default      = "\033[39m"
Black        = "\033[30m"
Red          = "\033[31m"
Green        = "\033[32m"
Yellow       = "\033[33m"
Blue         = "\033[34m"
Magenta      = "\033[35m"
Cyan         = "\033[36m"
LightGray    = "\033[37m"
DarkGray     = "\033[90m"
LightRed     = "\033[91m"
LightGreen   = "\033[92m"
LightYellow  = "\033[93m"
LightBlue    = "\033[94m"
LightMagenta = "\033[95m"
LightCyan    = "\033[96m"
White        = "\033[97m"

Result:

enter image description here

How can I view an object with an alert()

alert (product.UnitName + " " + product.UnitPrice + " " + product.Stock)

or else create a toString() method on your object and call

alert(product.toString())

But I have to agree with other posters - if it is debugging you're going for then firebug or F12 on IE9 or chrome and using console.log is the way to go

Check box size change with CSS

Try this

<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */

Android charting libraries

  • Achartengine: I have used this. Although for real time graph this might not give good performance if you do not tweak properly.

sql query to get earliest date

SELECT TOP 1 ID, Name, Score, [Date]
FROM myTable
WHERE ID = 2
Order BY [Date]

How does the "view" method work in PyTorch?

Let's do some examples, from simpler to more difficult.

  1. The view method returns a tensor with the same data as the self tensor (which means that the returned tensor has the same number of elements), but with a different shape. For example:

    a = torch.arange(1, 17)  # a's shape is (16,)
    
    a.view(4, 4) # output below
      1   2   3   4
      5   6   7   8
      9  10  11  12
     13  14  15  16
    [torch.FloatTensor of size 4x4]
    
    a.view(2, 2, 4) # output below
    (0 ,.,.) = 
    1   2   3   4
    5   6   7   8
    
    (1 ,.,.) = 
     9  10  11  12
    13  14  15  16
    [torch.FloatTensor of size 2x2x4]
    
  2. Assuming that -1 is not one of the parameters, when you multiply them together, the result must be equal to the number of elements in the tensor. If you do: a.view(3, 3), it will raise a RuntimeError because shape (3 x 3) is invalid for input with 16 elements. In other words: 3 x 3 does not equal 16 but 9.

  3. You can use -1 as one of the parameters that you pass to the function, but only once. All that happens is that the method will do the math for you on how to fill that dimension. For example a.view(2, -1, 4) is equivalent to a.view(2, 2, 4). [16 / (2 x 4) = 2]

  4. Notice that the returned tensor shares the same data. If you make a change in the "view" you are changing the original tensor's data:

    b = a.view(4, 4)
    b[0, 2] = 2
    a[2] == 3.0
    False
    
  5. Now, for a more complex use case. The documentation says that each new view dimension must either be a subspace of an original dimension, or only span d, d + 1, ..., d + k that satisfy the following contiguity-like condition that for all i = 0, ..., k - 1, stride[i] = stride[i + 1] x size[i + 1]. Otherwise, contiguous() needs to be called before the tensor can be viewed. For example:

    a = torch.rand(5, 4, 3, 2) # size (5, 4, 3, 2)
    a_t = a.permute(0, 2, 3, 1) # size (5, 3, 2, 4)
    
    # The commented line below will raise a RuntimeError, because one dimension
    # spans across two contiguous subspaces
    # a_t.view(-1, 4)
    
    # instead do:
    a_t.contiguous().view(-1, 4)
    
    # To see why the first one does not work and the second does,
    # compare a.stride() and a_t.stride()
    a.stride() # (24, 6, 2, 1)
    a_t.stride() # (24, 2, 1, 6)
    

    Notice that for a_t, stride[0] != stride[1] x size[1] since 24 != 2 x 3

ImportError: No module named 'encodings'

I could also fix this. PYTHONPATH and PYTHONHOME were in cause.

run this in a terminal

   touch ~/.bash_profile
   open ~/.bash_profile

and then delete all useless parts of this file, and save. I do not know how recommended it is to do that !

Display Image On Text Link Hover CSS Only

I did something like that:

HTML:

<p class='parent'>text text text</p>
<img class='child' src='idk.png'>

CSS:

.child {
    visibility: hidden;
}

.parent:hover .child {
    visibility: visible;
}

javascript multiple OR conditions in IF statement

This is an example:

false && true || true   // returns true
false && (true || true) // returns false
(true || true || true)  // returns true
false || true           // returns true
true || false           // returns true

Changing ImageView source

myImgView.setImageResource(R.drawable.monkey);

is used for setting image in the current image view, but if want to delete this image then you can use this code like:

((ImageView) v.findViewById(R.id.ImageView1)).setImageResource(0);

now this will delete the image from your image view, because it has set the resources value to zero.

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.

Two HTML tables side by side, centered on the page

The problem is that the DIV that should center your tables has no width defined. By default, DIVs are block elements and take up the entire width of their parent - in this case the entire document (propagating through the #outer DIV), so the automatic margin style has no effect.

For this technique to work, you simply have to set the width of the div that has margin:auto to anything but "auto" or "inherit" (either a fixed pixel value or a percentage).

How do I get a div to float to the bottom of its container?

A combination of floating and absolute positioning does the work for me. I was attempting to place the send time of a message at the bottom-right corner of the speech bubble. The time should never overlap the message body and it will not inflate the bubble unless it's really necessary.

The solution works like this:

  1. there're two spans with identical text;
  2. one is floated but invisible;
  3. the other is absolutely positioned to the corner;

The purpose of the invisible floated one is to ensure space for the visible one.

_x000D_
_x000D_
.speech-bubble {
  font-size: 16px;
  max-width: 240px;
  margin: 10px;
  display: inline-block;
  background-color: #ccc;
  border-radius: 5px;
  padding: 5px;
  position: relative;
}

.inline-time {
  float: right;
  padding-left: 10px;
  color: red;
}

.giant-text {
  font-size: 36px;
}

.tremendous-giant-text {
  font-size: 72px;
}

.absolute-time {
  position: absolute;
  color: green;
  right: 5px;
  bottom: 5px;
}

.hidden {
  visibility: hidden;
}
_x000D_
<ul>
  <li>
    <span class='speech-bubble'>
      This text is supposed to wrap the time &lt;span&gt; which always seats at the corner of this bubble.
      <span class='inline-time'>13:55</span>
    </span>
  </li>
  
  <li>
    <span class='speech-bubble'>
      Absolute positioning doesn't work because it doesn't care if the two pieces of text overlap. We want to float.
      <span class='inline-time'>13:55</span>
    </span>
  </li>

  <li>
    <span class='speech-bubble'>
      Easy, uh?
      <span class='inline-time'>13:55</span>
    </span>
  </li>
  
  <li>
    <span class='speech-bubble'>
      Well, not <span class='giant-text'>THAT</span>
      easy
      <span class='inline-time'>13:56</span>
    </span>
  </li>
  
  <li>
    <span class='speech-bubble'>
      <span class='tremendous-giant-text'>See?</span>
      <span class='inline-time'>13:56</span>
    </span>
  </li>
  
  <li>
    <span class='speech-bubble'>
      The problem is, we can't tell the span to float to right AND bottom...
      <span class='inline-time'>13:56</span>
    </span>
  </li>
  
  <li>
    <span class='speech-bubble'>
      We can combinate float and absolute: use floated span to reserve space (the bubble will be inflated if necessary) so that the absoluted span is safe to go.
      <span class='inline-time'>13:56</span>
    </span>
  </li>
  
  <li>
    <span class='speech-bubble'>
      <span class='tremendous-giant-text'>See?</span>
      <span class='inline-time'>13:56</span>
      <span class='absolute-time'>13:56</span>
    </span>
  </li>
  
  <li>
    <span class='speech-bubble'>
      Make the floated span invisible.
      <span class='inline-time'>13:56</span>
    </span>
  </li>
  
  <li>
    <span class='speech-bubble'>
      <span class='tremendous-giant-text'>See?</span>
      <span class='inline-time hidden'>13:56</span>
      <span class='absolute-time'>13:56</span>
    </span>
  </li>
  
  <li>
    <span class='speech-bubble'>
      The giant text here is to simulate images which are common in a typical chat app.
      <span class='tremendous-giant-text'>Done!</span>
      <span class='inline-time hidden'>13:56</span>
      <span class='absolute-time'>13:56</span>
    </span>
  </li>
</ul>
_x000D_
_x000D_
_x000D_

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

I got the same issue when I ran mongod command after installing it on Windows10. I stopped the mongodb service and started it again. Working like a charm

Command to stop mongodb service (in windows): net stop mongodb

Command to start mongodb server: mongod --dbpath PATH_TO_DATA_FOLDER

Can multiple different HTML elements have the same ID if they're different elements?

Well, using the HTML validator at w3.org, specific to HTML5, IDs must be unique

Consider the following...

<!DOCTYPE html> 
<html>
    <head>
        <meta charset="UTF-8">
        <title>MyTitle</title> 
    </head>
    <body>
        <div id="x">Barry</div>
        <div id="x">was</div>
        <div id="x">here</div>
    </body>
</html>

the validator responds with ...

Line 9, Column 14: Duplicate ID x.      <div id="x">was</div>
Warning Line 8, Column 14: The first occurrence of ID x was here.       <div id="x">Barry</div>
Error Line 10, Column 14: Duplicate ID x.       <div id="x">here</div>
Warning Line 8, Column 14: The first occurrence of ID x was here.       <div id="x">Barry</div>

... but the OP specifically stated - what about different element types. So consider the following HTML...

<!DOCTYPE html> 
<html>
    <head>
        <meta charset="UTF-8">
        <title>MyTitle</title> 
    </head>
    <body>
        <div id="x">barry
            <span id="x">was here</span>
        </div>
    </body>
</html>

... the result from the validator is...

Line 9, Column 16: Duplicate ID x.          <span id="x">was here</span>
Warning Line 8, Column 14: The first occurrence of ID x was here.       <div id="x">barry

Conclusion:

In either case (same element type, or different element type), if the id is used more than once it is not considered valid HTML5.

Spring Boot - inject map from application.yml

You can make it even simplier, if you want to avoid extra structures.

service:
  mappings:
    key1: value1
    key2: value2
@Configuration
@EnableConfigurationProperties
public class ServiceConfigurationProperties {

  @Bean
  @ConfigurationProperties(prefix = "service.mappings")
  public Map<String, String> serviceMappings() {
    return new HashMap<>();
  }

}

And then use it as usual, for example with a constructor:

public class Foo {

  private final Map<String, String> serviceMappings;

  public Foo(Map<String, String> serviceMappings) {
    this.serviceMappings = serviceMappings;
  }

}

How can I get the behavior of GNU's readlink -f on a Mac?

A lazy way that works for me,

$ brew install coreutils
$ ln -s /usr/local/bin/greadlink /usr/local/bin/readlink
$ which readlink
/usr/local/bin/readlink
/usr/bin/readlink

Get the first element of each tuple in a list in Python

Use a list comprehension:

res_list = [x[0] for x in rows]

Below is a demonstration:

>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>

Alternately, you could use unpacking instead of x[0]:

res_list = [x for x,_ in rows]

Below is a demonstration:

>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>

Both methods practically do the same thing, so you can choose whichever you like.

How to iterate a table rows with JQuery and access some cell values?

try this

var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');

function iterate(selector)
{
  var result = '';
  if ($(selector))
  {
    $(selector).each(function ()
    {
      if (result == '')
      {
        result = $(this).html();
      }
      else
      {
        result = result + "," + $(this).html();
      }
    });
  }
}

retrieve links from web page using python and BeautifulSoup

The following code is to retrieve all the links available in a webpage using urllib2 and BeautifulSoup4:

import urllib2
from bs4 import BeautifulSoup

url = urllib2.urlopen("http://www.espncricinfo.com/").read()
soup = BeautifulSoup(url)

for line in soup.find_all('a'):
    print(line.get('href'))

Gson library in Android Studio

If you are going to use it with Retrofit library, I suggest you to use Square's gson library as:

implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Regular expression to search multiple strings (Textpad)

If I understand what you are asking, it is a regular expression like this:

^(8768|9875|2353)

This matches the three sets of digit strings at beginning of line only.

HTML5 record audio to file

Stream audio in realtime without waiting for recording to end: https://github.com/noamtcohen/AudioStreamer

This streams PCM data but you could modify the code to stream mp3 or Speex

How to JOIN three tables in Codeigniter

Try as follows:

public function funcname($id)
{
    $this->db->select('*');
    $this->db->from('Album a'); 
    $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
    $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
    $this->db->where('c.album_id',$id);
    $this->db->order_by('c.track_title','asc');         
    $query = $this->db->get(); 
    return $query->result_array();
}

If no result found CI returns false otherwise true

Experimental decorators warning in TypeScript compilation

I faced the same issue while creating an Injectable Services in Angular 2. I have all the things at place in tsconfig.json .Still I was getting this error at ColorsImmutable line.

@Injectable()
export class ColorsImmutable {

And fix was to register the Service at module Level or Component Level using the providers array.

providers:[ColorsImmutable ],

Get/pick an image from Android's built-in Gallery app programmatically

basis with the above code, I reflected the code like below, may be it's more suitable:

public String getPath(Uri uri) {
    String selectedImagePath;
    //1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if(cursor != null){
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        selectedImagePath = cursor.getString(column_index);
    }else{
        selectedImagePath = null;
    }

    if(selectedImagePath == null){
        //2:OI FILE Manager --- call method: uri.getPath()
        selectedImagePath = uri.getPath();
    }
    return selectedImagePath;
}

"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

I came across this question when I was trying to find multiple filenames that I could not combine into a regular expression as described in @Chris J's answer, here is what worked for me

find . -name one.pdf -o -name two.txt -o -name anotherone.jpg

-o or -or is logical OR. See Finding Files on Gnu.org for more information.

I was running this on CygWin.

Run Android studio emulator on AMD processor

Since Android Studio 3.2 and Android Emulator 27.3.8 - the android emulator is supported by Windows Hypervisor Platform and as stated in the official android developer blog - there is mac support (since OS X v10.10 Yosemite) and windows support (since April 2018 Update). You may find further instructions on the developer blog.

In my opinion, the performance is significantly better than all previous workarounds.

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

Change

die (mysqli_error()); 

to

die('Error: ' . mysqli_error($myConnection));

in the query

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 

How to get full REST request body using Jersey?

It does seem you would have to use a MessageBodyReader here. Here's an example, using jdom:

import org.jdom.Document;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MediaType;
import javax.ws.rs.ext.MultivaluedMap;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.InputStream;

@Provider // this annotation is necessary!
@ConsumeMime("application/xml") // this is a hint to the system to only consume xml mime types
public class XMLMessageBodyReader implements MessageBodyReader<Document> {
  private SAXBuilder builder = new SAXBuilder();

  public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    // check if we're requesting a jdom Document
    return Document.class.isAssignableFrom(type);
  }

  public Document readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
    try {
      return builder.build(entityStream);
    }
    catch (Exception e) {
      // handle error somehow
    }
  } 
}

Add this class to the list of resources your jersey deployment will process (usually configured via web.xml, I think). You can then use this reader in one of your regular resource classes like this:

@Path("/somepath") @POST
public void handleXMLData(Document doc) {
  // do something with the document
}

I haven't verified that this works exactly as typed, but that's the gist of it. More reading here:

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

CodeIgniter: "Unable to load the requested class"

If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.

Ex.

Filename: csvsample.php

class csvsample {

}

How to set date format in HTML date input tag?

I found same question or related question on stackoverflow

Is there any way to change input type=“date” format?

I found one simple solution, You can not give particulate Format but you can customize Like this.

HTML Code:

    <body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt"  onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>

CSS Code:

#dt{text-indent: -500px;height:25px; width:200px;}

Javascript Code :

function mydate()
{
  //alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
 d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}

Output:

enter image description here

How Big can a Python List Get?

According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*).

PY_SSIZE_T_MAX is defined in pyport.h to be ((size_t) -1)>>1

On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912.

Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.

As long as the number of elements you have is equal or below this, all list functions should operate correctly.

Undo a Git merge that hasn't been pushed yet

With modern Git, you can:

git merge --abort

Older syntax:

git reset --merge

Old-school:

git reset --hard

But actually, it is worth noticing that git merge --abort is only equivalent to git reset --merge given that MERGE_HEAD is present. This can be read in the Git help for merge command.

git merge --abort is equivalent to git reset --merge when MERGE_HEAD is present.

After a failed merge, when there is no MERGE_HEAD, the failed merge can be undone with git reset --merge, but not necessarily with git merge --abort, so they are not only old and new syntax for the same thing.

Personally I find git reset --merge much more powerful and useful in everyday work, so that's the one I always use.

How to copy Docker images from one host to another without using a repository

You will need to save the Docker image as a tar file:

docker save -o <path for generated tar file> <image name>

Then copy your image to a new system with regular file transfer tools such as cp, scp or rsync(preferred for big files). After that you will have to load the image into Docker:

docker load -i <path to image tar file>

PS: You may need to sudo all commands.

EDIT: You should add filename (not just directory) with -o, for example:

docker save -o c:/myfile.tar centos:16

add to array if it isn't there already

With array_flip() it could look like this:

$flipped = array_flip($opts);
$flipped[$newValue] = 1;
$opts = array_keys($flipped);

With array_unique() - like this:

$opts[] = $newValue;
$opts = array_values(array_unique($opts));

Notice that array_values(...) — you need it if you're exporting array to JavaScript in JSON form. array_unique() alone would simply unset duplicate keys, without rebuilding the remaining elements'. So, after converting to JSON this would produce object, instead of array.

>>> json_encode(array_unique(['a','b','b','c']))
=> "{"0":"a","1":"b","3":"c"}"

>>> json_encode(array_values(array_unique(['a','b','b','c'])))
=> "["a","b","c"]"

excel - if cell is not blank, then do IF statement

Your formula is wrong. You probably meant something like:

=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Another equivalent:

=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Or even shorter:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))

OR EVEN SHORTER:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))

Append an object to a list in R in amortized constant time, O(1)?

This is a very interesting question and I hope my thought below could contribute an way of solution to it. This method do give a flat list without indexing, but it does have list and unlist to avoid the nesting structures. I'm not sure about the speed since I don't know how to benchmark it.

a_list<-list()
for(i in 1:3){
  a_list<-list(unlist(list(unlist(a_list,recursive = FALSE),list(rnorm(2))),recursive = FALSE))
}
a_list

[[1]]
[[1]][[1]]
[1] -0.8098202  1.1035517

[[1]][[2]]
[1] 0.6804520 0.4664394

[[1]][[3]]
[1] 0.15592354 0.07424637

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

Had the same issue, In my case I had 1. Parse the string into Json 2. Ensure that when I render my view does not try to display the whole object, but object.value

data = [
{
    "id": 1,
    "name": "Home Page",
    "info": "This little bit of info is being loaded from a Rails 
    API.",
    "created_at": "2018-09-18T16:39:22.184Z",
    "updated_at": "2018-09-18T16:39:22.184Z"
}];
var jsonData = JSON.parse(data)

Then my view

return (
<View style={styles.container}>
  <FlatList
    data={jsonData}
    renderItem={({ item }) => <Item title={item.name} />}
    keyExtractor={item => item.id}
  />
</View>);

Because I'm using an array, I used flat list to display, and ensured I work with object.value, not object otherwise you'll get the same issue

When and where to use GetType() or typeof()?

You may find it easier to use the is keyword:

if (mycontrol is TextBox)

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

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

Example:

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

I get exception when using Thread.sleep(x) or wait()

Use the following coding construct to handle exceptions

try {
  Thread.sleep(1000);
} catch (InterruptedException ie) {
    //Handle exception
}

Matplotlib connect scatterplot points with line - Python

For red lines an points

plt.plot(dates, values, '.r-') 

or for x markers and blue lines

plt.plot(dates, values, 'xb-')

Resize a picture to fit a JLabel

Or u can do it this way. The function u put the below 6 lines will throw an IOException. And will take your JLabel as a parameter.

BufferedImage bi=new BufferedImage(label.width(),label.height(),BufferedImage.TYPE_INT_RGB);

Graphics2D g=bi.createGraphics();

Image img=ImageIO.read(new File("path of your image"));

g.drawImage(img, 0, 0, label.width(), label.height(), null);

g.dispose();

return bi;

How do I position an image at the bottom of div?

Add relative positioning to the wrapping div tag, then absolutely position the image within it like this:

CSS:

.div-wrapper {
    position: relative;
    height: 300px;
    width: 300px;
}

.div-wrapper img {
    position: absolute;
    left: 0;
    bottom: 0;
}

HTML:

<div class="div-wrapper">
    <img src="blah.png"/>
</div>

Now the image sits at the bottom of the div.

Get current URL from IFRAME

I had an issue with blob url hrefs. So, with a reference to the iframe, I just produced an url from the iframe's src attribute:

    const iframeReference = document.getElementById("iframe_id");
    const iframeUrl = iframeReference ? new URL(iframeReference.src) : undefined;
    if (iframeUrl) {
        console.log("Voila: " + iframeUrl);
    } else {
        console.warn("iframe with id iframe_id not found");
    }

IE11 Document mode defaults to IE7. How to reset?

If you are a developer, this is what you need to do:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

How do I create a table based on another table

select * into newtable from oldtable

How can I check if a string is null or empty in PowerShell?

In addition to [string]::IsNullOrEmpty in order to check for null or empty you can cast a string to a Boolean explicitly or in Boolean expressions:

$string = $null
[bool]$string
if (!$string) { "string is null or empty" }

$string = ''
[bool]$string
if (!$string) { "string is null or empty" }

$string = 'something'
[bool]$string
if ($string) { "string is not null or empty" }

Output:

False
string is null or empty

False
string is null or empty

True
string is not null or empty

get client time zone from browser

you could use moment-timezone to guess the timezone:

> moment.tz.guess()
"America/Asuncion"

Use superscripts in R axis labels

@The Thunder Chimp You can split text in such a way that some sections are affected by super(or sub) script and others aren't through the use of *. For your example, with splitting the word "moment" from "4th" -

plot(rnorm(30), xlab = expression('4'^th*'moment'))

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

in my case I would install django (

pip install django

) and it has a same problem with ssl certificate (Cannot fetch index base URL http://pypi.python.org/simple/ )

it's from virtualenv so DO :

FIRST: delete your virtualenv

deactivate rm -rf env

SECOND: check have pip

pip3 -V

if you don't have

sudo apt-get install python3-pip

FINALLY:

install virtualenv with nosite-packages and make your virenviroment

sudo pip3 install virtualenv virtualenv --no-site-packages -p /usr/bin/python3.6

. env/bin/activate

Can someone give an example of cosine similarity, in a very simple, graphical way?

Here's a simple Python code to calculate cosine similarity:

import math

def dot_prod(v1, v2):
    ret = 0
    for i in range(len(v1)):
        ret += v1[i] * v2[i]
    return ret

def magnitude(v):
    ret = 0
    for i in v:
        ret += i**2
    return math.sqrt(ret)

def cos_sim(v1, v2):
    return (dot_prod(v1, v2)) / (magnitude(v1) * magnitude(v2))

HttpClient won't import in Android Studio

If you want import some class like :

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

You can add the following line in the build.gradle (Gradle dependencies)

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support:support-v4:27.1.0'

    .
    .
    .

    implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

}

How can I convert string to datetime with format specification in JavaScript?

Just for an updated answer here, there's a good js lib at http://www.datejs.com/

Datejs is an open source JavaScript Date library for parsing, formatting and processing.

java get file size efficiently

Actually, I think the "ls" may be faster. There are definitely some issues in Java dealing with getting File info. Unfortunately there is no equivalent safe method of recursive ls for Windows. (cmd.exe's DIR /S can get confused and generate errors in infinite loops)

On XP, accessing a server on the LAN, it takes me 5 seconds in Windows to get the count of the files in a folder (33,000), and the total size.

When I iterate recursively through this in Java, it takes me over 5 minutes. I started measuring the time it takes to do file.length(), file.lastModified(), and file.toURI() and what I found is that 99% of my time is taken by those 3 calls. The 3 calls I actually need to do...

The difference for 1000 files is 15ms local versus 1800ms on server. The server path scanning in Java is ridiculously slow. If the native OS can be fast at scanning that same folder, why can't Java?

As a more complete test, I used WineMerge on XP to compare the modified date, and size of the files on the server versus the files locally. This was iterating over the entire directory tree of 33,000 files in each folder. Total time, 7 seconds. java: over 5 minutes.

So the original statement and question from the OP is true, and valid. Its less noticeable when dealing with a local file system. Doing a local compare of the folder with 33,000 items takes 3 seconds in WinMerge, and takes 32 seconds locally in Java. So again, java versus native is a 10x slowdown in these rudimentary tests.

Java 1.6.0_22 (latest), Gigabit LAN, and network connections, ping is less than 1ms (both in the same switch)

Java is slow.

Remove final character from string

Simple:

st =  "abcdefghij"
st = st[:-1]

There is also another way that shows how it is done with steps:

list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

This is also a way with user input:

list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

To make it take away the last word in a list:

list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)

what's the easiest way to put space between 2 side-by-side buttons in asp.net

Old post, but I'd say the cleanest approach would be to add a class to the surrounding div and a button class on each button so your CSS rule becomes useful for more use cases:

_x000D_
_x000D_
/* Added to highlight spacing */_x000D_
.is-grouped {   _x000D_
    display: inline-block;_x000D_
    background-color: yellow;_x000D_
}_x000D_
_x000D_
.is-grouped > .button:not(:last-child) {_x000D_
    margin-right: 10px;_x000D_
}
_x000D_
Spacing shown in yellow<br><br>_x000D_
_x000D_
<div class='is-grouped'>_x000D_
    <button class='button'>Save</button>_x000D_
    <button class='button'>Save As...</button>_x000D_
    <button class='button'>Delete</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

bower command not found

Alternatively, you can use npx which comes along with the npm > 5.6.

npx bower install

C++11 rvalues and move semantics confusion (return statement)

As already mentioned in comments to the first answer, the return std::move(...); construct can make a difference in cases other than returning of local variables. Here's a runnable example that documents what happens when you return a member object with and without std::move():

#include <iostream>
#include <utility>

struct A {
  A() = default;
  A(const A&) { std::cout << "A copied\n"; }
  A(A&&) { std::cout << "A moved\n"; }
};

class B {
  A a;
 public:
  operator A() const & { std::cout << "B C-value: "; return a; }
  operator A() & { std::cout << "B L-value: "; return a; }
  operator A() && { std::cout << "B R-value: "; return a; }
};

class C {
  A a;
 public:
  operator A() const & { std::cout << "C C-value: "; return std::move(a); }
  operator A() & { std::cout << "C L-value: "; return std::move(a); }
  operator A() && { std::cout << "C R-value: "; return std::move(a); }
};

int main() {
  // Non-constant L-values
  B b;
  C c;
  A{b};    // B L-value: A copied
  A{c};    // C L-value: A moved

  // R-values
  A{B{}};  // B R-value: A copied
  A{C{}};  // C R-value: A moved

  // Constant L-values
  const B bc;
  const C cc;
  A{bc};   // B C-value: A copied
  A{cc};   // C C-value: A copied

  return 0;
}

Presumably, return std::move(some_member); only makes sense if you actually want to move the particular class member, e.g. in a case where class C represents short-lived adapter objects with the sole purpose of creating instances of struct A.

Notice how struct A always gets copied out of class B, even when the class B object is an R-value. This is because the compiler has no way to tell that class B's instance of struct A won't be used any more. In class C, the compiler does have this information from std::move(), which is why struct A gets moved, unless the instance of class C is constant.

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

In ReactJS, I check in the constructor if the variables are null, if they are I treat it like an exception and manage the exception appropriately. If the variables are not null, code carries on and compiler does not complain anymore after that point:

private variable1: any;
private variable2: any;

constructor(props: IProps) {
    super(props);

    // i.e. here I am trying to access an HTML element
    // which might be null if there is a typo in the name
    this.variable1 = document.querySelector('element1');
    this.variable2 = document.querySelector('element2');

    // check if objects are null
    if(!this.variable1 || !this.variable2) {
        // Manage the 'exception', show the user a message, etc.
    } else {
        // Interpreter should not complain from this point on
        // in any part of the file
        this.variable1.disabled = true; // i.e. this line should not show the error
    }

Bringing a subview to be in front of all other views

I had a need for this once. I created a custom UIView class - AlwaysOnTopView.

@interface AlwaysOnTopView : UIView
@end

@implementation AlwaysOnTopView

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.superview && [keyPath isEqual:@"subviews.@count"]) {
        [self.superview bringSubviewToFront:self];
    }

    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (self.superview) {
        [self.superview removeObserver:self forKeyPath:@"subviews.@count"];
    }

    [super willMoveToSuperview:newSuperview];
}

- (void)didMoveToSuperview {
    [super didMoveToSuperview];

    if (self.superview) {
        [self.superview addObserver:self forKeyPath:@"subviews.@count" options:0 context:nil];
    }
}

@end

Have your view extend this class. Of course this only ensures a subview is above all of its sibling views.

JavaScript seconds to time string with format hh:mm:ss

Variation on a theme. Handles single digit seconds a little differently

seconds2time(0)  ->  "0s" 
seconds2time(59) -> "59s" 
seconds2time(60) -> "1:00" 
seconds2time(1000) -> "16:40" 
seconds2time(4000) -> "1:06:40"

function seconds2time (seconds) {
    var hours   = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds - (hours * 3600)) / 60);
    var seconds = seconds - (hours * 3600) - (minutes * 60);
    var time = "";

    if (hours != 0) {
      time = hours+":";
    }
    if (minutes != 0 || time !== "") {
      minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
      time += minutes+":";
    }
    if (time === "") {
      time = seconds+"s";
    }
    else {
      time += (seconds < 10) ? "0"+seconds : String(seconds);
    }
    return time;
}

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

I solved it doing

run devenv /resetuserdata

in this path:

[x64] C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE

I assume that in x86 it works in this path:

[x86] C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE

How can I access the MySQL command line with XAMPP for Windows?

I had the same issue. Fistly, thats what i have :

  1. win 10
  2. xampp
  3. git bash

and i have done this to fix my problem :

  1. go to search box(PC)
  2. tape this environnement variable
  3. go to 'path' click 'edit'
  4. add this "%systemDrive%\xampp\mysql\bin\" C:\xampp\mysql\bin\
  5. click ok
  6. go to Git Bash and right click it and open it and run as administrator
  7. right this on your Git Bash winpty mysql -u root if your password is empty or winpty mysql -u root -p if you do have a password

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

For IOS 7 if you are allocing a tableview in a view controller you may look into

self.edgesForExtendedLayout = UIRectEdgeNone;

your problem seemed similar to mine

Update:

Swift in iOS 9.x:

self.edgesForExtendedLayout = UIRectEdge.None

Swift 3 :

self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)

Get name of currently executing test in JUnit 4

I'd suggest you decouple the test method name from your test data set. I would model a DataLoaderFactory class which loads/caches the sets of test data from your resources, and then in your test case cam call some interface method which returns a set of test data for the test case. Having the test data tied to the test method name assumes the test data can only be used once, where in most case i'd suggest that the same test data in uses in multiple tests to verify various aspects of your business logic.

Find a file in python

SARose's answer worked for me until I updated from Ubuntu 20.04 LTS. The slight change I made to his code makes it work on the latest Ubuntu release.

import subprocess

def find_files(file_name):
    command = ['locate'+ ' ' + file_name]
    output = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
    output = output.decode()
    search_results = output.split('\n')
    return search_results

How to add two edit text fields in an alert dialog

Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.

The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.

    public void showInput() {
        OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
            @Override
            public void onFocusChange(final View v, boolean hasFocus) {
                if (hasFocus) {
                    // Must use message queue to show keyboard
                    v.post(new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                            inputMethodManager.showSoftInput(v, 0);
                        }
                    });
                }
            }
        };

        final EditText editTextName = new EditText(this);
        editTextName.setHint("Name");
        editTextName.setFocusable(true);
        editTextName.setClickable(true);
        editTextName.setFocusableInTouchMode(true);
        editTextName.setSelectAllOnFocus(true);
        editTextName.setSingleLine(true);
        editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        editTextName.setOnFocusChangeListener(onFocusChangeListener);

        final EditText editTextPassword = new EditText(this);
        editTextPassword.setHint("Password");
        editTextPassword.setFocusable(true);
        editTextPassword.setClickable(true);
        editTextPassword.setFocusableInTouchMode(true);
        editTextPassword.setSelectAllOnFocus(true);
        editTextPassword.setSingleLine(true);
        editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
        editTextPassword.setOnFocusChangeListener(onFocusChangeListener);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(editTextName);
        linearLayout.addView(editTextPassword);

        DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    // Done button clicked
                    break;
                case DialogInterface.BUTTON_NEGATIVE:
                    // Cancel button clicked
                    break;
                }
            }
        };
        final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password")
                .setView(linearLayout)
                .setPositiveButton("Done", alertDialogClickListener)
                .setNegativeButton("Cancel", alertDialogClickListener)
                .create();

        editTextName.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                editTextPassword.requestFocus(); // Press Return to focus next one
                return false;
            }
        });
        editTextPassword.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // Press Return to invoke positive button on alertDialog.
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
                return false;
            }
        });

        // Must set password mode after creating alert dialog.
        editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
        editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        alertDialog.show();
    }

php $_GET and undefined index

I was having the same problem in localhost with xampp. Now I'm using this combination of parameters:

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

php.net: http://php.net/manual/pt_BR/function.error-reporting.php

How to execute shell command in Javascript

I don't know why the previous answers gave all sorts of complicated solutions. If you just want to execute a quick command like ls, you don't need async/await or callbacks or anything. Here's all you need - execSync:

const execSync = require('child_process').execSync;
// import { execSync } from 'child_process';  // replace ^ if using ES modules
const output = execSync('ls', { encoding: 'utf-8' });  // the default is 'buffer'
console.log('Output was:\n', output);

For error handling, add a try/catch block around the statement.

If you're running a command that takes a long time to complete, then yes, look at the asynchronous exec function.

How can I write an anonymous function in Java?

Yes if you are using latest java which is version 8. Java8 make it possible to define anonymous functions which was impossible in previous versions.

Lets take example from java docs to get know how we can declare anonymous functions, classes

The following example, HelloWorldAnonymousClasses, uses anonymous classes in the initialization statements of the local variables frenchGreeting and spanishGreeting, but uses a local class for the initialization of the variable englishGreeting:

public class HelloWorldAnonymousClasses {

    interface HelloWorld {
        public void greet();
        public void greetSomeone(String someone);
    }

    public void sayHello() {

        class EnglishGreeting implements HelloWorld {
            String name = "world";
            public void greet() {
                greetSomeone("world");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hello " + name);
            }
        }

        HelloWorld englishGreeting = new EnglishGreeting();

        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Salut " + name);
            }
        };

        HelloWorld spanishGreeting = new HelloWorld() {
            String name = "mundo";
            public void greet() {
                greetSomeone("mundo");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hola, " + name);
            }
        };
        englishGreeting.greet();
        frenchGreeting.greetSomeone("Fred");
        spanishGreeting.greet();
    }

    public static void main(String... args) {
        HelloWorldAnonymousClasses myApp =
            new HelloWorldAnonymousClasses();
        myApp.sayHello();
    }            
}

Syntax of Anonymous Classes

Consider the instantiation of the frenchGreeting object:

    HelloWorld frenchGreeting = new HelloWorld() {
        String name = "tout le monde";
        public void greet() {
            greetSomeone("tout le monde");
        }
        public void greetSomeone(String someone) {
            name = someone;
            System.out.println("Salut " + name);
        }
    };

The anonymous class expression consists of the following:

  • The new operator
  • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.

  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.

  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.

SVN checkout the contents of a folder, not the folder itself

Provide the directory on the command line:

svn checkout file:///home/landonwinters/svn/waterproject/trunk public_html

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

The time complexity of ArrayList.clear() is O(n) and of removeAll is O(n^2).

So yes, ArrayList.clear is much faster.

How to run jenkins as a different user

If you really want to run Jenkins as you, I suggest you check out my Jenkins.app. An alternative, easy way to run Jenkins on Mac.

See https://github.com/stisti/jenkins-app/

Download it from https://github.com/stisti/jenkins-app/downloads

MySQL equivalent of DECODE function in Oracle

The example translates directly to:

Select Name, CASE Age
       WHEN 13 then 'Thirteen' WHEN 14 then 'Fourteen' WHEN 15 then 'Fifteen' WHEN 16 then 'Sixteen'
       WHEN 17 then 'Seventeen' WHEN 18 then 'Eighteen' WHEN 19 then 'Nineteen'
       ELSE 'Adult' END AS AgeBracket
FROM Person

which you may prefer to format e.g. like this:

Select Name,
       CASE Age
         when 13 then 'Thirteen'
         when 14 then 'Fourteen'
         when 15 then 'Fifteen'
         when 16 then 'Sixteen'
         when 17 then 'Seventeen'
         when 18 then 'Eighteen'
         when 19 then 'Nineteen'
         else         'Adult'
       END AS AgeBracket
FROM Person

mysql alphabetical order

I try to sort data with query it working fine for me please try this:

select name from user order by name asc 

Also try below query for search record by alphabetically

SELECT name  FROM `user` WHERE `name` LIKE 'b%' 

INSERT ... ON DUPLICATE KEY (do nothing)

Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id (it won't trigger row update even though id is assigned to itself).

If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE.

Comprehensive beginner's virtualenv tutorial?

Virtualenv is a tool to create isolated Python environments.

Let's say you're working in 2 different projects, A and B. Project A is a web project and the team is using the following packages:

  • Python 2.8.x
  • Django 1.6.x

The project B is also a web project but your team is using:

  • Python 2.7.x
  • Django 1.4.x

The machine that you're working doesn't have any version of django, what should you do? Install django 1.4? django 1.6? If you install django 1.4 globally would be easy to point to django 1.6 to work in project A?

Virtualenv is your solution! You can create 2 different virtualenv's, one for project A and another for project B. Now, when you need to work in project A, just activate the virtualenv for project A, and vice-versa.

A better tip when using virtualenv is to install virtualenvwrapper to manage all the virtualenv's that you have, easily. It's a wrapper for creating, working, removing virtualenv's.

How to read a file into a variable in shell?

With bash you may use read like tis:

#!/usr/bin/env bash

{ IFS= read -rd '' value <config.txt;} 2>/dev/null

printf '%s' "$value"

Notice that:

  • The last newline is preserved.

  • The stderr is silenced to /dev/null by redirecting the whole commands block, but the return status of the read command is preserved, if one needed to handle read error conditions.

How can I get the corresponding table header (th) from a table cell (td)?

Find matching th for a td, taking into account colspan index issues.

_x000D_
_x000D_
$('table').on('click', 'td', get_TH_by_TD)_x000D_
_x000D_
function get_TH_by_TD(e){_x000D_
   var idx = $(this).index(),_x000D_
       th, th_colSpan = 0;_x000D_
_x000D_
   for( var i=0; i < this.offsetParent.tHead.rows[0].cells.length; i++ ){_x000D_
      th = this.offsetParent.tHead.rows[0].cells[i];_x000D_
      th_colSpan += th.colSpan;_x000D_
      if( th_colSpan >= (idx + this.colSpan) )_x000D_
        break;_x000D_
   }_x000D_
   _x000D_
   console.clear();_x000D_
   console.log( th );_x000D_
   return th;_x000D_
}
_x000D_
table{ width:100%; }_x000D_
th, td{ border:1px solid silver; padding:5px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>Click a TD:</p>_x000D_
<table>_x000D_
    <thead> _x000D_
        <tr>_x000D_
            <th colspan="2"></th>_x000D_
            <th>Name</th>_x000D_
            <th colspan="2">Address</th>_x000D_
            <th colspan="2">Other</th>_x000D_
        </tr>_x000D_
    </thead> _x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>X</td>_x000D_
            <td>1</td>_x000D_
            <td>Jon Snow</td>_x000D_
            <td>12</td>_x000D_
            <td>High Street</td>_x000D_
            <td>Postfix</td>_x000D_
            <td>Public</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to save LogCat contents to file?

You are not getting the answer you are looking for, are you.

Two ways to do what you want:

  1. Right-click in the logcat messages window, choose select all. Then your save will be all logcat messages in that window (including the ones scrolled out of view).
  2. When focus is in logcat messages window, type control-A, this will select all messages. Then save etc. etc.

Using Spring 3 autowire in a standalone Java application

Spring is moving away from XML files and uses annotations heavily. The following example is a simple standalone Spring application which uses annotation instead of XML files.

package com.zetcode.bean;

import org.springframework.stereotype.Component;

@Component
public class Message {

   private String message = "Hello there!";

   public void setMessage(String message){

      this.message  = message;
   }

   public String getMessage(){

      return message;
   }
}

This is a simple bean. It is decorated with the @Component annotation for auto-detection by Spring container.

package com.zetcode.main;

import com.zetcode.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.zetcode")
public class Application {

    public static void main(String[] args) {

        ApplicationContext context
                = new AnnotationConfigApplicationContext(Application.class);

        Application p = context.getBean(Application.class);
        p.start();
    }

    @Autowired
    private Message message;
    private void start() {
        System.out.println("Message: " + message.getMessage());
    }
}

This is the main Application class. The @ComponentScan annotation searches for components. The @Autowired annotation injects the bean into the message variable. The AnnotationConfigApplicationContext is used to create the Spring application context.

My Standalone Spring tutorial shows how to create a standalone Spring application with both XML and annotations.

Automatically start forever (node) on system restart

I would suggest using crontab. It's easy to use.

How to

  1. To start editing run the following replacing the "testuser" with your desired runtime user for the node process. If you choose a different user other than yourself, you will have to run this with sudo.

    $ crontab -u testuser -e
    
  2. If you have never done this before, it will ask you which editor you wish to edit with. I like vim, but will recommend nano for ease of use.

  3. Once in the editor add the following line:

    @reboot /usr/local/bin/forever start /your/path/to/your/app.js
    
  4. Save the file. You should get some feedback that the cron has been installed.

  5. For further confirmation of the installation of the cron, execute the following (again replacing "testuser" with your target username) to list the currently installed crons:

    $ crontab -u testuser -l 
    

Note that in my opinion, you should always use full paths when executing binaries in cron. Also, if the path to your forever script is not correct, run which forever to get the full path.

Given that forever calls node, you may also want to provide the full path to node:

@reboot /usr/local/bin/forever start -c /usr/local/bin/node /your/path/to/your/app.js

Further Reading

Is there a program to decompile Delphi?

Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.

So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.

Check if list<t> contains any of another list

You could use a nested Any() for this check which is available on any Enumerable:

bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));

Faster performing on larger collections would be to project parameters to source and then use Intersect which internally uses a HashSet<T> so instead of O(n^2) for the first approach (the equivalent of two nested loops) you can do the check in O(n) :

bool hasMatch = parameters.Select(x => x.source)
                          .Intersect(myStrings)
                          .Any(); 

Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.

Set value for particular cell in pandas DataFrame with iloc

Extending Jianxun's answer, using set_value mehtod in pandas. It sets value for a column at given index.

From pandas documentations:

DataFrame.set_value(index, col, value)

To set value at particular index for a column, do:

df.set_value(index, 'COL_NAME', x)

Hope it helps.

ORA-01843 not a valid month- Comparing Dates

If the source date contains minutes and seconds part, your date comparison will fail. you need to convert source date to the required format using to_char and the target date also.

convert a list of objects from one type to another using lambda expression

List<target> targetList = new List<target>(originalList.Cast<target>());

Are multiple `.gitignore`s frowned on?

There are many scenarios where you want to commit a directory to your Git repo but without the files in it, for example the logs, cache, uploads directories etc.

So what I always do is to add a .gitignore file in those directories with the following content:

*
!.gitignore

With this .gitignore file, Git will not track any files in those directories yet still allow me to add the .gitignore file and hence the directory itself to the repo.

How to properly exit a C# application?

Do you do:

Application.Run(myForm);

in your Main()?

I found it a very easy way to kill the application when the form is closed.

How can I rollback a git repository to a specific commit?

When doing branch updates from master, I notice that I sometimes over-click, and cause the branch to merge into the master, too. Found a way to undo that.

If your last commit was a merge, a little more love is needed:

git revert -m 1 HEAD

What is the difference between React Native and React?

React Native is a JavaScript framework and it comes with everything you need to write multi-platform apps (like iOS or Android).

ReactJS is a JavaScript library which is used to build web interfaces and build your website.

How do I get the key at a specific index from a Dictionary in Swift?

In Swift 3 try to use this code to get Key-Value Pair (tuple) at given index:

extension Dictionary {
    subscript(i:Int) -> (key:Key,value:Value) {
        get {
            return self[index(startIndex, offsetBy: i)];
        }
    }
}

Set background image according to screen resolution

Set body css to :

body { 
background: url(../img/background.jpg) no-repeat center center fixed #000; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

}

Python Inverse of a Matrix

For those like me, who were looking for a pure Python solution without pandas or numpy involved, check out the following GitHub project: https://github.com/ThomIves/MatrixInverse.

It generously provides a very good explanation of how the process looks like "behind the scenes". The author has nicely described the step-by-step approach and presented some practical examples, all easy to follow.

This is just a little code snippet from there to illustrate the approach very briefly (AM is the source matrix, IM is the identity matrix of the same size):

def invert_matrix(AM, IM):
    for fd in range(len(AM)):
        fdScaler = 1.0 / AM[fd][fd]
        for j in range(len(AM)):
            AM[fd][j] *= fdScaler
            IM[fd][j] *= fdScaler
        for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
            crScaler = AM[i][fd]
            for j in range(len(AM)):
                AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
                IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
    return IM

But please do follow the entire thing, you'll learn a lot more than just copy-pasting this code! There's a Jupyter notebook as well, btw.

Hope that helps someone, I personally found it extremely useful for my very particular task (Absorbing Markov Chain) where I wasn't able to use any non-standard packages.

What is the best way to auto-generate INSERT statements for a SQL Server table?

As mentioned by @Mike Ritacco but updated for SSMS 2008 R2

  1. Right click on the database name
  2. Choose Tasks > Generate scripts
  3. Depending on your settings the intro page may show or not
  4. Choose 'Select specific database objects',
  5. Expand the tree view and check the relevant tables
  6. Click Next
  7. Click Advanced
  8. Under General section, choose the appropriate option for 'Types of data to script'
  9. Complete the wizard

You will then get all of the INSERT statements for the data straight out of SSMS.

EDIT 2016-10-25 SQL Server 2016/SSMS 13.0.15900.1

  1. Right click on the database name

  2. Choose Tasks > Generate scripts

  3. Depending on your settings the intro page may show or not

  4. Choose 'Select specific database objects',

  5. Expand the tree view and check the relevant tables

  6. Click Next

  7. Click Advanced

  8. Under General section, choose the appropriate option for 'Types of data to script'

  9. Click OK

  10. Pick whether you want the output to go to a new query, the clipboard or a file

  11. Click Next twice

  12. Your script is prepared in accordance with the settings you picked above

  13. Click Finish

How can I pretty-print JSON using Go?

The accepted answer is great if you have an object you want to turn into JSON. The question also mentions pretty-printing just any JSON string, and that's what I was trying to do. I just wanted to pretty-log some JSON from a POST request (specifically a CSP violation report).

To use MarshalIndent, you would have to Unmarshal that into an object. If you need that, go for it, but I didn't. If you just need to pretty-print a byte array, plain Indent is your friend.

Here's what I ended up with:

import (
    "bytes"
    "encoding/json"
    "log"
    "net/http"
)

func HandleCSPViolationRequest(w http.ResponseWriter, req *http.Request) {
    body := App.MustReadBody(req, w)
    if body == nil {
        return
    }

    var prettyJSON bytes.Buffer
    error := json.Indent(&prettyJSON, body, "", "\t")
    if error != nil {
        log.Println("JSON parse error: ", error)
        App.BadRequest(w)
        return
    }

    log.Println("CSP Violation:", string(prettyJSON.Bytes()))
}

How to display div after click the button in Javascript?

HTML

<div id="myDiv" style="display:none;" class="answer_list" >WELCOME</div>
<input type="button" name="answer" onclick="ShowDiv()" />

JavaScript

function ShowDiv() {
    document.getElementById("myDiv").style.display = "";
}

Or if you wanted to use jQuery with a nice little animation:

<input id="myButton" type="button" name="answer" />

$('#myButton').click(function() {
  $('#myDiv').toggle('slow', function() {
    // Animation complete.
  });
});

How to destroy a DOM element with jQuery?

If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...

console.log($target);   // jQuery object
$target.remove();       // remove target from the DOM
console.log($target);   // $target still exists

Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)

$target = $();
console.log($target);   // empty jQuery object

Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)

delete $target;
console.log($target);   // error: $target is not defined

More reading: info about empty jQuery object, and info about delete

How can I run a PHP script in the background after a form is submitted?

And why not making a HTTP Request on the script and ignoring the response ?

http://php.net/manual/en/function.httprequest-send.php

If you make your request on the script you need to call your webserver will run it in background and you can (in your main script) show a message telling the user that the script is running.

How can I run MongoDB as a Windows service?

Consider using

mongod --install --rest --master

HTML Upload MAX_FILE_SIZE does not appear to work

There IS A POINT in introducing MAX_FILE_SIZE client side hidden form field.

php.ini can limit uploaded file size. So, while your script honors the limit imposed by php.ini, different HTML forms can further limit an uploaded file size. So, when uploading video, form may limit* maximum size to 10MB, and while uploading photos, forms may put a limit of just 1mb. And at the same time, the maximum limit can be set in php.ini to suppose 10mb to allow all this.

Although this is not a fool proof way of telling the server what to do, yet it can be helpful.

  • HTML does'nt limit anything. It just forwards the server all form variable including MAX_FILE_SIZE and its value.

Hope it helped someone.

SQL: How to perform string does not equal

select * from table
where tester NOT LIKE '%username%';

How can I regenerate ios folder in React Native project?

The process you need to follow is so similar to renaming a react native app. Basically you just need to run react-native upgrade in your root project directory. For further info you can check another question here. The instructions below explains how to create another react native project based on a copied one with a new name.

  • First copy the directory which your to-be-name-changed application exists. And go to your newly cloned directory.
  • Change the name at index.ios/android.js file which is given as a parameter to AppRegistry.
  • Change the name and version accordingly on package.json
  • Delete /ios and /android folders which are remaining from your older app.
  • Run $react-native upgrade to generate /ios and /android folders again.
  • Run $react-native link for any native dependency.
  • Finally run $react-native run-ios or anything you want.

How to select the last record of a table in SQL?

$sql="SELECT tot_visit FROM visitors WHERE date = DATE(NOW()) - 1 into @s                
$conn->query($sql);
$sql = "INSERT INTO visitors (nbvisit_day,date,tot_visit) VALUES (1,CURRENT_DATE,@s+1)";
$conn->query($sql);

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

Below solution is a clean work around.It does not compromises security because we are using same strict firewall.

The Steps for fixing is as below:

STEP 1 : Create a Class overriding StrictHttpFirewall as below.

package com.biz.brains.project.security.firewall;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpMethod;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedException;

public class CustomStrictHttpFirewall implements HttpFirewall {
    private static final Set<String> ALLOW_ANY_HTTP_METHOD = Collections.unmodifiableSet(Collections.emptySet());

    private static final String ENCODED_PERCENT = "%25";

    private static final String PERCENT = "%";

    private static final List<String> FORBIDDEN_ENCODED_PERIOD = Collections.unmodifiableList(Arrays.asList("%2e", "%2E"));

    private static final List<String> FORBIDDEN_SEMICOLON = Collections.unmodifiableList(Arrays.asList(";", "%3b", "%3B"));

    private static final List<String> FORBIDDEN_FORWARDSLASH = Collections.unmodifiableList(Arrays.asList("%2f", "%2F"));

    private static final List<String> FORBIDDEN_BACKSLASH = Collections.unmodifiableList(Arrays.asList("\\", "%5c", "%5C"));

    private Set<String> encodedUrlBlacklist = new HashSet<String>();

    private Set<String> decodedUrlBlacklist = new HashSet<String>();

    private Set<String> allowedHttpMethods = createDefaultAllowedHttpMethods();

    public CustomStrictHttpFirewall() {
        urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
        urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
        urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);

        this.encodedUrlBlacklist.add(ENCODED_PERCENT);
        this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
        this.decodedUrlBlacklist.add(PERCENT);
    }

    public void setUnsafeAllowAnyHttpMethod(boolean unsafeAllowAnyHttpMethod) {
        this.allowedHttpMethods = unsafeAllowAnyHttpMethod ? ALLOW_ANY_HTTP_METHOD : createDefaultAllowedHttpMethods();
    }

    public void setAllowedHttpMethods(Collection<String> allowedHttpMethods) {
        if (allowedHttpMethods == null) {
            throw new IllegalArgumentException("allowedHttpMethods cannot be null");
        }
        if (allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
            this.allowedHttpMethods = ALLOW_ANY_HTTP_METHOD;
        } else {
            this.allowedHttpMethods = new HashSet<>(allowedHttpMethods);
        }
    }

    public void setAllowSemicolon(boolean allowSemicolon) {
        if (allowSemicolon) {
            urlBlacklistsRemoveAll(FORBIDDEN_SEMICOLON);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
        }
    }

    public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
        if (allowUrlEncodedSlash) {
            urlBlacklistsRemoveAll(FORBIDDEN_FORWARDSLASH);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
        }
    }

    public void setAllowUrlEncodedPeriod(boolean allowUrlEncodedPeriod) {
        if (allowUrlEncodedPeriod) {
            this.encodedUrlBlacklist.removeAll(FORBIDDEN_ENCODED_PERIOD);
        } else {
            this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
        }
    }

    public void setAllowBackSlash(boolean allowBackSlash) {
        if (allowBackSlash) {
            urlBlacklistsRemoveAll(FORBIDDEN_BACKSLASH);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
        }
    }

    public void setAllowUrlEncodedPercent(boolean allowUrlEncodedPercent) {
        if (allowUrlEncodedPercent) {
            this.encodedUrlBlacklist.remove(ENCODED_PERCENT);
            this.decodedUrlBlacklist.remove(PERCENT);
        } else {
            this.encodedUrlBlacklist.add(ENCODED_PERCENT);
            this.decodedUrlBlacklist.add(PERCENT);
        }
    }

    private void urlBlacklistsAddAll(Collection<String> values) {
        this.encodedUrlBlacklist.addAll(values);
        this.decodedUrlBlacklist.addAll(values);
    }

    private void urlBlacklistsRemoveAll(Collection<String> values) {
        this.encodedUrlBlacklist.removeAll(values);
        this.decodedUrlBlacklist.removeAll(values);
    }

    @Override
    public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
        rejectForbiddenHttpMethod(request);
        rejectedBlacklistedUrls(request);

        if (!isNormalized(request)) {
            request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL was not normalized."));
        }

        String requestUri = request.getRequestURI();
        if (!containsOnlyPrintableAsciiCharacters(requestUri)) {
            request.setAttribute("isNormalized",  new RequestRejectedException("The requestURI was rejected because it can only contain printable ASCII characters."));
        }
        return new FirewalledRequest(request) {
            @Override
            public void reset() {
            }
        };
    }

    private void rejectForbiddenHttpMethod(HttpServletRequest request) {
        if (this.allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
            return;
        }
        if (!this.allowedHttpMethods.contains(request.getMethod())) {
            request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the HTTP method \"" +
                    request.getMethod() +
                    "\" was not included within the whitelist " +
                    this.allowedHttpMethods));
        }
    }

    private void rejectedBlacklistedUrls(HttpServletRequest request) {
        for (String forbidden : this.encodedUrlBlacklist) {
            if (encodedUrlContains(request, forbidden)) {
                request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
            }
        }
        for (String forbidden : this.decodedUrlBlacklist) {
            if (decodedUrlContains(request, forbidden)) {
                request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
            }
        }
    }

    @Override
    public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
        return new FirewalledResponse(response);
    }

    private static Set<String> createDefaultAllowedHttpMethods() {
        Set<String> result = new HashSet<>();
        result.add(HttpMethod.DELETE.name());
        result.add(HttpMethod.GET.name());
        result.add(HttpMethod.HEAD.name());
        result.add(HttpMethod.OPTIONS.name());
        result.add(HttpMethod.PATCH.name());
        result.add(HttpMethod.POST.name());
        result.add(HttpMethod.PUT.name());
        return result;
    }

    private static boolean isNormalized(HttpServletRequest request) {
        if (!isNormalized(request.getRequestURI())) {
            return false;
        }
        if (!isNormalized(request.getContextPath())) {
            return false;
        }
        if (!isNormalized(request.getServletPath())) {
            return false;
        }
        if (!isNormalized(request.getPathInfo())) {
            return false;
        }
        return true;
    }

    private static boolean encodedUrlContains(HttpServletRequest request, String value) {
        if (valueContains(request.getContextPath(), value)) {
            return true;
        }
        return valueContains(request.getRequestURI(), value);
    }

    private static boolean decodedUrlContains(HttpServletRequest request, String value) {
        if (valueContains(request.getServletPath(), value)) {
            return true;
        }
        if (valueContains(request.getPathInfo(), value)) {
            return true;
        }
        return false;
    }

    private static boolean containsOnlyPrintableAsciiCharacters(String uri) {
        int length = uri.length();
        for (int i = 0; i < length; i++) {
            char c = uri.charAt(i);
            if (c < '\u0020' || c > '\u007e') {
                return false;
            }
        }

        return true;
    }

    private static boolean valueContains(String value, String contains) {
        return value != null && value.contains(contains);
    }

    private static boolean isNormalized(String path) {
        if (path == null) {
            return true;
        }

        if (path.indexOf("//") > -1) {
            return false;
        }

        for (int j = path.length(); j > 0;) {
            int i = path.lastIndexOf('/', j - 1);
            int gap = j - i;

            if (gap == 2 && path.charAt(i + 1) == '.') {
                // ".", "/./" or "/."
                return false;
            } else if (gap == 3 && path.charAt(i + 1) == '.' && path.charAt(i + 2) == '.') {
                return false;
            }

            j = i;
        }

        return true;
    }

}

STEP 2 : Create a FirewalledResponse class

package com.biz.brains.project.security.firewall;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

class FirewalledResponse extends HttpServletResponseWrapper {
    private static final Pattern CR_OR_LF = Pattern.compile("\\r|\\n");
    private static final String LOCATION_HEADER = "Location";
    private static final String SET_COOKIE_HEADER = "Set-Cookie";

    public FirewalledResponse(HttpServletResponse response) {
        super(response);
    }

    @Override
    public void sendRedirect(String location) throws IOException {
        // TODO: implement pluggable validation, instead of simple blacklisting.
        // SEC-1790. Prevent redirects containing CRLF
        validateCrlf(LOCATION_HEADER, location);
        super.sendRedirect(location);
    }

    @Override
    public void setHeader(String name, String value) {
        validateCrlf(name, value);
        super.setHeader(name, value);
    }

    @Override
    public void addHeader(String name, String value) {
        validateCrlf(name, value);
        super.addHeader(name, value);
    }

    @Override
    public void addCookie(Cookie cookie) {
        if (cookie != null) {
            validateCrlf(SET_COOKIE_HEADER, cookie.getName());
            validateCrlf(SET_COOKIE_HEADER, cookie.getValue());
            validateCrlf(SET_COOKIE_HEADER, cookie.getPath());
            validateCrlf(SET_COOKIE_HEADER, cookie.getDomain());
            validateCrlf(SET_COOKIE_HEADER, cookie.getComment());
        }
        super.addCookie(cookie);
    }

    void validateCrlf(String name, String value) {
        if (hasCrlf(name) || hasCrlf(value)) {
            throw new IllegalArgumentException(
                    "Invalid characters (CR/LF) in header " + name);
        }
    }

    private boolean hasCrlf(String value) {
        return value != null && CR_OR_LF.matcher(value).find();
    }
}

STEP 3: Create a custom Filter to suppress the RejectedException

package com.biz.brains.project.security.filter;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestRejectedExceptionFilter extends GenericFilterBean {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            try {
                RequestRejectedException requestRejectedException=(RequestRejectedException) servletRequest.getAttribute("isNormalized");
                if(Objects.nonNull(requestRejectedException)) {
                    throw requestRejectedException;
                }else {
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            } catch (RequestRejectedException requestRejectedException) {
                HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                log
                    .error(
                            "request_rejected: remote={}, user_agent={}, request_url={}",
                            httpServletRequest.getRemoteHost(),  
                            httpServletRequest.getHeader(HttpHeaders.USER_AGENT),
                            httpServletRequest.getRequestURL(), 
                            requestRejectedException
                    );

                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
}

STEP 4: Add the custom filter to spring filter chain in security configuration

@Override
protected void configure(HttpSecurity http) throws Exception {
     http.addFilterBefore(new RequestRejectedExceptionFilter(),
             ChannelProcessingFilter.class);
}

Now using above fix, we can handle RequestRejectedException with Error 404 page.

MySQL INSERT INTO ... VALUES and SELECT

try this

INSERT INTO TABLE1 (COL1 , COL2,COL3) values
('A STRING' , 5 , (select idTable2 from Table2) )
where ...

Fastest way to check if a value exists in a list

Because the question is not always supposed to be understood as the fastest technical way - I always suggest the most straightforward fastest way to understand/write: a list comprehension, one-liner

[i for i in list_from_which_to_search if i in list_to_search_in]

I had a list_to_search_in with all the items, and wanted to return the indexes of the items in the list_from_which_to_search.

This returns the indexes in a nice list.

There are other ways to check this problem - however list comprehensions are quick enough, adding to the fact of writing it quick enough, to solve a problem.

How do I detect what .NET Framework versions and service packs are installed?

The Framework 4 beta installs to a differing registry key.

using System;
using System.Collections.ObjectModel;
using Microsoft.Win32;

class Program
{
    static void Main(string[] args)
    {
        foreach(Version ver in InstalledDotNetVersions())
            Console.WriteLine(ver);

        Console.ReadKey();
    }


    public static Collection<Version> InstalledDotNetVersions()
    {
        Collection<Version> versions = new Collection<Version>();
        RegistryKey NDPKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
        if (NDPKey != null)
        {
            string[] subkeys = NDPKey.GetSubKeyNames();
            foreach (string subkey in subkeys)
            {
                GetDotNetVersion(NDPKey.OpenSubKey(subkey), subkey, versions);
                GetDotNetVersion(NDPKey.OpenSubKey(subkey).OpenSubKey("Client"), subkey, versions);
                GetDotNetVersion(NDPKey.OpenSubKey(subkey).OpenSubKey("Full"), subkey, versions);
            }
        }
        return versions;
    }

    private static void GetDotNetVersion(RegistryKey parentKey, string subVersionName, Collection<Version> versions)
    {
        if (parentKey != null)
        {
            string installed = Convert.ToString(parentKey.GetValue("Install"));
            if (installed == "1")
            {
                string version = Convert.ToString(parentKey.GetValue("Version"));
                if (string.IsNullOrEmpty(version))
                {
                    if (subVersionName.StartsWith("v"))
                        version = subVersionName.Substring(1);
                    else
                        version = subVersionName;
                }

                Version ver = new Version(version);

                if (!versions.Contains(ver))
                    versions.Add(ver);
            }
        }
    }
}

what exactly is device pixel ratio?

Short answer

The device pixel ratio is the ratio between physical pixels and logical pixels. For instance, the iPhone 4 and iPhone 4S report a device pixel ratio of 2, because the physical linear resolution is double the logical linear resolution.

  • Physical resolution: 960 x 640
  • Logical resolution: 480 x 320

The formula is:

linres_p/linres_l

Where:

linres_p is the physical linear resolution

and:

linres_l is the logical linear resolution

Other devices report different device pixel ratios, including non-integer ones. For example, the Nokia Lumia 1020 reports 1.6667, the Samsumg Galaxy S4 reports 3, and the Apple iPhone 6 Plus reports 2.46 (source: dpilove). But this does not change anything in principle, as you should never design for any one specific device.

Discussion

The CSS "pixel" is not even defined as "one picture element on some screen", but rather as a non-linear angular measurement of 0.0213° viewing angle, which is approximately 1/96 of an inch at arm's length. Source: CSS Absolute Lengths

This has lots of implications when it comes to web design, such as preparing high-definition image resources and carefully applying different images at different device pixel ratios. You wouldn't want to force a low-end device to download a very high resolution image, only to downscale it locally. You also don't want high-end devices to upscale low resolution images for a blurry user experience.

If you are stuck with bitmap images, to accommodate for many different device pixel ratios, you should use CSS Media Queries to provide different sets of resources for different groups of devices. Combine this with nice tricks like background-size: cover or explicitly set the background-size to percentage values.

Example

#element { background-image: url('lores.png'); }

@media only screen and (min-device-pixel-ratio: 2) {
    #element { background-image: url('hires.png'); }
}

@media only screen and (min-device-pixel-ratio: 3) {
    #element { background-image: url('superhires.png'); }
}

This way, each device type only loads the correct image resource. Also keep in mind that the px unit in CSS always operates on logical pixels.

A case for vector graphics

As more and more device types appear, it gets trickier to provide all of them with adequate bitmap resources. In CSS, media queries is currently the only way, and in HTML5, the picture element lets you use different sources for different media queries, but the support is still not 100 % since most web developers still have to support IE11 for a while more (source: caniuse).

If you need crisp images for icons, line-art, design elements that are not photos, you need to start thinking about SVG, which scales beautifully to all resolutions.

How do I resolve "Cannot find module" error using Node.js?

I had a very similar issue. Removing the entire node_modules folder and re-installing worked for me:

rm -rf node_modules
npm install

How does a Java HashMap handle different objects with the same hash code?

As it is said, a picture is worth 1000 words. I say: some code is better than 1000 words. Here's the source code of HashMap. Get method:

/**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

So it becomes clear that hash is used to find the "bucket" and the first element is always checked in that bucket. If not, then equals of the key is used to find the actual element in the linked list.

Let's see the put() method:

  /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

It's slightly more complicated, but it becomes clear that the new element is put in the tab at the position calculated based on hash:

i = (n - 1) & hash here i is the index where the new element will be put (or it is the "bucket"). n is the size of the tab array (array of "buckets").

First, it is tried to be put as the first element of in that "bucket". If there is already an element, then append a new node to the list.

Python strip() multiple characters?

I did a time test here, using each method 100000 times in a loop. The results surprised me. (The results still surprise me after editing them in response to valid criticism in the comments.)

Here's the script:

import timeit

bad_chars = '(){}<>'

setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""

timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ",  timer.timeit(100000)


timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)

timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)

timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)

Here are the results:

List comprehension:  0.631745100021
Regular expression:  0.155561923981
Replace in loop:  0.235936164856
string.translate:  0.0965719223022

Results on other runs follow a similar pattern. If speed is not the primary concern, however, I still think string.translate is not the most readable; the other three are more obvious, though slower to varying degrees.

print call stack in C or C++

Another answer to an old thread.

When I need to do this, I usually just use system() and pstack

So something like this:

#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <sstream>
#include <cstdlib>

void f()
{
    pid_t myPid = getpid();
    std::string pstackCommand = "pstack ";
    std::stringstream ss;
    ss << myPid;
    pstackCommand += ss.str();
    system(pstackCommand.c_str());
}

void g()
{
   f();
}


void h()
{
   g();
}

int main()
{
   h();
}

This outputs

#0  0x00002aaaab62d61e in waitpid () from /lib64/libc.so.6
#1  0x00002aaaab5bf609 in do_system () from /lib64/libc.so.6
#2  0x0000000000400c3c in f() ()
#3  0x0000000000400cc5 in g() ()
#4  0x0000000000400cd1 in h() ()
#5  0x0000000000400cdd in main ()

This should work on Linux, FreeBSD and Solaris. I don't think that macOS has pstack or a simple equivalent, but this thread seems to have an alternative.

If you are using C, then you will need to use C string functions.

#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

void f()
{
    pid_t myPid = getpid();
    /*
      length of command 7 for 'pstack ', 7 for the PID, 1 for nul
    */
    char pstackCommand[7+7+1];
    sprintf(pstackCommand, "pstack %d", (int)myPid);
    system(pstackCommand);
}

I've used 7 for the max number of digits in the PID, based on this post.

Vue.js data-bind style backgroundImage not working

Binding background image style using a dynamic value from v-for loop could be done like this.

<div v-for="i in items" :key="n" 
  :style="{backgroundImage: 'url('+require('./assets/cars/'+i.src+'.jpg')+')'}">
</div>

Converting A String To Hexadecimal In Java

First convert it into bytes using getBytes() function and then convert it into hex usign this :

private static String hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<bytes.length; i++) {
        sb.append(String.format("%02X ",bytes[i]));
    }
    return sb.toString();
}

Regular expression to return text between parenthesis

contents_re = re.match(r'[^\(]*\((?P<contents>[^\(]+)\)', data)
if contents_re:
    print(contents_re.groupdict()['contents'])

Simplest Way to Test ODBC on WIndows

One way to create a quick test query in Windows via an ODBC connection is using the DQY format.

To achieve this, create a DQY file (e.g. test.dqy) containing the magic first two lines (XLODBC and 1) as below, followed by your ODBC connection string on the third line and your query on the fourth line (all on one line), e.g.:

XLODBC
1
Driver={Microsoft ODBC for Oracle};server=DB;uid=scott;pwd=tiger;
SELECT COUNT(1) n FROM emp

Then, if you open the file by double-clicking it, it will open in Excel and populate the worksheet with the results of the query.

ASP.NET MVC get textbox input value

You may use jQuery:

<input type="text" name="IP" id="IP" value=""/>
@Html.ActionLink(@Resource.ButtonTitleAdd, "Add", "Configure", new { ipValue ="xxx", TypeId = "1" }, new {@class = "link"})

<script>
  $(function () {
    $('.link').click(function () {
      var ipvalue = $("#IP").val();
      this.href = this.href.replace("xxx", ipvalue);
    });
  });
</script>

Asynchronously wait for Task<T> to complete with timeout

How about this:

int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
    // task completed within timeout
} else { 
    // timeout logic
}

And here's a great blog post "Crafting a Task.TimeoutAfter Method" (from MS Parallel Library team) with more info on this sort of thing.

Addition: at the request of a comment on my answer, here is an expanded solution that includes cancellation handling. Note that passing cancellation to the task and the timer means that there are multiple ways cancellation can be experienced in your code, and you should be sure to test for and be confident you properly handle all of them. Don't leave to chance various combinations and hope your computer does the right thing at runtime.

int timeout = 1000;
var task = SomeOperationAsync(cancellationToken);
if (await Task.WhenAny(task, Task.Delay(timeout, cancellationToken)) == task)
{
    // Task completed within timeout.
    // Consider that the task may have faulted or been canceled.
    // We re-await the task so that any exceptions/cancellation is rethrown.
    await task;

}
else
{
    // timeout/cancellation logic
}

Python Checking a string's first and last character

You should either use

if str1[0] == '"' and str1[-1] == '"'

or

if str1.startswith('"') and str1.endswith('"')

but not slice and check startswith/endswith together, otherwise you'll slice off what you're looking for...

How to calculate sum of a formula field in crystal Reports?

(Assuming you are looking at the reports in the Crystal Report Designer...)

Your menu options might be a little different depending on the version of Crystal Reports you're using, but you can either:

  • Make a summary field: Right-click on the desired formula field in your detail section and choose "Insert Summary". Choose "sum" from the drop-down box and verify that the correct account grouping is selected, then click OK. You will then have a simple sum field in your group footer section.
  • Make a running total field: Click on the "Insert" menu and choose "Running Total Field..."*** Click on the New button and give your new running total field a name. Choose your formula field under "Field to summarize" and choose "sum" under "Type of Summary". Here you can also change when the total is evaluated and reset, leave these at their default if you're wanting a sum on each record. You can also use a formula to determine when a certain field should be counted in the total. (Evaluate: Use Formula)

PHP file_get_contents() and setting request headers

Using the php cURL libraries will probably be the right way to go, as this library has more features than the simple file_get_contents(...).

An example:

<?php
$ch = curl_init();
$headers = array('HTTP_ACCEPT: Something', 'HTTP_ACCEPT_LANGUAGE: fr, en, da, nl', 'HTTP_CONNECTION: Something');

curl_setopt($ch, CURLOPT_URL, "http://localhost"); # URL to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
curl_setopt($ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above
$result = curl_exec( $ch ); # run!
curl_close($ch);
?>

The service cannot accept control messages at this time

I killed related w3wp.exe (on a friends' advise) at task manager and it worked.

Note: Use at your own risk. Be careful picking which one to kill.

CSS z-index not working (position absolute)

This is because of the Stacking Context, setting a z-index will make it apply to all children as well.

You could make the two <div>s siblings instead of descendants.

<div class="absolute"></div>
<div id="relative"></div>

http://jsfiddle.net/P7c9q/3/

dynamically add and remove view to viewpager

I've created a custom PagerAdapters library to change items in PagerAdapters dynamically.

You can change items dynamically like following by using this library.

@Override
protected void onCreate(Bundle savedInstanceState) {
        /** ... **/
    adapter = new MyStatePagerAdapter(getSupportFragmentManager()
                            , new String[]{"1", "2", "3"});
    ((ViewPager)findViewById(R.id.view_pager)).setAdapter(adapter);
     adapter.add("4");
     adapter.remove(0);
}

class MyPagerAdapter extends ArrayViewPagerAdapter<String> {

    public MyPagerAdapter(String[] data) {
        super(data);
    }

    @Override
    public View getView(LayoutInflater inflater, ViewGroup container, String item, int position) {
        View v = inflater.inflate(R.layout.item_page, container, false);
        ((TextView) v.findViewById(R.id.item_txt)).setText(item);
        return v;
    }
}

Thils library also support pages created by Fragments.

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

I read somewhere else that you can try - catch java.lang.OutOfMemoryError and on the catch block, you can free all resources that you know might use a lot of memory, close connections and so forth, then do a System.gc() then re-try whatever you were going to do.

Another way is this although, i don't know whether this would work, but I am currently testing whether it will work on my application.

The Idea is to do Garbage collection by calling System.gc() which is known to increase free memory. You can keep checking this after a memory gobbling code executes.

//Mimimum acceptable free memory you think your app needs
long minRunningMemory = (1024*1024);

Runtime runtime = Runtime.getRuntime();

if(runtime.freeMemory()<minRunningMemory)
 System.gc();

How do I decompile a .NET EXE into readable C# source code?

Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.

ADDED: My latest favourite is JetBrains' dotPeek.

Creating a .dll file in C#.Net

You need to change project settings. Right click your project, go to properites. In Application tab change output type to class library instead of Windows application.

How to set focus on input field?

You could just create a directive that forces focus on the decorated element on postLinking:

angular.module('directives')
.directive('autoFocus', function() {
    return {
        restrict: 'AC',
        link: function(_scope, _element) {
            _element[0].focus();
        }
    };
});

Then in your html:

<input type="text" name="first" auto-focus/> <!-- this will get the focus -->
<input type="text" name="second"/>

This would work for modals and ng-if toggled elements, not for ng-show since postLinking happens only on HTML processing.

How to write text in ipython notebook?

Simply Enter Esc and type m it will convert to text cell.

checking if a number is divisible by 6 PHP

Why don't you use the Modulus Operator?

Try this:

while ($s % 6 != 0) $s++;

Or is this what you meant?

<?

 $s= <some_number>;
 $k= $s % 6;

 if($k !=0)    $s=$s+6-$k;
?>

How to bring an activity to foreground (top of stack)?

i.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);

Note Your homeactivity launchmode should be single_task

How to edit the size of the submit button on a form?

just use style attribute with height and width option

<input type="submit" id="search" value="Search"  style="height:50px; width:50px" />

Append text to file from command line without using io redirection

If you just want to tack something on by hand, then the sed answer will work for you. If instead the text is in file(s) (say file1.txt and file2.txt):

Using Perl:

perl -e 'open(OUT, ">>", "outfile.txt"); print OUT while (<>);' file*.txt

N.B. while the >> may look like an indication of redirection, it is just the file open mode, in this case "append".

Embedding Windows Media Player for all browsers

I have found something that Actually works in both FireFox and IE, on Elizabeth Castro's site (thanks to the link on this site) - I have tried all other versions here, but could not make them work in both the browsers

<object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" 
  id="player" width="320" height="260">
  <param name="url" 
    value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
  <param name="src" 
    value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
  <param name="showcontrols" value="true" />
  <param name="autostart" value="true" />
  <!--[if !IE]>-->
  <object type="video/x-ms-wmv" 
    data="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" 
    width="320" height="260">
    <param name="src" 
      value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
    <param name="autostart" value="true" />
    <param name="controller" value="true" />
  </object>
  <!--<![endif]-->
</object>

Check her site out: http://www.alistapart.com/articles/byebyeembed/ and the version with the classid in the initial object tag

How do I implement a progress bar in C#?

When you perform operations on Background thread and you want to update UI, you can not call or set anything from background thread. In case of WPF you need Dispatcher.BeginInvoke and in case of WinForms you need Invoke method.

WPF:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Dispatcher.BeginInvoke((Action)delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

WinForms:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Invoke(delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

for WinForms delegate may require some casting or you may need little help there, dont remember the exact syntax now.

How to ignore the certificate check when ssl

For anyone interested in applying this solution on a per request basis, this is an option and uses a Lambda expression. The same Lambda expression can be applied to the global filter mentioned by blak3r as well. This method appears to require .NET 4.5.

String url = "https://www.stackoverflow.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

In .NET 4.0, the Lambda Expression can be applied to the global filter as such

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

Different color for each bar in a bar chart; ChartJS

After looking into the Chart.Bar.js file I've managed to find the solution. I've used this function to generate a random color:

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

I've added it to the end of the file and i called this function right inside the "fillColor:" under

helpers.each(dataset.data,function(dataPoint,index){
                    //Add a new point for each piece of data, passing any required data to draw.

so now it looks like this:

helpers.each(dataset.data,function(dataPoint,index){
                    //Add a new point for each piece of data, passing any required data to draw.

                    datasetObject.bars.push(new this.BarClass({
                        value : dataPoint,
                        label : data.labels[index],
                        datasetLabel: dataset.label,
                        strokeColor : dataset.strokeColor,
                        fillColor : getRandomColor(),
                        highlightFill : dataset.highlightFill || dataset.fillColor,
                        highlightStroke : dataset.highlightStroke || dataset.strokeColor
                    }));
                },this);

and it works I get different color for each bar.

SQL Server FOR EACH Loop

[CREATE PROCEDURE [rat].[GetYear]

AS
BEGIN

-- variable for storing start date
Declare @StartYear as int
-- Variable for the End date 
Declare @EndYear as int 

-- Setting the value in strat Date
select @StartYear = Value from   rat.Configuration where Name = 'REPORT_START_YEAR'; 

-- Setting the End date 
select @EndYear = Value from   rat.Configuration where Name = 'REPORT_END_YEAR'; 


-- Creating Tem table 
    with [Years] as
    (
        --Selecting the Year
        select @StartYear [Year] 
        --doing Union 
        union all
         -- doing the loop in Years table 
         select Year+1 Year from [Years] where Year < @EndYear
     )
    --Selecting the Year table 
selec]

Display date/time in user's locale format and time offset

For new projects, just use moment.js

This question is pretty old, so moment.js didn't exist at that time, but for new projects, it simplifies tasks like this a lot.

It's best to parse your date string from UTC as follows (create an ISO-8601 compatible string on the server to get consistent results across all browsers):

var m = moment("2013-02-08T09:30:26Z");

Now just use m in your application, moment.js defaults to the local timezone for display operations. There are many ways to format the date and time values or extract portions of it.

You can even format a moment object in the users locale like this:

m.format('LLL') // Returns "February 8 2013 8:30 AM" on en-us

To transform a moment.js object into a different timezone (i.e. neither the local one nor UTC), you'll need the moment.js timezone extension. That page has also some examples, it's pretty simple to use.

Recursive directory listing in DOS

You can get the parameters you are asking for by typing:

dir /?

For the full list, try:

dir /s /b /a:d

Converting a sentence string to a string array of words in Java

Now, this can be accomplished just with split as it takes regex:

String s = "This is a sample sentence with []s.";
String[] words = s.split("\\W+");

this will give words as: {"this","is","a","sample","sentence", "s"}

The \\W+ will match all non-alphabetic characters occurring one or more times. So there is no need to replace. You can check other patterns also.

How can I create a memory leak in Java?

I have had a nice "memory leak" in relation to PermGen and XML parsing once. The XML parser we used (I can't remember which one it was) did a String.intern() on tag names, to make comparison faster. One of our customers had the great idea to store data values not in XML attributes or text, but as tagnames, so we had a document like:

<data>
   <1>bla</1>
   <2>foo</>
   ...
</data>

In fact, they did not use numbers but longer textual IDs (around 20 characters), which were unique and came in at a rate of 10-15 million a day. That makes 200 MB of rubbish a day, which is never needed again, and never GCed (since it is in PermGen). We had permgen set to 512 MB, so it took around two days for the out-of-memory exception (OOME) to arrive...

AngularJS - Trigger when radio button is selected

In newer versions of angular (I'm using 1.3) you can basically set the model and the value and the double binding do all the work this example works like a charm:

_x000D_
_x000D_
angular.module('radioExample', []).controller('ExampleController', ['$scope', function($scope) {_x000D_
  $scope.color = {_x000D_
    name: 'blue'_x000D_
  };_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
<html>_x000D_
<body ng-app="radioExample">_x000D_
<form name="myForm" ng-controller="ExampleController">_x000D_
  <input type="radio" ng-model="color.name" value="red">  Red <br/>_x000D_
  <input type="radio" ng-model="color.name" value="green"> Green <br/>_x000D_
  <input type="radio" ng-model="color.name" value="blue"> Blue <br/>_x000D_
  <tt>color = {{color.name}}</tt><br/>_x000D_
 </form>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What are the differences between B trees and B+ trees?

The principal advantage of B+ trees over B trees is they allow you to pack in more pointers to other nodes by removing pointers to data, thus increasing the fanout and potentially decreasing the depth of the tree.

The disadvantage is that there are no early outs when you might have found a match in an internal node. But since both data structures have huge fanouts, the vast majority of your matches will be on leaf nodes anyway, making on average the B+ tree more efficient.

What is the most accurate way to retrieve a user's correct IP address in PHP?

Thanks for this, very useful.

It would help though if the code were syntactically correct. As it is there's a { too many around line 20. Which I'm afraid means nobody actually tried this out.

I may be crazy, but after trying it on a few valid and invalid addresses, the only version of validate_ip() that worked was this:

    public function validate_ip($ip)
    {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) === false)
            return false;
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === false)
            return false;
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false)
            return false;

        return true;
    }

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.

Force download a pdf link using javascript/ajax/jquery

In javascript use the preventDefault() method of the event args parameter.

<a href="no-script.html">Download now!</a>

$('a').click(function(e) {
    e.preventDefault(); // stop the browser from following
    window.location.href = 'downloads/file.pdf';
});

How to upgrade Git on Windows to the latest version?

Git Bash

Note, if you are instead looking to find out what version of Git Bash you are running, or want to see if you need to update Git Bash, it is part of Git for Windows.

So your Git Bash version is:

git --version

git version 2.23.0.windows.1

Note that it is technically different from Bash. On my same machine when I run:

echo $BASH_VERSION

4.4.23(1)-release

Git for Windows installer

To update to the latest version of Git and Git Bash, you can download and install the latest version of git for Windows. As per FAQ, settings/customizations should be preserved if they were installed in the appropriate configuration folders.

Note: Their installer is actually intelligently designed to do the right thing (except for telling you that it's doing the right thing automatically). If you are doing an update, then every screen on the installer is pre-marked with the settings from your current (soon to be previous) install.

It is not showing you generic default settings. You do not need to look any of them up, or fear for breaking your carefully honed setup. Just leave everything as is, to retain your previous choices.

In fact, they made it even easier (if only it was clear that they did so).
There is a checkbox at the bottom [] Show only new settings (I don't remember the exact wording). Since nothing on the first screen changes when you mark the box, it is not exactly obvious what it is for. If you mark the box, then all of your current settings will be retained, and it will skip showing those subsequent settings screens to you. Only screens with newly introduced settings will be shown.

git update-git-for-windows

Alternatively, as others have noted, you can also update Git Bash and Git (by definition, both are always updated at the same time) from the Git Bash command line, via:

git update-git-for-windows  

If you type git update, git kindly reminds you that the command has been updated to git update-git-for-windows:

Warning! git update has been deprecated;
Please use git update-git-for-windows instead.
Git for Windows 2.26.0.windows.1 (64bit)
Up to date

Is there an alternative to string.Replace that is case-insensitive?

Seems like string.Replace should have an overload that takes a StringComparison argument. Since it doesn't, you could try something like this:

public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)
{
    StringBuilder sb = new StringBuilder();

    int previousIndex = 0;
    int index = str.IndexOf(oldValue, comparison);
    while (index != -1)
    {
        sb.Append(str.Substring(previousIndex, index - previousIndex));
        sb.Append(newValue);
        index += oldValue.Length;

        previousIndex = index;
        index = str.IndexOf(oldValue, index, comparison);
    }
    sb.Append(str.Substring(previousIndex));

    return sb.ToString();
}

How to prevent http file caching in Apache httpd (MAMP)

Based on the example here: http://drupal.org/node/550488

The following will probably work in .htaccess

 <IfModule mod_expires.c>
   # Enable expirations.
   ExpiresActive On

   # Cache all files for 2 weeks after access (A).
   ExpiresDefault A1209600

  <FilesMatch (\.js|\.html)$>
     ExpiresActive Off
  </FilesMatch>
 </IfModule>

jQuery hasClass() - check for more than one class

What about this,

$.fn.extend({
     hasClasses: function( selector ) {
        var classNamesRegex = new RegExp("( " + selector.replace(/ +/g,"").replace(/,/g, " | ") + " )"),
            rclass = /[\n\t\r]/g,
            i = 0,
            l = this.length;
        for ( ; i < l; i++ ) {
            if ( this[i].nodeType === 1 && classNamesRegex.test((" " + this[i].className + " ").replace(rclass, " "))) {
                return true;
            }
        }
        return false;
    }
});

Easy to use,

if ( $("selector").hasClasses("class1, class2, class3") ) {
  //Yes It does
}

And It seems to be faster, http://jsperf.com/hasclasstest/7

Centering elements in jQuery Mobile

In the situation where you are NOT going to use this over and over (i.e. not needed in your style sheet), inline style statements usually work anywhere they would work inyour style sheet. E.g:

<div data-role="controlgroup" data-type="horizontal" style="text-align:center;">