Programs & Examples On #Node set

how to convert an RGB image to numpy array?

You can get numpy array of rgb image easily by using numpy and Image from PIL

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

im = Image.open('*image_name*') #These two lines
im_arr = np.array(im) #are all you need
plt.imshow(im_arr) #Just to verify that image array has been constructed properly

How to check if element is visible after scrolling?

This considers any padding, border or margin the element has as well as elements larger than the viewport itself.

function inViewport($ele) {
    var lBound = $(window).scrollTop(),
        uBound = lBound + $(window).height(),
        top = $ele.offset().top,
        bottom = top + $ele.outerHeight(true);

    return (top > lBound && top < uBound)
        || (bottom > lBound && bottom < uBound)
        || (lBound >= top && lBound <= bottom)
        || (uBound >= top && uBound <= bottom);
}

To call it use something like this:

var $myElement = $('#my-element'),
    canUserSeeIt = inViewport($myElement);

console.log(canUserSeeIt); // true, if element is visible; false otherwise

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

Check to see if there are any triggers on the table you are trying to execute queries against. They can sometimes throw this error as they are trying to run the update/select/insert trigger that is on the table.

You can modify your query to disable then enable the trigger if the trigger DOES NOT need to be executed for whatever query you are trying to run.

ALTER TABLE your_table DISABLE TRIGGER [the_trigger_name]

UPDATE    your_table
SET     Gender = 'Female'
WHERE     (Gender = 'Male')

ALTER TABLE your_table ENABLE TRIGGER [the_trigger_name]

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

"Initializing" variables in python?

I know you have already accepted another answer, but I think the broader issue needs to addressed - programming style that is suitable to the current language.

Yes, 'initialization' isn't needed in Python, but what you are doing isn't initialization. It is just an incomplete and erroneous imitation of initialization as practiced in other languages. The important thing about initialization in static typed languages is that you specify the nature of the variables.

In Python, as in other languages, you do need to give variables values before you use them. But giving them values at the start of the function isn't important, and even wrong if the values you give have nothing to do with values they receive later. That isn't 'initialization', it's 'reuse'.

I'll make some notes and corrections to your code:

def main():
   # doc to define the function
   # proper Python indentation
   # document significant variables, especially inputs and outputs
   # grade_1, grade_2, grade_3, average - id these
   # year - id this
   # fName, lName, ID, converted_ID 

   infile = open("studentinfo.txt", "r") 
   # you didn't 'intialize' this variable

   data = infile.read()  
   # nor this  

   fName, lName, ID, year = data.split(",")
   # this will produce an error if the file does not have the right number of strings
   # 'year' is now a string, even though you 'initialized' it as 0

   year = int(year)
   # now 'year' is an integer
   # a language that requires initialization would have raised an error
   # over this switch in type of this variable.

   # Prompt the user for three test scores
   grades = eval(input("Enter the three test scores separated by a comma: "))
   # 'eval' ouch!
   # you could have handled the input just like you did the file input.

   grade_1, grade_2, grade_3 = grades   
   # this would work only if the user gave you an 'iterable' with 3 values
   # eval() doesn't ensure that it is an iterable
   # and it does not ensure that the values are numbers. 
   # What would happen with this user input: "'one','two','three',4"?

   # Create a username 
   uName = (lName[:4] + fName[:2] + str(year)).lower()

   converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
   # earlier you 'initialized' converted_ID
   # initialization in a static typed language would have caught this typo
   # pseudo-initialization in Python does not catch typos
   ....

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

Very good option is update to Internet Explorer 10. You will find very useful developers tools including compatibility with from IE5 to IE 10 including quirks mode. If switch the IE version i menu, the page rendering of the page is changing immediately.

Very good feature of this mode is javascript and HTML (firebug like) debugger, which works in compatibility mode. It means, you can debug javascript in very old IE with the newest debugger, which is very cool feature. You cannot do that with virtual machine. Yes, you can have virtual machine for checking the final result. enter image description here

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

From find manual:

NON-BUGS         

   Operator precedence surprises
   The command find . -name afile -o -name bfile -print will never print
   afile because this is actually equivalent to find . -name afile -o \(
   -name bfile -a -print \).  Remember that the precedence of -a is
   higher than that of -o and when there is no operator specified
   between tests, -a is assumed.

   “paths must precede expression” error message
   $ find . -name *.c -print
   find: paths must precede expression
   Usage: find [-H] [-L] [-P] [-Olevel] [-D ... [path...] [expression]

   This happens because *.c has been expanded by the shell resulting in
   find actually receiving a command line like this:
   find . -name frcode.c locate.c word_io.c -print
   That command is of course not going to work.  Instead of doing things
   this way, you should enclose the pattern in quotes or escape the
   wildcard:
   $ find . -name '*.c' -print
   $ find . -name \*.c -print

Python Requests library redirect new url

the documentation has this blurb https://requests.readthedocs.io/en/master/user/quickstart/#redirection-and-history

import requests

r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for 

Wrap a text within only two lines inside div

I believe the CSS-only solution text-overflow: ellipsis applies to one line only, so you won't be able to go this route:

.yourdiv {

    line-height: 1.5em; /* Sets line height to 1.5 times text size */
    height: 3em; /* Sets the div height to 2x line-height (3 times text size) */
    width: 100%; /* Use whatever width you want */
    white-space: normal; /* Wrap lines of text */
    overflow: hidden; /* Hide text that goes beyond the boundaries of the div */
    text-overflow: ellipsis; /* Ellipses (cross-browser) */
    -o-text-overflow: ellipsis; /* Ellipses (cross-browser) */
}

Have you tried http://tpgblog.com/threedots/ for jQuery?

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

In a case where you are using a custom cell type, say ArticleCell, you might get an error that says :

    Initializer for conditional binding must have Optional type, not 'ArticleCell'

You will get this error if your line of code looks something like this:

    if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as! ArticleCell 

You can fix this error by doing the following :

    if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as ArticleCell?

If you check the above, you will see that the latter is using optional casting for a cell of type ArticleCell.

Java 8: Difference between two LocalDateTime in multiple units

TL;DR

Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());

and then use the methods period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart().


Expanded answer

I'll answer the original question, i.e. how to get the time difference between two LocalDateTimes in years, months, days, hours & minutes, such that the "sum" (see note below) of all the values for the different units equals the total temporal difference, and such that the value in each unit is smaller than the next bigger unit—i.e. minutes < 60, hours < 24, and so on.

Given two LocalDateTimes start and end, e.g.

LocalDateTime start = LocalDateTime.of(2019, 11, 29, 17, 15);
LocalDateTime end = LocalDateTime.of(2020, 11, 30, 18, 44);

we can represent the absolute timespan between the two with a Duration—perhaps using Duration.between(start, end). But the biggest unit we can extract out of a Duration is days (as a temporal unit equivalent to 24h)—see the note below for an explanation. To use larger units (months, years) we can represent this Duration with a pair of (Period, Duration), where the Period measures the difference up to a precision of days and the Duration represents the remainder:

Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());

Now we can simply use the methods defined on Period and Duration to extract the individual units:

System.out.printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds",
        period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(),
        duration.toMinutesPart(), duration.toSecondsPart());
1 years, 0 months, 1 days, 1 hours, 29 minutes, 0 seconds

or, using the default format:

System.out.println(period + " + " + duration);
P1Y1D + PT1H29M

Note on years, months & days

Note that, in java.time's conception, "units" like "month" or "year" don't represent a fixed, absolute temporal value—they're date- and calendar-dependent, as the following example illustrates:

LocalDateTime
        start1 = LocalDateTime.of(2020, 1, 1, 0, 0),
        end1 = LocalDateTime.of(2021, 1, 1, 0, 0),
        start2 = LocalDateTime.of(2021, 1, 1, 0, 0),
        end2 = LocalDateTime.of(2022, 1, 1, 0, 0);
System.out.println(Period.between(start1.toLocalDate(), end1.toLocalDate()));
System.out.println(Duration.between(start1, end1).toDays());
System.out.println(Period.between(start2.toLocalDate(), end2.toLocalDate()));
System.out.println(Duration.between(start2, end2).toDays());
P1Y
366
P1Y
365

How can I add a box-shadow on one side of an element?

What I do is create a vertical block for the shadow, and place it next to where my block element should be. The two blocks are then wrapped into another block:

<div id="wrapper">
    <div id="shadow"></div>  
    <div id="content">CONTENT</div>  
</div>

<style>

div#wrapper {
  width:200px;
  height:258px;      
}

div#wrapper > div#shadow {
  display:inline-block;
  width:1px;
  height:100%;
  box-shadow: -3px 0px 5px 0px rgba(0,0,0,0.8)
}

div#wrapper > div#content {
  display:inline-block;
  height:100%;
  vertical-align:top;
}

</style>

jsFiddle example here.

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet.

The propagation delay, is the time it takes a bit to propagate from one router to the next.

the transmission and propagation delay are completely different! if denote the length of the packet by L bits, and denote the transmission rate of the link from first router to second router by R bits/sec. then transmission delay will be L/R. and this is depended to transmission rate of link and the length of packet.

then if denote the distance between two routers d and denote the propagation speed s, the propagation delay will be d/s. it is a function of the Distance between the two routers, but has no dependence to the packet's length or the transmission rate of the link.

Getting time and date from timestamp with php

Works for me:

select DATE( FROM_UNIXTIME( columnname ) ) from tablename;

How do I parse a HTML page with Node.js

Use htmlparser2, its way faster and pretty straightforward. Consult this usage example:

https://www.npmjs.org/package/htmlparser2#usage

And the live demo here:

http://demos.forbeslindesay.co.uk/htmlparser2/

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

symfony 2 twig limit the length of the text and put three dots

Bugginess* in the new Drupal 8 capabilities here inspired us to write our own:

<a href="{{ view_node }}">{% if title|length > 32 %}{% set title_array = title|split(' ') %}{% set title_word_count = 0 %}{% for ta in title_array %}{% set word_count = ta|length %}{% if title_word_count < 32 %}{% set title_word_count = title_word_count + word_count %}{{ ta }} {% endif %}{% endfor %}...{% else %}{{ title }}{% endif %}</a>

This takes into consideration both words and characters (*the "word boundary" setting in D8 was displaying nothing).

How do I run a terminal inside of Vim?

If enabled in your version of Vim, a terminal can be started with the :term command.

Terminal window support was added to Vim 8. It is an optional feature that can be enabled when compiling Vim with the +terminal feature. If your version of Vim has terminal support, :echo has('terminal') will output "1".

Entering :term will place you in Terminal-Job mode, where you can use the terminal as expected.

Within Terminal-Job mode, pressing Ctrl-W N or Ctrl-\ Ctrl-N switches the mode to Terminal-Normal, which allows the cursor to be moved and commands to be ran similarly to Vim's Normal mode. To switch back to Terminal-Job mode, press i.

Other answers mention similar functionality in Neovim.

TSQL CASE with if comparison in SELECT statement

Should be:

SELECT registrationDate, 
       (SELECT CASE
        WHEN COUNT(*)< 2 THEN 'Ama'
        WHEN COUNT(*)< 5 THEN 'SemiAma' 
        WHEN COUNT(*)< 7 THEN 'Good'  
        WHEN COUNT(*)< 9 THEN 'Better' 
        WHEN COUNT(*)< 12 THEN 'Best'
        ELSE 'Outstanding'
        END as a FROM Articles 
        WHERE Articles.userId = Users.userId) as ranking,
        (SELECT COUNT(*) 
        FROM Articles 
        WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS

How to get IntPtr from byte[] in C#

IntPtr GetIntPtr(Byte[] byteBuf)
{
    IntPtr ptr = Marshal.AllocHGlobal(byteBuf.Length);
    for (int i = 0; i < byteBuf.Length; i++)
    {
       Marshal.WriteByte(ptr, i, byteBuf[i]);
    }
    return ptr;
}

Another git process seems to be running in this repository

Try deleting index.lock file in your .git directory.

rm -f .git/index.lock

Such problems generally occur when you execute two git commands simultaneously; maybe one from the command prompt and one from an IDE.

How to style the <option> with only CSS?

I've played around with select items before and without overriding the functionality with JavaScript, I don't think it's possible in Chrome. Whether you use a plugin or write your own code, CSS only is a no go for Chrome/Safari and as you said, Firefox is better at dealing with it.

PHP not displaying errors even though display_errors = On

When running PHP on windows with ISS there are some configuration settings in ISS that need to be set to prevent generic default pages from being shown.

1) Double click on FastCGISettings, click on PHP then Edit. Set StandardErrorMode to ReturnStdErrLn500.

StandardErrorMode

2) Go the the site, double click on the Error Pages, click on the 500 status, click Edit Feature Settings, Change Error Responses to Detailed Errors, click ok

Change Error Responses to Detailed Errors

Call Class Method From Another Class

You can call a function from within a class with:

A().method1()

Passing command line arguments to R CMD BATCH

You need to put arguments before my_script.R and use - on the arguments, e.g.

R CMD BATCH -blabla my_script.R

commandArgs() will receive -blabla as a character string in this case. See the help for details:

$ R CMD BATCH --help
Usage: R CMD BATCH [options] infile [outfile]

Run R non-interactively with input from infile and place output (stdout
and stderr) to another file.  If not given, the name of the output file
is the one of the input file, with a possible '.R' extension stripped,
and '.Rout' appended.

Options:
  -h, --help        print short help message and exit
  -v, --version     print version info and exit
  --no-timing           do not report the timings
  --            end processing of options

Further arguments starting with a '-' are considered as options as long
as '--' was not encountered, and are passed on to the R process, which
by default is started with '--restore --save --no-readline'.
See also help('BATCH') inside R.

Pandas create empty DataFrame with only column names

Creating colnames with iterating

df = pd.DataFrame(columns=['colname_' + str(i) for i in range(5)])
print(df)

# Empty DataFrame
# Columns: [colname_0, colname_1, colname_2, colname_3, colname_4]
# Index: []

to_html() operations

print(df.to_html())

# <table border="1" class="dataframe">
#   <thead>
#     <tr style="text-align: right;">
#       <th></th>
#       <th>colname_0</th>
#       <th>colname_1</th>
#       <th>colname_2</th>
#       <th>colname_3</th>
#       <th>colname_4</th>
#     </tr>
#   </thead>
#   <tbody>
#   </tbody>
# </table>

this seems working

print(type(df.to_html()))
# <class 'str'>

The problem is caused by

when you create df like this

df = pd.DataFrame(columns=COLUMN_NAMES)

it has 0 rows × n columns, you need to create at least one row index by

df = pd.DataFrame(columns=COLUMN_NAMES, index=[0])

now it has 1 rows × n columns. You are be able to add data. Otherwise its df that only consist colnames object(like a string list).

Folder structure for a Node.js project

Assuming we are talking about web applications and building APIs:

One approach is to categorize files by feature, much like what a micro service architecture would look like. The biggest win in my opinion is that it is super easy to see which files relate to a feature of the application.

The best way to illustrate is through an example:


We are developing a library application. In the first version of the application, a user can:

  • Search for books and see metadata of books
  • Search for authors and see their books

In a second version, users can also:

  • Create an account and log in
  • Loan/borrow books

In a third version, users can also:

  • Save a list of books they want to read/mark favorites

First we have the following structure:

books
  +- controllers
  ¦   +- booksController.js
  ¦   +- authorsController.js
  ¦
  +- entities
      +- book.js
      +- author.js

We then add on the user and loan features:

user
  +- controllers
  ¦   +- userController.js
  +- entities
  ¦   +- user.js
  +- middleware
       +- authentication.js
loan
  +- controllers
  ¦   +- loanController.js
  +- entities
      +- loan.js

And then the favorites functionality:

favorites
  +- controllers
  ¦   +- favoritesController.js
  +- entities
      +- favorite.js

For any new developer that gets handed the task to add on that the books search should also return information if any book have been marked as favorite, it's really easy to see where in the code he/she should look.

Then when the product owner sweeps in and exclaims that the favorites feature should be removed completely, it's easy to remove it.

django templates: include and extends

More info about why it wasn't working for me in case it helps future people:

The reason why it wasn't working is that {% include %} in django doesn't like special characters like fancy apostrophe. The template data I was trying to include was pasted from word. I had to manually remove all of these special characters and then it included successfully.

How to list active / open connections in Oracle?

select
  username,
  osuser,
  terminal,
  utl_inaddr.get_host_address(terminal) IP_ADDRESS
from
  v$session
where
  username is not null
order by
  username,
  osuser;

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Unsupported major.minor version 52.0 in my app

I also faced this problem when making a new project in eclipse.

  1. Open your eclipse installation directory
  2. Open the file eclipse.ini
  3. Modify

    Dosgi.requiredJavaVersion=1.6 
    

    to

    Dosgi.requiredJavaVersion=1.7
    

Hope this helps

how to check the dtype of a column in python pandas

In pandas 0.20.2 you can do:

from pandas.api.types import is_string_dtype
from pandas.api.types import is_numeric_dtype

is_string_dtype(df['A'])
>>>> True

is_numeric_dtype(df['B'])
>>>> True

So your code becomes:

for y in agg.columns:
    if (is_string_dtype(agg[y])):
        treat_str(agg[y])
    elif (is_numeric_dtype(agg[y])):
        treat_numeric(agg[y])

How can you export the Visual Studio Code extension list?

There is an Extension Manager extension, that may help. It seems to allow to install a set of extensions specified in the settings.json.

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

I had the same problem

I fixed that by using two options

contentType: false
processData: false

Actually I Added these two command to my $.ajax({}) function

Video auto play is not working in Safari and Chrome desktop browser

var video = document.querySelector('video');
video.muted = true;
video.play()

Only this solution helped me, <video autoplay muted ...>...</video> didn't work...

How a thread should close itself in Java?

If you're at the top level - or able to cleanly get to the top level - of the thread, then just returning is nice. Throwing an exception isn't as clean, as you need to be able to check that nothing's going to catch the exception and ignore it.

The reason you need to use Thread.currentThread() in order to call interrupt() is that interrupt() is an instance method - you need to call it on the thread you want to interrupt, which in your case happens to be the current thread. Note that the interruption will only be noticed the next time the thread would block (e.g. for IO or for a monitor) anyway - it doesn't mean the exception is thrown immediately.

How to retrieve records for last 30 minutes in MS SQL?

Change this (CURRENT_TIMESTAMP-30)

To This: DateADD(mi, -30, Current_TimeStamp)

To get the current date use GetDate().

MSDN Link to DateAdd Function
MSDN Link to Get Date Function

is there any alternative for ng-disabled in angular2?

Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable

For radio button:

<md-radio-button disabled>Select color</md-radio-button>

For dropdown:

<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

I have resolved the said

MqttException (0) - javax.net.ssl.SSLHandshakeException: No subjectAltNames on the certificate match

error by adding one (can add multiple) alternative subject name in the server certificate (having CN=example.com) which after prints the part of certificate as below:

Subject Alternative Name:
DNS: example.com

I used KeyExplorer on windows for generating my server certificate. You can follow this link for adding alternative subject names (follow the only part for adding it).

No provider for Router?

Babar Bilal's answer likely worked perfectly for earlier Angular 2 alpha/beta releases. However, anyone solving this problem with Angular release v4+ may want to try the following change to his answer instead (wrapping the single route in the required array):

RouterModule.forRoot([{ path: "", component: LoginComponent}])

Simple WPF RadioButton Binding?

This example might be seem a bit lengthy, but its intention should be quite clear.

It uses 3 Boolean properties in the ViewModel called, FlagForValue1, FlagForValue2 and FlagForValue3. Each of these 3 properties is backed by a single private field called _intValue.

The 3 Radio buttons of the view (xaml) are each bound to its corresponding Flag property in the view model. This means the radio button displaying "Value 1" is bound to the FlagForValue1 bool property in the view model and the other two accordingly.

When setting one of the properties in the view model (e.g. FlagForValue1), its important to also raise property changed events for the other two properties (e.g. FlagForValue2, and FlagForValue3) so the UI (WPF INotifyPropertyChanged infrastructure) can selected / deselect each radio button correctly.

    private int _intValue;

    public bool FlagForValue1
    {
        get
        {
            return (_intValue == 1) ? true : false;
        }
        set
        {
            _intValue = 1;
            RaisePropertyChanged("FlagForValue1");
            RaisePropertyChanged("FlagForValue2");
            RaisePropertyChanged("FlagForValue3");
        }
    }

    public bool FlagForValue2
    {
        get
        {
            return (_intValue == 2) ? true : false;
        }
        set
        {
            _intValue = 2;
            RaisePropertyChanged("FlagForValue1");
            RaisePropertyChanged("FlagForValue2");
            RaisePropertyChanged("FlagForValue3");
        }
    }

    public bool FlagForValue3
    {
        get
        {
            return (_intValue == 3) ? true : false;
        }
        set
        {
            _intValue = 3;
            RaisePropertyChanged("FlagForValue1");
            RaisePropertyChanged("FlagForValue2");
            RaisePropertyChanged("FlagForValue3");
        }
    }

The xaml looks like this:

                <RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue1, Mode=TwoWay}"
                             >Value 1</RadioButton>

                <RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue2, Mode=TwoWay}"
                             >Value 2</RadioButton>

                <RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue3, Mode=TwoWay}"
                             >Value 3</RadioButton>

JavaScript pattern for multiple constructors

How do you find this one?

function Foobar(foobar) {
    this.foobar = foobar;
}

Foobar.prototype = {
    foobar: null
};

Foobar.fromComponents = function(foo, bar) {
    var foobar = foo + bar;
    return new Foobar(foobar);
};

//usage: the following two lines give the same result
var x = Foobar.fromComponents('Abc', 'Cde');
var y = new Foobar('AbcDef')

PHP Adding 15 minutes to Time value

Your code doesn't work (parse) because you have an extra ) at the end that causes a Parse Error. Count, you have 2 ( and 3 ). It would work fine if you fix that, but strtotime() returns a timestamp, so to get a human readable time use date().

$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);

Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.

To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):

 $endTime = strtotime($selectedTime) + 900;  //900 = 15 min X 60 sec

Still, the ) is the main issue here.

How to filter a dictionary according to an arbitrary condition function?

dict((k, v) for k, v in points.items() if all(x < 5 for x in v))

You could choose to call .iteritems() instead of .items() if you're in Python 2 and points may have a lot of entries.

all(x < 5 for x in v) may be overkill if you know for sure each point will always be 2D only (in that case you might express the same constraint with an and) but it will work fine;-).

How to create a drop-down list?

Try this:

package example.spin.spinnerexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Getting the instance of Spinner and applying OnItemSelectedListener on it
        Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
        spin.setOnItemSelectedListener(this);

        //Creating the ArrayAdapter instance having the bank name list
        ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //Setting the ArrayAdapter data on the Spinner
        spin.setAdapter(aa);
    }


    //Performing action onItemSelected and onNothing selected
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
        Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }
}

activity_main.xml:-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/simpleSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp" />

</RelativeLayout>

How to center Font Awesome icons horizontally?

It's a really old topic but as it still comes up top in search results:

Nowadays you can add additional class fa-fw to set it fixed width.

Example:

<i class="fa fa-pencil fa-fw" aria-hidden="true"></i>

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

The latest docker supports setting ulimits through the command line and the API. For instance, docker run takes --ulimit <type>=<soft>:<hard> and there can be as many of these as you like. So, for your nofile, an example would be --ulimit nofile=262144:262144

Move top 1000 lines from text file to a new file using Unix shell commands

Perl approach:

perl -ne 'if($i<1000) { print; } else { print STDERR;}; $i++;' in 1> in.new 2> out && mv in.new in

Postgres: How to do Composite keys?

Your compound PRIMARY KEY specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT (already implied), too:

 CREATE TABLE tags
      (
               question_id INTEGER NOT NULL,
               tag_id SERIAL NOT NULL,
               tag1 VARCHAR(20),
               tag2 VARCHAR(20),
               tag3 VARCHAR(20),
               PRIMARY KEY(question_id, tag_id)
      );

NOTICE:  CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
    NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
    CREATE TABLE
    pg=> \d tags
                                         Table "public.tags"
       Column    |         Type          |                       Modifiers       
    -------------+-----------------------+-------------------------------------------------------
     question_id | integer               | not null
     tag_id      | integer               | not null default nextval('tags_tag_id_seq'::regclass)
     tag1        | character varying(20) |
     tag2        | character varying(20) |
     tag3        | character varying(20) |
    Indexes:
        "tags_pkey" PRIMARY KEY, btree (question_id, tag_id)

How to read numbers separated by space using scanf

int main()
{
char string[200];
int g,a,i,G[20],A[20],met;

gets(string);
g=convert_input(G,string);

for(i=0;i<=g;i++)
    printf("\n%d>>%d",i,G[i]);
return 0;
}

int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
    temp=0;
    while(string[i]!=' ' && string[i]!='\0')
        temp=temp*10 + (string[i++]-'0') ;
    if(string[i]==' ')
        i++;
    K[j++]=temp;
}
return j-1;
}

Access all Environment properties as a Map or Properties object

I had the requirement to retrieve all properties whose key starts with a distinct prefix (e.g. all properties starting with "log4j.appender.") and wrote following Code (using streams and lamdas of Java 8).

public static Map<String,Object> getPropertiesStartingWith( ConfigurableEnvironment aEnv,
                                                            String aKeyPrefix )
{
    Map<String,Object> result = new HashMap<>();

    Map<String,Object> map = getAllProperties( aEnv );

    for (Entry<String, Object> entry : map.entrySet())
    {
        String key = entry.getKey();

        if ( key.startsWith( aKeyPrefix ) )
        {
            result.put( key, entry.getValue() );
        }
    }

    return result;
}

public static Map<String,Object> getAllProperties( ConfigurableEnvironment aEnv )
{
    Map<String,Object> result = new HashMap<>();
    aEnv.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
    return result;
}

public static Map<String,Object> getAllProperties( PropertySource<?> aPropSource )
{
    Map<String,Object> result = new HashMap<>();

    if ( aPropSource instanceof CompositePropertySource)
    {
        CompositePropertySource cps = (CompositePropertySource) aPropSource;
        cps.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
        return result;
    }

    if ( aPropSource instanceof EnumerablePropertySource<?> )
    {
        EnumerablePropertySource<?> ps = (EnumerablePropertySource<?>) aPropSource;
        Arrays.asList( ps.getPropertyNames() ).forEach( key -> result.put( key, ps.getProperty( key ) ) );
        return result;
    }

    // note: Most descendants of PropertySource are EnumerablePropertySource. There are some
    // few others like JndiPropertySource or StubPropertySource
    myLog.debug( "Given PropertySource is instanceof " + aPropSource.getClass().getName()
                 + " and cannot be iterated" );

    return result;

}

private static void addAll( Map<String, Object> aBase, Map<String, Object> aToBeAdded )
{
    for (Entry<String, Object> entry : aToBeAdded.entrySet())
    {
        if ( aBase.containsKey( entry.getKey() ) )
        {
            continue;
        }

        aBase.put( entry.getKey(), entry.getValue() );
    }
}

Note that the starting point is the ConfigurableEnvironment which is able to return the embedded PropertySources (the ConfigurableEnvironment is a direct descendant of Environment). You can autowire it by:

@Autowired
private ConfigurableEnvironment  myEnv;

If you not using very special kinds of property sources (like JndiPropertySource, which is usually not used in spring autoconfiguration) you can retrieve all properties held in the environment.

The implementation relies on the iteration order which spring itself provides and takes the first found property, all later found properties with the same name are discarded. This should ensure the same behaviour as if the environment were asked directly for a property (returning the first found one).

Note also that the returned properties are not yet resolved if they contain aliases with the ${...} operator. If you want to have a particular key resolved you have to ask the Environment directly again:

myEnv.getProperty( key );

Calling a function every 60 seconds

There are 2 ways to call-

  1. setInterval(function (){ functionName();}, 60000);

  2. setInterval(functionName, 60000);

above function will call on every 60 seconds.

how to re-format datetime string in php?

If you want to use substr(), you can easily add the dashes or slashes like this..

$datetime = "20130409163705"; 
$yyyy = substr($datetime,0,4);
$mm = substr($datetime,4,6);
$dd = substr($datetime,6,8);
$hh = substr($datetime,8,10);
$MM = substr($datetime,10,12);
$ss = substr($datetime,12,14);
$dt_formatted = $mm."/".$dd."/".$yyyy." ".$hh.":".$MM.":".$ss;

You can figure out any further formatting from that point.

Git push error '[remote rejected] master -> master (branch is currently checked out)'

git config --local receive.denyCurrentBranch updateInstead

https://github.com/git/git/blob/v2.3.0/Documentation/config.txt#L2155

Use that on the server repository, and it also updates the working tree if no untracked overwrite would happen.

It was added in Git 2.3 as mentioned by VonC in the comments.

I've compiled Git 2.3 and gave it a try. Sample usage:

git init server
cd server
touch a
git add .
git commit -m 0
git config --local receive.denyCurrentBranch updateInstead

cd ..
git clone server local
cd local
touch b
git add .
git commit -m 1
git push origin master:master

cd ../server
ls

Output:

a
b

Yay, b got pushed!

How to add a local repo and treat it as a remote repo

You have your arguments to the remote add command reversed:

git remote add <NAME> <PATH>

So:

git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git

See git remote --help for more information.

How do I find out my python path using python?

import subprocess
python_path = subprocess.check_output("which python", shell=True).strip()
python_path = python_path.decode('utf-8')

@class vs. #import

Compiler will complain only if you are going to use that class in such a way that the compiler needs to know its implementation.

Ex:

  1. This could be like if you are going to derive your class from it or
  2. If you are going to have an object of that class as a member variable (though rare).

It will not complain if you are just going to use it as a pointer. Of course, you will have to #import it in the implementation file (if you are instantiating an object of that class) since it needs to know the class contents to instantiate an object.

NOTE: #import is not same as #include. This means there is nothing called circular import. import is kind of a request for the compiler to look into a particular file for some information. If that information is already available, compiler ignores it.

Just try this, import A.h in B.h and B.h in A.h. There will be no problems or complaints and it will work fine too.

When to use @class

You use @class only if you don't even want to import a header in your header. This could be a case where you don't even care to know what that class will be. Cases where you may not even have a header for that class yet.

An example of this could be that you are writing two libraries. One class, lets call it A, exists in one library. This library includes a header from the second library. That header might have a pointer of A but again might not need to use it. If library 1 is not yet available, library B will not be blocked if you use @class. But if you are looking to import A.h, then library 2's progress is blocked.

Which language uses .pde extension?

Bad news I'm afraid (or maybe great news?) : it isn't C code, it's an example of "Processing" - an open source language aimed at programming images. Take a look here

Looks very cool.

Styling input radio with css

Here is simple example of how you can do this.

Just replace the image file and you are done.

HTML Code

<input type="radio" id="r1" name="rr" />
<label for="r1"><span></span>Radio Button 1</label>
<p>
<input type="radio" id="r2" name="rr" />
<label for="r2"><span></span>Radio Button 2</label>

CSS

input[type="radio"] {
    display:none;
}

input[type="radio"] + label {
    color:#f2f2f2;
    font-family:Arial, sans-serif;
    font-size:14px;
}

input[type="radio"] + label span {
    display:inline-block;
    width:19px;
    height:19px;
    margin:-1px 4px 0 0;
    vertical-align:middle;
    background:url(check_radio_sheet.png) -38px top no-repeat;
    cursor:pointer;
}

input[type="radio"]:checked + label span {
    background:url(check_radio_sheet.png) -57px top no-repeat;
}

Working DEMO

node.js require all files in a folder?

Another option is to use the package require-dir which let's you do the following. It supports recursion as well.

var requireDir = require('require-dir');
var dir = requireDir('./path/to/dir');

CSS background-image - What is the correct usage?

Have a look at the respective sitepoint reference pages for background-image and URIs

  1. It does not have to be in quotes but can use them if you like. (I think IE5/Mac does not support single quotes).
  2. Both relative and absolute is possible; a relative path is relative to the path of the css file.

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Parallel.ForEach vs Task.Factory.StartNew

I did a small experiment of running a method "1,000,000,000 (one billion)" times with "Parallel.For" and one with "Task" objects.

I measured the processor time and found Parallel more efficient. Parallel.For divides your task in to small work items and executes them on all the cores parallely in a optimal way. While creating lot of task objects ( FYI TPL will use thread pooling internally) will move every execution on each task creating more stress in the box which is evident from the experiment below.

I have also created a small video which explains basic TPL and also demonstrated how Parallel.For utilizes your core more efficiently http://www.youtube.com/watch?v=No7QqSc5cl8 as compared to normal tasks and threads.

Experiment 1

Parallel.For(0, 1000000000, x => Method1());

Experiment 2

for (int i = 0; i < 1000000000; i++)
{
    Task o = new Task(Method1);
    o.Start();
}

Processor time comparison

How does a ArrayList's contains() method evaluate objects?

The ArrayList uses the equals method implemented in the class (your case Thing class) to do the equals comparison.

Is there a way to use two CSS3 box shadows on one element?

Box shadows can use commas to have multiple effects, just like with background images (in CSS3).

PHP Get all subdirectories of a given directory

If you're looking for a recursive directory listing solutions. Use below code I hope it should help you.

<?php
/**
 * Function for recursive directory file list search as an array.
 *
 * @param mixed $dir Main Directory Path.
 *
 * @return array
 */
function listFolderFiles($dir)
{
    $fileInfo     = scandir($dir);
    $allFileLists = [];

    foreach ($fileInfo as $folder) {
        if ($folder !== '.' && $folder !== '..') {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $folder) === true) {
                $allFileLists[$folder . '/'] = listFolderFiles($dir . DIRECTORY_SEPARATOR . $folder);
            } else {
                $allFileLists[$folder] = $folder;
            }
        }
    }

    return $allFileLists;
}//end listFolderFiles()


$dir = listFolderFiles('your searching directory path ex:-F:\xampp\htdocs\abc');
echo '<pre>';
print_r($dir);
echo '</pre>'

?>

PHP combine two associative arrays into one array

UPDATE Just a quick note, as I can see this looks really stupid, and it has no good use with pure PHP because the array_merge just works there. BUT try it with the PHP MongoDB driver before you rush to downvote. That dude WILL add indexes for whatever reason, and WILL ruin the merged object. With my naïve little function, the merge comes out exactly the way it was supposed to with a traditional array_merge.


I know it's an old question but I'd like to add one more case I had recently with MongoDB driver queries and none of array_merge, array_replace nor array_push worked. I had a bit complex structure of objects wrapped as arrays in array:

$a = [
 ["a" => [1, "a2"]],
 ["b" => ["b1", 2]]
];
$t = [
 ["c" => ["c1", "c2"]],
 ["b" => ["b1", 2]]
];

And I needed to merge them keeping the same structure like this:

$merged = [
 ["a" => [1, "a2"]],
 ["b" => ["b1", 2]],
 ["c" => ["c1", "c2"]],
 ["b" => ["b1", 2]]
];

The best solution I came up with was this:

public static function glueArrays($arr1, $arr2) {
    // merges TWO (2) arrays without adding indexing. 
    $myArr = $arr1;
    foreach ($arr2 as $arrayItem) {
        $myArr[] = $arrayItem;
    }
    return $myArr;
}

How can I determine the URL that a local Git repository was originally cloned from?

Short answer:

$ git remote show -n origin

or, an alternative for pure quick scripts:

$ git config --get remote.origin.url

Some info:

  1. $ git remote -v will print all remotes (not what you want). You want origin right?
  2. $ git remote show origin much better, shows only origin but takes too long (tested on git version 1.8.1.msysgit.1).

I ended up with: $ git remote show -n origin, which seems to be fastest. With -n it will not fetch remote heads (AKA branches). You don't need that type of info, right?

http://www.kernel.org/pub//software/scm/git/docs/git-remote.html

You can apply | grep -i fetch to all three versions to show only the fetch URL.

If you require pure speed, then use:

$ git config --get remote.origin.url

Thanks to @Jefromi for pointing that out.

How to print values separated by spaces instead of new lines in Python 2.7

First of all print isn't a function in Python 2, it is a statement.

To suppress the automatic newline add a trailing ,(comma). Now a space will be used instead of a newline.

Demo:

print 1,
print 2

output:

1 2

Or use Python 3's print() function:

from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)

As you can clearly see print() function is much more powerful as we can specify any string to be used as end rather a fixed space.

How to click a href link using Selenium

Thi is your code :

Driver.findElement(By.xpath(//a[@href ='/docs/configuration']")).click();

You missed the Quotation mark

it should be as below

Driver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();

Hope this helps!

Convert String To date in PHP

Try this:

$new_date=date('d-m-Y', strtotime($date));

<embed> vs. <object>

Answer updated for 2020:

Both <object> and <embed> are included in the WHAT-WG HTML Living Standard (Sept 2020).


<object>

The object element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a child browsing context, or as an external resource to be processed by a plugin.


<embed>

The embed element provides an integration point for an external (typically non-HTML) application or interactive content.


Are there advantages/disadvantages to using one tag vs. the other?

The opinion of Mozilla Developer Network (MDN) appears (albeit fairly subtly) to very marginally favour <object> over <embed> but overwhelmingly, MDN, wants to recommend that wherever you can, you avoid embedding external content entirely.

[...] you are unlikely to use these elements very much — Applets haven't been used for years, Flash is no longer very popular, due to a number of reasons (see The case against plugins, below), PDFs tend to be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. Plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects.

Once upon a time, plugins were indispensable on the Web. Remember the days when you had to install Adobe Flash Player just to watch a movie online? And then you constantly got annoying alerts about updating Flash Player and your Java Runtime Environment. Web technologies have since grown much more robust, and those days are over. For virtually all applications, it's time to stop delivering content that depends on plugins and start taking advantage of Web technologies instead.

Source: https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies#The_%3Cembed%3E_and_%3Cobject%3E_elements

Force overwrite of local file with what's in origin repo?

If you want to overwrite only one file:

git fetch
git checkout origin/master <filepath>

If you want to overwrite all changed files:

git fetch
git reset --hard origin/master

(This assumes that you're working on master locally and you want the changes on the origin's master - if you're on a branch, substitute that in instead.)

From Arraylist to Array

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0])). In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation. You can follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

Simplest way to wait some asynchronous tasks complete, in Javascript?

If you are using Babel or such transpilers and using async/await you could do :

function onDrop() {
   console.log("dropped");
}

async function dropAll( collections ) {
   const drops = collections.map(col => conn.collection(col).drop(onDrop) );
   await drops;
   console.log("all dropped");
}

Django values_list vs values

The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.

Here's a short snippet to keep SO reviewers happy:

values

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

And read the section which follows it:

value_list

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.

Copy data from one existing row to another existing row in SQL?

Copy a value from one row to any other qualified rows within the same table (or different tables):

UPDATE `your_table` t1, `your_table` t2
SET t1.your_field = t2.your_field
WHERE t1.other_field = some_condition
AND t1.another_field = another_condition
AND t2.source_id = 'explicit_value'

Start off by aliasing the table into 2 unique references so the SQL server can tell them apart

Next, specify the field(s) to copy.

Last, specify the conditions governing the selection of the rows

Depending on the conditions you may copy from a single row to a series, or you may copy a series to a series. You may also specify different tables, and you can even use sub-selects or joins to allow using other tables to control the relationships.

Add missing dates to pandas dataframe

One issue is that reindex will fail if there are duplicate values. Say we're working with timestamped data, which we want to index by date:

df = pd.DataFrame({
    'timestamps': pd.to_datetime(
        ['2016-11-15 1:00','2016-11-16 2:00','2016-11-16 3:00','2016-11-18 4:00']),
    'values':['a','b','c','d']})
df.index = pd.DatetimeIndex(df['timestamps']).floor('D')
df

yields

            timestamps             values
2016-11-15  "2016-11-15 01:00:00"  a
2016-11-16  "2016-11-16 02:00:00"  b
2016-11-16  "2016-11-16 03:00:00"  c
2016-11-18  "2016-11-18 04:00:00"  d

Due to the duplicate 2016-11-16 date, an attempt to reindex:

all_days = pd.date_range(df.index.min(), df.index.max(), freq='D')
df.reindex(all_days)

fails with:

...
ValueError: cannot reindex from a duplicate axis

(by this it means the index has duplicates, not that it is itself a dup)

Instead, we can use .loc to look up entries for all dates in range:

df.loc[all_days]

yields

            timestamps             values
2016-11-15  "2016-11-15 01:00:00"  a
2016-11-16  "2016-11-16 02:00:00"  b
2016-11-16  "2016-11-16 03:00:00"  c
2016-11-17  NaN                    NaN
2016-11-18  "2016-11-18 04:00:00"  d

fillna can be used on the column series to fill blanks if needed.

Python list subtraction operation

The other solutions have one of a few problems:

  1. They don't preserve order, or
  2. They don't remove a precise count of elements, e.g. for x = [1, 2, 2, 2] and y = [2, 2] they convert y to a set, and either remove all matching elements (leaving [1] only) or remove one of each unique element (leaving [1, 2, 2]), when the proper behavior would be to remove 2 twice, leaving [1, 2], or
  3. They do O(m * n) work, where an optimal solution can do O(m + n) work

Alain was on the right track with Counter to solve #2 and #3, but that solution will lose ordering. The solution that preserves order (removing the first n copies of each value for n repetitions in the list of values to remove) is:

from collections import Counter

x = [1,2,3,4,3,2,1]  
y = [1,2,2]  
remaining = Counter(y)

out = []
for val in x:
    if remaining[val]:
        remaining[val] -= 1
    else:
        out.append(val)
# out is now [3, 4, 3, 1], having removed the first 1 and both 2s.

Try it online!

To make it remove the last copies of each element, just change the for loop to for val in reversed(x): and add out.reverse() immediately after exiting the for loop.

Constructing the Counter is O(n) in terms of y's length, iterating x is O(n) in terms of x's length, and Counter membership testing and mutation are O(1), while list.append is amortized O(1) (a given append can be O(n), but for many appends, the overall big-O averages O(1) since fewer and fewer of them require a reallocation), so the overall work done is O(m + n).

You can also test for to determine if there were any elements in y that were not removed from x by testing:

remaining = +remaining  # Removes all keys with zero counts from Counter
if remaining:
    # remaining contained elements with non-zero counts

How to replace multiple strings in a file using PowerShell

To get the post by George Howarth working properly with more than one replacement you need to remove the break, assign the output to a variable ($line) and then output the variable:

$lookupTable = @{
    'something1' = 'something1aa'
    'something2' = 'something2bb'
    'something3' = 'something3cc'
    'something4' = 'something4dd'
    'something5' = 'something5dsf'
    'something6' = 'something6dfsfds'
}

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'

Get-Content -Path $original_file | ForEach-Object {
    $line = $_

    $lookupTable.GetEnumerator() | ForEach-Object {
        if ($line -match $_.Key)
        {
            $line = $line -replace $_.Key, $_.Value
        }
    }
   $line
} | Set-Content -Path $destination_file

Extracting the last n characters from a string in R

I used the following code to get the last character of a string.

    substr(output, nchar(stringOfInterest), nchar(stringOfInterest))

You can play with the nchar(stringOfInterest) to figure out how to get last few characters.

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

Usually this kind of error comes when you do DateTime conversion or parsing. Check the calendar setting in the server where the application is hosted, mainly the time zone and short date format, and ensure it's set to the right time zone for the location. Hope this would resolve the issue.

How to make a JSONP request from Javascript without JQuery?

Please find below JavaScript example to make a JSONP call without JQuery:

Also, you can refer my GitHub repository for reference.

https://github.com/shedagemayur/JavaScriptCode/tree/master/jsonp

_x000D_
_x000D_
window.onload = function(){_x000D_
    var callbackMethod = 'callback_' + new Date().getTime();_x000D_
_x000D_
    var script = document.createElement('script');_x000D_
    script.src = 'https://jsonplaceholder.typicode.com/users/1?callback='+callbackMethod;_x000D_
_x000D_
    document.body.appendChild(script);_x000D_
_x000D_
    window[callbackMethod] = function(data){_x000D_
        delete window[callbackMethod];_x000D_
        document.body.removeChild(script);_x000D_
        console.log(data);_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How to select/get drop down option in Selenium 2

in ruby for constantly using, add follow:

module Selenium
  module WebDriver
    class Element
      def select(value)
        self.find_elements(:tag_name => "option").find do |option|
          if option.text == value
            option.click
              return
           end
       end
    end
  end
end

and you will be able to select value:

browser.find_element(:xpath, ".//xpath").select("Value")

How can I get (query string) parameters from the URL in Next.js?

  • Get it by using the below code in the about.js page:

    Enter image description here

_x000D_
_x000D_
// pages/about.js
import Link from 'next/link'
export default ({ url: { query: { name } } }) => (
  <p>Welcome to About! { name }</p>
)
_x000D_
_x000D_
_x000D_

JavaScript - populate drop down list with array

You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:

// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?

See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.

What is the difference between a static and const variable?

A constant value cannot change. A static variable exists to a function, or class, rather than an instance or object.

These two concepts are not mutually exclusive, and can be used together.

insert a NOT NULL column to an existing table

If you aren't allowing the column to be Null you need to provide a default to populate existing rows. e.g.

ALTER TABLE dbo.YourTbl ADD
    newcol int NOT NULL CONSTRAINT DF_YourTbl_newcol DEFAULT 0

On Enterprise Edition this is a metadata only change since 2012

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

My guess is that $_.Name does not exist.

If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_

urlencode vs rawurlencode?

Proof is in the source code of PHP.

I'll take you through a quick process of how to find out this sort of thing on your own in the future any time you want. Bear with me, there'll be a lot of C source code you can skim over (I explain it). If you want to brush up on some C, a good place to start is our SO wiki.

Download the source (or use http://lxr.php.net/ to browse it online), grep all the files for the function name, you'll find something such as this:

PHP 5.3.6 (most recent at time of writing) describes the two functions in their native C code in the file url.c.

RawUrlEncode()

PHP_FUNCTION(rawurlencode)
{
    char *in_str, *out_str;
    int in_str_len, out_str_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str,
                              &in_str_len) == FAILURE) {
        return;
    }

    out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len);
    RETURN_STRINGL(out_str, out_str_len, 0);
}

UrlEncode()

PHP_FUNCTION(urlencode)
{
    char *in_str, *out_str;
    int in_str_len, out_str_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str,
                              &in_str_len) == FAILURE) {
        return;
    }

    out_str = php_url_encode(in_str, in_str_len, &out_str_len);
    RETURN_STRINGL(out_str, out_str_len, 0);
}

Okay, so what's different here?

They both are in essence calling two different internal functions respectively: php_raw_url_encode and php_url_encode

So go look for those functions!

Lets look at php_raw_url_encode

PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length)
{
    register int x, y;
    unsigned char *str;

    str = (unsigned char *) safe_emalloc(3, len, 1);
    for (x = 0, y = 0; len--; x++, y++) {
        str[y] = (unsigned char) s[x];
#ifndef CHARSET_EBCDIC
        if ((str[y] < '0' && str[y] != '-' && str[y] != '.') ||
            (str[y] < 'A' && str[y] > '9') ||
            (str[y] > 'Z' && str[y] < 'a' && str[y] != '_') ||
            (str[y] > 'z' && str[y] != '~')) {
            str[y++] = '%';
            str[y++] = hexchars[(unsigned char) s[x] >> 4];
            str[y] = hexchars[(unsigned char) s[x] & 15];
#else /*CHARSET_EBCDIC*/
        if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) {
            str[y++] = '%';
            str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4];
            str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15];
#endif /*CHARSET_EBCDIC*/
        }
    }
    str[y] = '\0';
    if (new_length) {
        *new_length = y;
    }
    return ((char *) str);
}

And of course, php_url_encode:

PHPAPI char *php_url_encode(char const *s, int len, int *new_length)
{
    register unsigned char c;
    unsigned char *to, *start;
    unsigned char const *from, *end;

    from = (unsigned char *)s;
    end = (unsigned char *)s + len;
    start = to = (unsigned char *) safe_emalloc(3, len, 1);

    while (from < end) {
        c = *from++;

        if (c == ' ') {
            *to++ = '+';
#ifndef CHARSET_EBCDIC
        } else if ((c < '0' && c != '-' && c != '.') ||
                   (c < 'A' && c > '9') ||
                   (c > 'Z' && c < 'a' && c != '_') ||
                   (c > 'z')) {
            to[0] = '%';
            to[1] = hexchars[c >> 4];
            to[2] = hexchars[c & 15];
            to += 3;
#else /*CHARSET_EBCDIC*/
        } else if (!isalnum(c) && strchr("_-.", c) == NULL) {
            /* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */
            to[0] = '%';
            to[1] = hexchars[os_toascii[c] >> 4];
            to[2] = hexchars[os_toascii[c] & 15];
            to += 3;
#endif /*CHARSET_EBCDIC*/
        } else {
            *to++ = c;
        }
    }
    *to = 0;
    if (new_length) {
        *new_length = to - start;
    }
    return (char *) start;
}

One quick bit of knowledge before I move forward, EBCDIC is another character set, similar to ASCII, but a total competitor. PHP attempts to deal with both. But basically, this means byte EBCDIC 0x4c byte isn't the L in ASCII, it's actually a <. I'm sure you see the confusion here.

Both of these functions manage EBCDIC if the web server has defined it.

Also, they both use an array of chars (think string type) hexchars look-up to get some values, the array is described as such:

/* rfc1738:

   ...The characters ";",
   "/", "?", ":", "@", "=" and "&" are the characters which may be
   reserved for special meaning within a scheme...

   ...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
   reserved characters used for their reserved purposes may be used
   unencoded within a URL...

   For added safety, we only leave -_. unencoded.
 */

static unsigned char hexchars[] = "0123456789ABCDEF";

Beyond that, the functions are really different, and I'm going to explain them in ASCII and EBCDIC.

Differences in ASCII:

URLENCODE:

  • Calculates a start/end length of the input string, allocates memory
  • Walks through a while-loop, increments until we reach the end of the string
  • Grabs the present character
  • If the character is equal to ASCII Char 0x20 (ie, a "space"), add a + sign to the output string.
  • If it's not a space, and it's also not alphanumeric (isalnum(c)), and also isn't and _, -, or . character, then we , output a % sign to array position 0, do an array look up to the hexchars array for a lookup for os_toascii array (an array from Apache that translates char to hex code) for the key of c (the present character), we then bitwise shift right by 4, assign that value to the character 1, and to position 2 we assign the same lookup, except we preform a logical and to see if the value is 15 (0xF), and return a 1 in that case, or a 0 otherwise. At the end, you'll end up with something encoded.
  • If it ends up it's not a space, it's alphanumeric or one of the _-. chars, it outputs exactly what it is.

RAWURLENCODE:

  • Allocates memory for the string
  • Iterates over it based on length provided in function call (not calculated in function as with URLENCODE).

Note: Many programmers have probably never seen a for loop iterate this way, it's somewhat hackish and not the standard convention used with most for-loops, pay attention, it assigns x and y, checks for exit on len reaching 0, and increments both x and y. I know, it's not what you'd expect, but it's valid code.

  • Assigns the present character to a matching character position in str.
  • It checks if the present character is alphanumeric, or one of the _-. chars, and if it isn't, we do almost the same assignment as with URLENCODE where it preforms lookups, however, we increment differently, using y++ rather than to[1], this is because the strings are being built in different ways, but reach the same goal at the end anyway.
  • When the loop's done and the length's gone, It actually terminates the string, assigning the \0 byte.
  • It returns the encoded string.

Differences:

  • UrlEncode checks for space, assigns a + sign, RawURLEncode does not.
  • UrlEncode does not assign a \0 byte to the string, RawUrlEncode does (this may be a moot point)
  • They iterate differntly, one may be prone to overflow with malformed strings, I'm merely suggesting this and I haven't actually investigated.

They basically iterate differently, one assigns a + sign in the event of ASCII 20.

Differences in EBCDIC:

URLENCODE:

  • Same iteration setup as with ASCII
  • Still translating the "space" character to a + sign. Note-- I think this needs to be compiled in EBCDIC or you'll end up with a bug? Can someone edit and confirm this?
  • It checks if the present char is a char before 0, with the exception of being a . or -, OR less than A but greater than char 9, OR greater than Z and less than a but not a _. OR greater than z (yeah, EBCDIC is kinda messed up to work with). If it matches any of those, do a similar lookup as found in the ASCII version (it just doesn't require a lookup in os_toascii).

RAWURLENCODE:

  • Same iteration setup as with ASCII
  • Same check as described in the EBCDIC version of URL Encode, with the exception that if it's greater than z, it excludes ~ from the URL encode.
  • Same assignment as the ASCII RawUrlEncode
  • Still appending the \0 byte to the string before return.

Grand Summary

  • Both use the same hexchars lookup table
  • URIEncode doesn't terminate a string with \0, raw does.
  • If you're working in EBCDIC I'd suggest using RawUrlEncode, as it manages the ~ that UrlEncode does not (this is a reported issue). It's worth noting that ASCII and EBCDIC 0x20 are both spaces.
  • They iterate differently, one may be faster, one may be prone to memory or string based exploits.
  • URIEncode makes a space into +, RawUrlEncode makes a space into %20 via array lookups.

Disclaimer: I haven't touched C in years, and I haven't looked at EBCDIC in a really really long time. If I'm wrong somewhere, let me know.

Suggested implementations

Based on all of this, rawurlencode is the way to go most of the time. As you see in Jonathan Fingland's answer, stick with it in most cases. It deals with the modern scheme for URI components, where as urlencode does things the old school way, where + meant "space."

If you're trying to convert between the old format and new formats, be sure that your code doesn't goof up and turn something that's a decoded + sign into a space by accidentally double-encoding, or similar "oops" scenarios around this space/20%/+ issue.

If you're working on an older system with older software that doesn't prefer the new format, stick with urlencode, however, I believe %20 will actually be backwards compatible, as under the old standard %20 worked, just wasn't preferred. Give it a shot if you're up for playing around, let us know how it worked out for you.

Basically, you should stick with raw, unless your EBCDIC system really hates you. Most programmers will never run into EBCDIC on any system made after the year 2000, maybe even 1990 (that's pushing, but still likely in my opinion).

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

Passing an array of data as an input parameter to an Oracle procedure

This is one way to do it:

SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
  2  /

Type created

SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
  2  BEGIN
  3    FOR i IN 1..t_in.count LOOP
  4      dbms_output.put_line(t_in(i));
  5    END LOOP;
  6  END;
  7  /

Procedure created

SQL> DECLARE
  2    v_t MyType;
  3  BEGIN
  4    v_t := MyType();
  5    v_t.EXTEND(10);
  6    v_t(1) := 'this is a test';
  7    v_t(2) := 'A second test line';
  8    testing(v_t);
  9  END;
 10  /

this is a test
A second test line

To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:

SQL> CREATE OR REPLACE PACKAGE p IS
  2    TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
  3  
  4    PROCEDURE pp (inp p_type);
  5  END p;
  6  /

Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
  2    PROCEDURE pp (inp p_type) IS
  3    BEGIN
  4      FOR i IN 1..inp.count LOOP
  5        dbms_output.put_line(inp(i));
  6      END LOOP;
  7    END pp;
  8  END p;
  9  /

Package body created
SQL> DECLARE
  2    v_t p.p_type;
  3  BEGIN
  4    v_t(1) := 'this is a test of p';
  5    v_t(2) := 'A second test line for p';
  6    p.pp(v_t);
  7  END;
  8  /

this is a test of p
A second test line for p

PL/SQL procedure successfully completed

SQL> 

This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.

How to search for a string in an arraylist

May be easier using a java.util.HashSet. For example:

  List <String> list = new ArrayList<String>(); 
  list.add("behold");
  list.add("bend");
  list.add("bet");

  //Load the list into a hashSet
  Set<String> set = new HashSet<String>(list);
  if (set.contains("bend"))
  {
    System.out.println("String found!");
  }

jQuery hasAttr checking to see if there is an attribute on an element

You can also use it with attributes such as disabled="disabled" on the form fields etc. like so:

$("#change_password").click(function() {
    var target = $(this).attr("rel");
    if($("#" + target).attr("disabled")) {
        $("#" + target).attr("disabled", false);
    } else {
        $("#" + target).attr("disabled", true);
    }
});

The "rel" attribute stores the id of the target input field.

how to find seconds since 1970 in java

Another option is to use the TimeUtils utility method:

TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)

Spring Rest POST Json RequestBody Content type not supported

In my case I had two Constructors in the bean and I had the same error. I have just deleted one of them and now the issue is fixed!

Case vs If Else If: Which is more efficient?

it can do this for case statements as the values are compiler constants. An explanation in more detail is here http://sequence-points.blogspot.com/2007/10/why-is-switch-statement-faster-than-if.html

Javascript change Div style

function abc() {
    var color = document.getElementById("test").style.color;
    if (color === "red")
         document.getElementById("test").style.color="black";
    else
         document.getElementById("test").style.color="red";
}

How can I add a username and password to Jenkins?

Go to Manage Jenkins > Configure Global Security and select the Enable Security checkbox.

For the basic username/password authentication, I would recommend selecting Jenkins Own User Database for the security realm and then selecting Logged in Users can do anything or a matrix based strategy (in case when you have multiple users with different permissions) for the Authorization.

How to replace NaNs by preceding values in pandas DataFrame?

In my case, we have time series from different devices but some devices could not send any value during some period. So we should create NA values for every device and time period and after that do fillna.

df = pd.DataFrame([["device1", 1, 'first val of device1'], ["device2", 2, 'first val of device2'], ["device3", 3, 'first val of device3']])
df.pivot(index=1, columns=0, values=2).fillna(method='ffill').unstack().reset_index(name='value')

Result:

        0   1   value
0   device1     1   first val of device1
1   device1     2   first val of device1
2   device1     3   first val of device1
3   device2     1   None
4   device2     2   first val of device2
5   device2     3   first val of device2
6   device3     1   None
7   device3     2   None
8   device3     3   first val of device3

Access item in a list of lists

for l in list1:
    val = 50 - l[0] + l[1] - l[2]
    print "val:", val

Loop through list and do operation on the sublist as you wanted.

'innerText' works in IE, but not in Firefox

found this here:

<!--[if lte IE 8]>
    <script type="text/javascript">
        if (Object.defineProperty && Object.getOwnPropertyDescriptor &&
            !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get)
          (function() {
            var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
            Object.defineProperty(Element.prototype, "textContent",
              { // It won't work if you just drop in innerText.get
                // and innerText.set or the whole descriptor.
                get : function() {
                  return innerText.get.call(this)
                },
                set : function(x) {
                  return innerText.set.call(this, x)
                }
              }
            );
          })();
    </script>
<![endif]-->

Calculate difference between two dates (number of days)?

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    DateTime d = Calendar1.SelectedDate;
    // int a;
    TextBox2.Text = d.ToShortDateString();
    string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
    string s1 =  Convert.ToDateTime(Label7.Text).ToShortDateString();
    DateTime dt = Convert.ToDateTime(s).Date;
    DateTime dt1 = Convert.ToDateTime(s1).Date;
    if (dt <= dt1)
    {
        Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
    }
    else
    {
        string diff = dt.Subtract(dt1).ToString();
        Response.Write(diff);
        Label18.Text = diff;
        Session["diff"] = Label18.Text;
    }
}   

Get remote registry value

another option ... needs remoting ...

(invoke-command -ComputerName mymachine -ScriptBlock {Get-ItemProperty HKLM:\SOFTWARE\VanDyke\VShell\License -Name Version }).version

Getting String value from enum in Java

I believe enum have a .name() in its API, pretty simple to use like this example:

private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }

    private enum Security {
            low,
            high
    }

With this you can simply call

yourObject.security() 

and it returns high/low as String, in this example

Spring Boot Java Config Set Session Timeout

server.session.timeout in the application.properties file is now deprecated. The correct setting is:

server.servlet.session.timeout=60s

Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.

How do I jump out of a foreach loop in C#?

how about:

return(sList.Contains("ok"));

That should do the trick if all you want to do is check for an "ok" and return the answer ...

Get the _id of inserted document in Mongo database in NodeJS

There is a second parameter for the callback for collection.insert that will return the doc or docs inserted, which should have _ids.

Try:

collection.insert(objectToInsert, function(err,docsInserted){
    console.log(docsInserted);
});

and check the console to see what I mean.

How do I work with a git repository within another repository?

The key is git submodules.

Start reading the Submodules chapter of the Git Community Book or of the Users Manual

Say you have repository PROJECT1, PROJECT2, and MEDIA...

cd /path/to/PROJECT1
git submodule add ssh://path.to.repo/MEDIA
git commit -m "Added Media submodule"

Repeat on the other repo...

Now, the cool thing is, that any time you commit changes to MEDIA, you can do this:

cd /path/to/PROJECT2/MEDIA
git pull
cd ..
git add MEDIA
git commit -m "Upgraded media to version XYZ"

This just recorded the fact that the MEDIA submodule WITHIN PROJECT2 is now at version XYZ.

It gives you 100% control over what version of MEDIA each project uses. git submodules are great, but you need to experiment and learn about them.

With great power comes the great chance to get bitten in the rump.

Python: Finding differences between elements of a list

>>> t
[1, 3, 6]
>>> [j-i for i, j in zip(t[:-1], t[1:])]  # or use itertools.izip in py2k
[2, 3]

Pass Hidden parameters using response.sendRedirect()

Using session, I successfully passed a parameter (name) from servlet #1 to servlet #2, using response.sendRedirect in servlet #1. Servlet #1 code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    String name = request.getParameter("name");
    String password = request.getParameter("password");
    ...
    request.getSession().setAttribute("name", name);
    response.sendRedirect("/todo.do");

In Servlet #2, you don't need to get name back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name"); ---but you don't need this.

If Servlet #2 calls a JSP, you can show name this way on the JSP webpage:

<h1>Welcome ${name}</h1>

ClassNotFoundException: org.slf4j.LoggerFactory

I had the same on Android. This is how i fixed it:

including ONLY the file:

slf4j-api-1.7.6.jar

in my libs/ folder

Having any additional slf4j* file, caused the NoClassDefFoundError.

Obviously, the rest of the libs can be there (android-support-v4, etc)

Versions: Eclipse Kepler 2013 06 14 - 02 29 ADT 22.3 Android SDK: 4.4.2

Hope someone saves the time i wasted thanks to this!

Where does gcc look for C and C++ header files?

In addition, gcc will look in the directories specified after the -I option.


Create ArrayList from array

If you use :

new ArrayList<T>(Arrays.asList(myArray));

you may create and fill two lists ! Filling twice a big list is exactly what you don't want to do because it will create another Object[] array each time the capacity needs to be extended.

Fortunately the JDK implementation is fast and Arrays.asList(a[]) is very well done. It create a kind of ArrayList named Arrays.ArrayList where the Object[] data points directly to the array.

// in Arrays
@SafeVarargs
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}
//still in Arrays, creating a private unseen class
private static class ArrayList<E>

    private final E[] a;    
    ArrayList(E[] array) {
        a = array; // you point to the previous array
    }
    ....
}

The dangerous side is that if you change the initial array, you change the List ! Are you sure you want that ? Maybe yes, maybe not.

If not, the most understandable way is to do this :

ArrayList<Element> list = new ArrayList<Element>(myArray.length); // you know the initial capacity
for (Element element : myArray) {
    list.add(element);
}

Or as said @glglgl, you can create another independant ArrayList with :

new ArrayList<T>(Arrays.asList(myArray));

I love to use Collections, Arrays, or Guava. But if it don't fit, or you don't feel it, just write another inelegant line instead.

How to check ASP.NET Version loaded on a system?

Look in c:\windows\Microsoft.NET\Framework and you will see various folders starting with "v" indicating the versions of .NET installed.

Fatal error: Call to a member function fetch_assoc() on a non-object

That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::

$result = $this->database->query($query);
if (!$result) {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

That should throw an exception if there's an error...

How do I get the path of a process in Unix / Linux

There's no "guaranteed to work anywhere" method.

Step 1 is to check argv[0], if the program was started by its full path, this would (usually) have the full path. If it was started by a relative path, the same holds (though this requires getting teh current working directory, using getcwd().

Step 2, if none of the above holds, is to get the name of the program, then get the name of the program from argv[0], then get the user's PATH from the environment and go through that to see if there's a suitable executable binary with the same name.

Note that argv[0] is set by the process that execs the program, so it is not 100% reliable.

Adding a y-axis label to secondary y-axis in matplotlib

I don't have access to Python right now, but off the top of my head:

fig = plt.figure()

axes1 = fig.add_subplot(111)
# set props for left y-axis here

axes2 = axes1.twinx()   # mirror them
axes2.set_ylabel(...)

Eclipse error "Could not find or load main class"

If You are using eclipse then the following steps will solve your problem:

Go to Run -> Run Configurations -> Main Class Search -> Locate your class manually -> Apply -> Run

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

How to convert a Java String to an ASCII byte array?

In my string I have Thai characters (TIS620 encoded) and German umlauts. The answer from agiles put me on the right path. Instead of .getBytes() I use now

  int len = mString.length(); // Length of the string
  byte[] dataset = new byte[len];
  for (int i = 0; i < len; ++i) {
     char c = mString.charAt(i);
     dataset[i]= (byte) c;
  }

Select elements by attribute in CSS

    [data-value] {
  /* Attribute exists */
}

[data-value="foo"] {
  /* Attribute has this exact value */
}

[data-value*="foo"] {
  /* Attribute value contains this value somewhere in it */
}

[data-value~="foo"] {
  /* Attribute has this value in a space-separated list somewhere */
}

[data-value^="foo"] {
  /* Attribute value starts with this */
}

[data-value|="foo"] {
  /* Attribute value starts with this in a dash-separated list */
}

[data-value$="foo"] {
  /* Attribute value ends with this */
}

How to transform numpy.matrix or array to scipy sparse matrix

There are several sparse matrix classes in scipy.

bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix

Any of them can do the conversion.

import numpy as np
from scipy import sparse
a=np.array([[1,0,1],[0,0,1]])
b=sparse.csr_matrix(a)
print(b)

(0, 0)  1
(0, 2)  1
(1, 2)  1

See http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information .

Sonar properties files

Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem

Split by comma and strip whitespace in Python

Split using a regular expression. Note I made the case more general with leading spaces. The list comprehension is to remove the null strings at the front and back.

>>> import re
>>> string = "  blah, lots  ,  of ,  spaces, here "
>>> pattern = re.compile("^\s+|\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['blah', 'lots', 'of', 'spaces', 'here']

This works even if ^\s+ doesn't match:

>>> string = "foo,   bar  "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>

Here's why you need ^\s+:

>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['  blah', 'lots', 'of', 'spaces', 'here']

See the leading spaces in blah?

Clarification: above uses the Python 3 interpreter, but results are the same in Python 2.

PHP check if file is an image

Native way to get the mimetype:

For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()

Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.

While mime_content_type is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).

If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.

function getMimeType($filename)
{
    $mimetype = false;
    if(function_exists('finfo_open')) {
        // open with FileInfo
    } elseif(function_exists('getimagesize')) {
        // open with GD
    } elseif(function_exists('exif_imagetype')) {
       // open with EXIF
    } elseif(function_exists('mime_content_type')) {
       $mimetype = mime_content_type($filename);
    }
    return $mimetype;
}

List columns with indexes in PostgreSQL

Here's a function that wraps cope360's answer:

CREATE OR REPLACE FUNCTION getIndices(_table_name varchar)
  RETURNS TABLE(table_name varchar, index_name varchar, column_name varchar) AS $$
  BEGIN
    RETURN QUERY
    select
    t.relname::varchar as table_name,
    i.relname::varchar as index_name,
    a.attname::varchar as column_name
from
    pg_class t,
    pg_class i,
    pg_index ix,
    pg_attribute a
where
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and a.attrelid = t.oid
    and a.attnum = ANY(ix.indkey)
    and t.relkind = 'r'
    and t.relname = _table_name
order by
    t.relname,
    i.relname;
  END;
  $$ LANGUAGE plpgsql;

Usage:

select * from getIndices('<my_table>')

.htaccess redirect http to https

Add this code at the end of your .htaccess file

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Write HTML string in JSON

You could make the identifier a param for a query selector. For PHP and compatible languages use an associative array (in effect an objects) and then json_encode.

$temp=array('#id'  =>array('href'=>'services.html')
           ,'img'  =>array('src'=>"img/SolutionInnerbananer.jpg")
           ,'.html'=>'<h2 class="fg-white">AboutUs</h2><p class="fg-white">...</p>'
           );
echo json_encode($temp);  

But HTML don't do it for you without some JS.

{"#id":{"href":"services.html"},"img":{"src":"img\/SolutionInnerbananer.jpg"}
 ,".html":"<h2 class=\"fg-white\">AboutUs<\/h2><p class=\"fg-white\">...<\/p>"}

How to convert float number to Binary?

Consider below example

Convert 2.625 to binary.

We will consider the integer and fractional part separately.

The integral part is easy, 2 = 10. 

For the fractional part:

0.625   × 2 =   1.25    1   Generate 1 and continue with the rest.
0.25    × 2 =   0.5     0   Generate 0 and continue.
0.5     × 2 =   1.0     1   Generate 1 and nothing remains.

So 0.625 = 0.101, and 2.625 = 10.101.

See this link for more information.

ImportError: DLL load failed: The specified module could not be found

I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: https://www.microsoft.com/en-us/download/details.aspx?id=48145 fixed the missing DLLs.

I find it better and easier than downloading and pasting DLLs.

Socket accept - "Too many open files"

Just another information about CentOS. In this case, when using "systemctl" to launch process. You have to modify the system file ==> /usr/lib/systemd/system/processName.service .Had this line in the file :

LimitNOFILE=50000

And just reload your system conf :

systemctl daemon-reload

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

If you got any error on your console by saying, “Embedded servlet container failed to start. Port 8080 was already in use.” Then go to application.properties file and add this property “server.port = 8090”.

Actually the default port for spring boot is 8080, if you have something else on that port, the above error will occur. So we are asking spring boot to run on other port by adding “server.port = 8090” in application.properties file.

Controlling number of decimal digits in print output in R

The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options value as a default.

As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.

Mathematica or Maple will allow you to give as many decimal places as your heart desires.

EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.

On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin (usually 2e-308).

Compare these two analyses.

x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1)  #Should throw an error

x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2)  #ok

In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.


As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr package.

mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")

These are slower and more memory intensive to use than regular (double precision) numeric vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.

How can I write variables inside the tasks file in ansible

I know, it is long ago, but since the easiest answer was not yet posted I will do so for other user that might step by.

Just move the var inside the "name" block:

- name: Download apache
  vars:
    url: czxcxz
  shell: wget {{url}} 

Change the project theme in Android Studio?

In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click on android:theme = "@style/AppTheme" in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

At parent= in styles.xml you can browse all available styles by using auto-complete inside the "". E.g. try parent="Theme." with your cursor right after the . and then pressing Ctrl + Space.

You can also preview themes in the preview window in Android Studio.

enter image description here

Maximum length for MD5 input/output

MD5 processes an arbitrary-length message into a fixed-length output of 128 bits, typically represented as a sequence of 32 hexadecimal digits.

ggplot2 legend to bottom and horizontal

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

When should I really use noexcept?

In Bjarne's words (The C++ Programming Language, 4th Edition, page 366):

Where termination is an acceptable response, an uncaught exception will achieve that because it turns into a call of terminate() (§13.5.2.5). Also, a noexcept specifier (§13.5.1.1) can make that desire explicit.

Successful fault-tolerant systems are multilevel. Each level copes with as many errors as it can without getting too contorted and leaves the rest to higher levels. Exceptions support that view. Furthermore, terminate() supports this view by providing an escape if the exception-handling mechanism itself is corrupted or if it has been incompletely used, thus leaving exceptions uncaught. Similarly, noexcept provides a simple escape for errors where trying to recover seems infeasible.

double compute(double x) noexcept;     {
    string s = "Courtney and Anya";
    vector<double> tmp(10);
    // ...
}

The vector constructor may fail to acquire memory for its ten doubles and throw a std::bad_alloc. In that case, the program terminates. It terminates unconditionally by invoking std::terminate() (§30.4.1.3). It does not invoke destructors from calling functions. It is implementation-defined whether destructors from scopes between the throw and the noexcept (e.g., for s in compute()) are invoked. The program is just about to terminate, so we should not depend on any object anyway. By adding a noexcept specifier, we indicate that our code was not written to cope with a throw.

No String-argument constructor/factory method to deserialize from String value ('')

Use below code snippet This worked for me

ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"symbol\":\"ABCD\}";
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
Trade trade = objectMapper.readValue(jsonString, new TypeReference<Symbol>() {});

Model Class

@JsonIgnoreProperties    public class Symbol {
    @JsonProperty("symbol")
    private String symbol;
}

Android - Activity vs FragmentActivity?

ianhanniballake is right. You can get all the functionality of Activity from FragmentActivity. In fact, FragmentActivity has more functionality.

Using FragmentActivity you can easily build tab and swap format. For each tab you can use different Fragment (Fragments are reusable). So for any FragmentActivity you can reuse the same Fragment.

Still you can use Activity for single pages like list down something and edit element of the list in next page.

Also remember to use Activity if you are using android.app.Fragment; use FragmentActivity if you are using android.support.v4.app.Fragment. Never attach a android.support.v4.app.Fragment to an android.app.Activity, as this will cause an exception to be thrown.

Duplicate line in Visual Studio Code

Ubuntu :

  • Duplicate Line Up : Ctrl + Alt + Shift + 8
  • Duplicate Line Down : Ctrl + Alt + Shift + 2

Colouring plot by factor in R

data<-iris
plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)
legend(7,4.3,unique(data$Species),col=1:length(data$Species),pch=1)

should do it for you. But I prefer ggplot2 and would suggest that for better graphics in R.

apache ProxyPass: how to preserve original IP address

If you have the capability to do so, I would recommend using either mod-jk or mod-proxy-ajp to pass requests from Apache to JBoss. The AJP protocol is much more efficient compared to using HTTP proxy requests and as a benefit, JBoss will see the request as coming from the original client and not Apache.

How to add multiple font files for the same font?

nowadays,2017-12-17. I don't find any description about Font-property-order‘s necessity in spec. And I test in chrome always works whatever the order is.

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-weight: 900;
  src: url('#{$fa-font-path}/fa-solid-900.eot');
  src: url('#{$fa-font-path}/fa-solid-900.eot?#iefix') format('embedded-opentype'),
  url('#{$fa-font-path}/fa-solid-900.woff2') format('woff2'),
  url('#{$fa-font-path}/fa-solid-900.woff') format('woff'),
  url('#{$fa-font-path}/fa-solid-900.ttf') format('truetype'),
  url('#{$fa-font-path}/fa-solid-900.svg#fontawesome') format('svg');
}

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-weight: 400;
  src: url('#{$fa-font-path}/fa-regular-400.eot');
  src: url('#{$fa-font-path}/fa-regular-400.eot?#iefix') format('embedded-opentype'),
  url('#{$fa-font-path}/fa-regular-400.woff2') format('woff2'),
  url('#{$fa-font-path}/fa-regular-400.woff') format('woff'),
  url('#{$fa-font-path}/fa-regular-400.ttf') format('truetype'),
  url('#{$fa-font-path}/fa-regular-400.svg#fontawesome') format('svg');
}

Using Apache httpclient for https

I put together this test app to reproduce the issue using the HTTP testing framework from the Apache HttpClient package:

ClassLoader cl = HCTest.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore  = KeyStore.getInstance("jks");
char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);

TrustManagerFactory tmf = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
TrustManager[] tm = tmf.getTrustManagers();

KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
        KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, pwd);
KeyManager[] km = kmfactory.getKeyManagers();

SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(km, tm, null);

LocalTestServer localServer = new LocalTestServer(sslcontext);
localServer.registerDefaultHandlers();

localServer.start();
try {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    TrustStrategy trustStrategy = new TrustStrategy() {

        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            for (X509Certificate cert: chain) {
                System.err.println(cert);
            }
            return false;
        }

    };

    SSLSocketFactory sslsf = new SSLSocketFactory("TLS", null, null, keystore, null,
            trustStrategy, new AllowAllHostnameVerifier());
    Scheme https = new Scheme("https", 443, sslsf);
    httpclient.getConnectionManager().getSchemeRegistry().register(https);

    InetSocketAddress address = localServer.getServiceAddress();
    HttpHost target1 = new HttpHost(address.getHostName(), address.getPort(), "https");
    HttpGet httpget1 = new HttpGet("/random/100");
    HttpResponse response1 = httpclient.execute(target1, httpget1);
    System.err.println(response1.getStatusLine());
    HttpEntity entity1 = response1.getEntity();
    EntityUtils.consume(entity1);
    HttpHost target2 = new HttpHost("www.verisign.com", 443, "https");
    HttpGet httpget2 = new HttpGet("/");
    HttpResponse response2 = httpclient.execute(target2, httpget2);
    System.err.println(response2.getStatusLine());
    HttpEntity entity2 = response2.getEntity();
    EntityUtils.consume(entity2);
} finally {
    localServer.stop();
}

Even though, Sun's JSSE implementation appears to always read the trust material from the default trust store for some reason, it does not seem to get added to the SSL context and to impact the process of trust verification during the SSL handshake.

Here's the output of the test app. As you can see, the first request succeeds whereas the second fails as the connection to www.verisign.com is rejected as untrusted.

[
[
  Version: V1
  Subject: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
  Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3

  Key:  Sun DSA Public Key
    Parameters:DSA
    p:     fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669
    455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7
    6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb
    83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7
    q:     9760508f 15230bcc b292b982 a2eb840b f0581cf5
    g:     f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
    5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
    3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
    cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a

  y:
    f0cc639f 702fd3b1 03fa8fa6 676c3756 ea505448 23cd1147 fdfa2d7f 662f7c59
    a02ddc1a fd76673e 25210344 cebbc0e7 6250fff1 a814a59f 30ff5c7e c4f186d8
    f0fd346c 29ea270d b054c040 c74a9fc0 55a7020f eacf9f66 a0d86d04 4f4d23de
    7f1d681f 45c4c674 5762b71b 808ded17 05b74baf 8de3c4ab 2ef662e3 053af09e

  Validity: [From: Sat Dec 11 14:48:35 CET 2004,
               To: Tue Dec 09 14:48:35 CET 2014]
  Issuer: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
  SerialNumber: [    41bafab3]

]
  Algorithm: [SHA1withDSA]
  Signature:
0000: 30 2D 02 15 00 85 BE 6B   D0 91 EF 34 72 05 FF 1A  0-.....k...4r...
0010: DB F6 DE BF 92 53 9B 14   27 02 14 37 8D E8 CB AC  .....S..'..7....
0020: 4E 6C 93 F2 1F 7D 20 A1   2D 6F 80 5F 58 AE 33     Nl.... .-o._X.3

]
HTTP/1.1 200 OK
[
[
  Version: V3
  Subject: CN=www.verisign.com, OU=" Production Security Services", O="VeriSign, Inc.", STREET=487 East Middlefield Road, L=Mountain View, ST=California, OID.2.5.4.17=94043, C=US, SERIALNUMBER=2497886, OID.2.5.4.15="V1.0, Clause 5.(b)", OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US
  Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5

  Key:  Sun RSA public key, 2048 bits
  modulus: 20699622354183393041832954221256409980425015218949582822286196083815087464214375375678538878841956356687753084333860738385445545061253653910861690581771234068858443439641948884498053425403458465980515883570440998475638309355278206558031134532548167239684215445939526428677429035048018486881592078320341210422026566944903775926801017506416629554190534665876551381066249522794321313235316733139718653035476771717662585319643139144923795822646805045585537550376512087897918635167815735560529881178122744633480557211052246428978388768010050150525266771462988042507883304193993556759733514505590387262811565107773578140271
  public exponent: 65537
  Validity: [From: Wed May 26 02:00:00 CEST 2010,
               To: Sat May 26 01:59:59 CEST 2012]
  Issuer: CN=VeriSign Class 3 Extended Validation SSL SGC CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
  SerialNumber: [    53d2bef9 24a7245e 83ca01e4 6caa2477]

Certificate Extensions: 10
[1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
  [accessMethod: 1.3.6.1.5.5.7.48.1
   accessLocation: URIName: http://EVIntl-ocsp.verisign.com, accessMethod: 1.3.6.1.5.5.7.48.2
   accessLocation: URIName: http://EVIntl-aia.verisign.com/EVIntl2006.cer]
]

...

]
Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
    at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:345)
    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
    at org.apache.http.conn.ssl.SSLSocketFactory.createLayeredSocket(SSLSocketFactory.java:446)
...

Emulate/Simulate iOS in Linux

BrowserStack.com
On this site, you can emulate a lot of iOS's devices online.

ASP.NET MVC - Getting QueryString values

I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.

Batch file to run a command in cmd within a directory

CMD.EXE will not execute internal commands contained inside the string. Only actual files can be launched with that string.

You will need to actually call a batch file to do what you want.

BAT1.bat

start cmd.exe /k bat2.bat

BAT2.bat

cd C:\activiti-5.9\setup
ant demo.start

You may want to create a folder called BAT, and add it's location to your path. So if you create C:\BAT, add C:\BAT\; to the path. The path is located at:

    click -> Start -> right-click Computer -> Properties ->
    click -> Avanced System Settings -> Environment Variables
   select -> Path (From either list. User Variables are specific to 
                   your profile, System Variables are, duh, system-wide.)
    Click -> Edit
Press the -> the [END] or [HOME] key.
     Type -> C:\BAT\;
    Click -> OK -> OK

Now place all your batch files in C:\BAT and they will be found, regardless of the current directory.

How to load local html file into UIWebView

Make sure "html_files" is a directory in your app's main bundle, and not just a group in Xcode.

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

I was facing same issue, tried restarting my server, reopening editor but computer restart did the magic.

P.S: I was facing issue on a windows machine and issue occurred when I moved module into a new folder.

Properly close mongoose's connection once you're done

Probably you have this:

const db = mongoose.connect('mongodb://localhost:27017/db');

// Do some stuff

db.disconnect();

but you can also have something like this:

mongoose.connect('mongodb://localhost:27017/db');

const model = mongoose.model('Model', ModelSchema);

model.find().then(doc => {
  console.log(doc);
}

you cannot call db.disconnect() but you can close the connection after you use it.

model.find().then(doc => {
  console.log(doc);
}).then(() => {
  mongoose.connection.close();
});

Re-sign IPA (iPhone)

Thank you, Erik, for posting this. This worked for me. I'd like to add a note about an extra step I needed. Within "Payload/Application.app/" there was a directory named "CACertChains" that contained a file named "cacert.pem". I had to remove the directory and the .pem to complete these steps. Thanks again! –

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

You cannot.

According to the XML Schema specification, a boolean is true or false. True is not valid:


  3.2.2.1 Lexical representation
  An instance of a datatype that is defined as ·boolean· can have the 
  following legal literals {true, false, 1, 0}. 

  3.2.2.2 Canonical representation
  The canonical representation for boolean is the set of 
  literals {true, false}. 

If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.

Determine a string's encoding in C#

I know this is a bit late - but to be clear:

A string doesn't really have encoding... in .NET the a string is a collection of char objects. Essentially, if it is a string, it has already been decoded.

However if you are reading the contents of a file, which is made of bytes, and wish to convert that to a string, then the file's encoding must be used.

.NET includes encoding and decoding classes for: ASCII, UTF7, UTF8, UTF32 and more.

Most of these encodings contain certain byte-order marks that can be used to distinguish which encoding type was used.

The .NET class System.IO.StreamReader is able to determine the encoding used within a stream, by reading those byte-order marks;

Here is an example:

    /// <summary>
    /// return the detected encoding and the contents of the file.
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="contents"></param>
    /// <returns></returns>
    public static Encoding DetectEncoding(String fileName, out String contents)
    {
        // open the file with the stream-reader:
        using (StreamReader reader = new StreamReader(fileName, true))
        {
            // read the contents of the file into a string
            contents = reader.ReadToEnd();

            // return the encoding.
            return reader.CurrentEncoding;
        }
    }

MySQL ORDER BY rand(), name ASC

SELECT  *
FROM    (
        SELECT  *
        FROM    users
        WHERE   1
        ORDER BY
                rand()
        LIMIT 20
        ) q
ORDER BY
        name

Back to previous page with header( "Location: " ); in PHP

try:

header('Location: ' . $_SERVER['HTTP_REFERER']);

Note that this may not work with secure pages (HTTPS) and it's a pretty bad idea overall as the header can be hijacked, sending the user to some other destination. The header may not even be sent by the browser.

Ideally, you will want to either:

  • Append the return address to the request as a query variable (eg. ?back=/list)
  • Define a return page in your code (ie. all successful form submissions redirect to the listing page)
  • Provide the user the option of where they want to go next (eg. Save and continue editing or just Save)

How to make a transparent HTML button?

<div class="button_style">
This is your button value
</div>

.button_style{   
background-color: Transparent;
border: none;             /* Your can add different style/properties of button Here*/
cursor:pointer;    
}

How to compare only date in moment.js

Meanwhile you can use the isSameOrAfter method:

moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');

Docs: https://momentjs.com/docs/#/query/is-same-or-after/

Compare two columns using pandas

Wrap each individual condition in parentheses, and then use the & operator to combine the conditions:

df.loc[(df['one'] >= df['two']) & (df['one'] <= df['three']), 'que'] = df['one']

You can fill the non-matching rows by just using ~ (the "not" operator) to invert the match:

df.loc[~ ((df['one'] >= df['two']) & (df['one'] <= df['three'])), 'que'] = ''

You need to use & and ~ rather than and and not because the & and ~ operators work element-by-element.

The final result:

df
Out[8]: 
  one  two three que
0  10  1.2   4.2  10
1  15   70  0.03    
2   8    5     0  

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

Can you force Vue.js to reload/re-render?

I had this issue with an image gallery that I wanted to rerender due to changes made on a different tab. So tab1 = imageGallery, tab2 = favoriteImages

tab @change="updateGallery()" -> this forces my v-for directive to process the filteredImages function every time I switch tabs.

<script>
export default {
  data() {
    return {
      currentTab: 0,
      tab: null,
      colorFilter: "",
      colors: ["None", "Beige", "Black"], 
      items: ["Image Gallery", "Favorite Images"]
    };
  },
  methods: {
    filteredImages: function() {
      return this.$store.getters.getImageDatabase.filter(img => {
        if (img.color.match(this.colorFilter)) return true;
      });
    },
    updateGallery: async function() {
      // instance is responsive to changes
      // change is made and forces filteredImages to do its thing
      // async await forces the browser to slow down and allows changes to take effect
      await this.$nextTick(function() {
        this.colorFilter = "Black";
      });

      await this.$nextTick(function() {
        // Doesnt hurt to zero out filters on change
        this.colorFilter = "";
      });
    }
  }
};
</script>

How to switch from POST to GET in PHP CURL

CURL request by default is GET, you don't have to set any options to make a GET CURL request.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I have used MySQL DB for Hive MetaStore. Please follow the below steps:

  • in hive-site.xml the metastore should be proper
<property>
 <name>javax.jdo.option.ConnectionURL</name> 
 <value>jdbc:mysql://localhost/metastorecreateDatabaseIfNotExist=true&amp;useSSL=false</value>
</property>
  • go to the mysql: mysql -u hduser -p
  • then run drop database metastore
  • then come out from MySQL and execute schematool -initSchema dbType mysql

Now error will go.

Targeting .NET Framework 4.5 via Visual Studio 2010

From another search. Worked for me!

"You can use Visual Studio 2010 and it does support it, provided your OS supports .NET 4.5.

Right click on your solution to add a reference (as you do). When the dialog box shows, select browse, then navigate to the following folder:

C:\Program Files(x86)\Reference Assemblies\Microsoft\Framework\.Net Framework\4.5

You will find it there."

How to remove array element in mongodb?

You can simply use $pull to remove a sub-document. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

Collection.update({
    _id: parentDocumentId
  }, {
    $pull: {
      subDocument: {
        _id: SubDocumentId
      }
    }
  });

This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.

Read more about pull here.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

What worked for me was stopping the Internet Information Services (IIS). If you are using Windows 7, click on your Start button and in your search box, type "iis". Click on "Internet Information Services (IIS) Manager". When the window pops up, and assuming you've got none of the icons selected, you should just be able to click Stop on the right action pane. My XAMPP Apache started right up. Hope it all worked out for you.

Auto Increment after delete in MySQL

I got a very simple but tricky method.

While deleting a row, you can preserve the IDs into another temporary table. After that, when you will insert new data into the main table then you can search and pick IDs from the temporary table. So use a checking here. If the temporary table has no IDs then calculate maximum ID into the main table and set the new ID as: new_ID = old_max_ID+1.

NB: You can not use auto-increment feature here.

How do I make a text go onto the next line if it overflows?

In order to use word-wrap: break-word, you need to set a width (in px). For example:

div {
    width: 250px;
    word-wrap: break-word;
}

word-wrap is a CSS3 property, but it should work in all browsers, including IE 5.5-9.

C++ unordered_map using a custom class type as the key

To be able to use std::unordered_map (or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:

  1. A hash function; this must be a class that overrides operator() and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash template for your key-type.

  2. A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator(), or as a specialization of std::equal, or – easiest of all – by overloading operator==() for your key type (as you did already).

The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.

A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:

struct Key
{
  std::string first;
  std::string second;
  int         third;

  bool operator==(const Key &other) const
  { return (first == other.first
            && second == other.second
            && third == other.third);
  }
};

Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):

namespace std {

  template <>
  struct hash<Key>
  {
    std::size_t operator()(const Key& k) const
    {
      using std::size_t;
      using std::hash;
      using std::string;

      // Compute individual hash values for first,
      // second and third and combine them using XOR
      // and bit shifting:

      return ((hash<string>()(k.first)
               ^ (hash<string>()(k.second) << 1)) >> 1)
               ^ (hash<int>()(k.third) << 1);
    }
  };

}

With this in place, you can instantiate a std::unordered_map for the key-type:

int main()
{
  std::unordered_map<Key,std::string> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}

It will automatically use std::hash<Key> as defined above for the hash value calculations, and the operator== defined as member function of Key for equality checks.

If you don't want to specialize template inside the std namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
    using std::size_t;
    using std::hash;
    using std::string;

    return ((hash<string>()(k.first)
             ^ (hash<string>()(k.second) << 1)) >> 1)
             ^ (hash<int>()(k.third) << 1);
  }
};

int main()
{
  std::unordered_map<Key,std::string,KeyHasher> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}

How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.

This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value and hash_combine function template from the Boost library. The former acts in a similar way as std::hash for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:

#include <boost/functional/hash.hpp>

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
      using boost::hash_value;
      using boost::hash_combine;

      // Start with a hash value of 0    .
      std::size_t seed = 0;

      // Modify 'seed' by XORing and bit-shifting in
      // one member of 'Key' after the other:
      hash_combine(seed,hash_value(k.first));
      hash_combine(seed,hash_value(k.second));
      hash_combine(seed,hash_value(k.third));

      // Return the result.
      return seed;
  }
};

And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:

namespace std
{
    template <>
    struct hash<Key>
    {
        size_t operator()( const Key& k ) const
        {
            // Compute individual hash values for first, second and third
            // http://stackoverflow.com/a/1646913/126995
            size_t res = 17;
            res = res * 31 + hash<string>()( k.first );
            res = res * 31 + hash<string>()( k.second );
            res = res * 31 + hash<int>()( k.third );
            return res;
        }
    };
}

Skipping Iterations in Python

I think you're looking for continue

How to get a specific output iterating a hash in Ruby?

The most basic way to iterate over a hash is as follows:

hash.each do |key, value|
  puts key
  puts value
end

How to convert SQL Server's timestamp column to datetime format

for me works: TO_DATE('19700101', 'yyyymmdd') + (TIME / 24 / 60 / 60) (oracle DB)

Can I multiply strings in Java to repeat sequences?

Similar to what has already been said:

public String multStuff(String first, String toAdd, int amount) { 
    String append = "";
    for (int i = 1; i <= amount; i++) {
        append += toAdd;               
    }
    return first + append;
}

Input multStuff("123", "0", 3);

Output "123000"

Parsing time string in Python

Your best bet is to have a look at strptime()

Something along the lines of

>>> from datetime import datetime
>>> date_str = 'Tue May 08 15:14:45 +0800 2012'
>>> date = datetime.strptime(date_str, '%a %B %d %H:%M:%S +0800 %Y')
>>> date
datetime.datetime(2012, 5, 8, 15, 14, 45)

Im not sure how to do the +0800 timezone unfortunately, maybe someone else can help out with that.

The formatting strings can be found at http://docs.python.org/library/time.html#time.strftime and are the same for formatting the string for printing.

Hope that helps

Mark

PS, Your best bet for timezones in installing pytz from pypi. ( http://pytz.sourceforge.net/ ) in fact I think pytz has a great datetime parsing method if i remember correctly. The standard lib is a little thin on the ground with timezone functionality.

VBA macro that search for file in multiple subfolders

Just for fun, here's a sample with a recursive function which (I hope) should be a bit simpler to understand and to use with your code:

Function Recurse(sPath As String) As String

    Dim FSO As New FileSystemObject
    Dim myFolder As Folder
    Dim mySubFolder As Folder

    Set myFolder = FSO.GetFolder(sPath)
    For Each mySubFolder In myFolder.SubFolders
        Call TestSub(mySubFolder.Path)
        Recurse = Recurse(mySubFolder.Path)
    Next

End Function

Sub TestR()

    Call Recurse("D:\Projets\")

End Sub

Sub TestSub(ByVal s As String)

    Debug.Print s

End Sub

Edit: Here's how you can implement this code in your workbook to achieve your objective.

Sub TestSub(ByVal s As String)

    Dim FSO As New FileSystemObject
    Dim myFolder As Folder
    Dim myFile As File

    Set myFolder = FSO.GetFolder(s)
    For Each myFile In myFolder.Files
        If myFile.Name = Range("E1").Value Then
            Debug.Print myFile.Name 'Or do whatever you want with the file
        End If
    Next

End Sub

Here, I just debug the name of the found file, the rest is up to you. ;)

Of course, some would say it's a bit clumsy to call twice the FileSystemObject so you could simply write your code like this (depends on wether you want to compartmentalize or not):

Function Recurse(sPath As String) As String

    Dim FSO As New FileSystemObject
    Dim myFolder As Folder
    Dim mySubFolder As Folder
    Dim myFile As File

    Set myFolder = FSO.GetFolder(sPath)

    For Each mySubFolder In myFolder.SubFolders
        For Each myFile In mySubFolder.Files
            If myFile.Name = Range("E1").Value Then
                Debug.Print myFile.Name & " in " & myFile.Path 'Or do whatever you want with the file
                Exit For
            End If
        Next
        Recurse = Recurse(mySubFolder.Path)
    Next

End Function

Sub TestR()

    Call Recurse("D:\Projets\")

End Sub

How do I install g++ for Fedora?

Since Fedora 22 yum has been deprecated so the commands given in other answers will actually fire up 'Dandified yum' i.e. dnf. So the new command to install g++ in recent distributions is

su -c "dnf install gcc-c++"

As of Nov 2015 this installs the 5.1.1 version.
Also note that in Fedora 23 when I gave the command g++ -v, Fedora automatically asked me if I want to install gcc-c++ package. I think thats nice.(After the install it also ran the command g++ -v for me)
Only nit pick that I can do about it is that instead of a progress indicator you just get * Downloading packages... message which you may not like if you are on a slow internet connection.

#1071 - Specified key was too long; max key length is 1000 bytes

I was facing same issue, used below query to resolve it.

While creating DB you can use utf-8 encoding

eg. create database my_db character set utf8 collate utf8mb4;

EDIT: (Considering suggestions from comments) Changed utf8_bin to utf8mb4

Ternary operator ?: vs if...else

I think that there are situations where the inline if can yield "faster" code because of the scope it works at. Object creation and destruction can be costly so consider the follow scenario :

class A{
    public:
    A() : value(0) {
        cout << "Default ctor" << endl;
    }
    A(int myInt) : value(myInt)
    {
        cout << "Overloaded ctor" << endl;
    }

    A& operator=(const A& other){
        cout << "= operator" << endl;
        value = other.value; 
    }

    ~A(){
        cout << "destroyed" << std::endl;
    }

    int value;

};


int main()
{
   {
       A a;
       if(true){
           a = A(5);
       }else{
           a = A(10);
       }
   }

   cout << "Next test" << endl;
   {
        A b = true? A(5) : A(10);
   }
   return 0;
}

With this code, the output will be :

Default ctor                                                                                                                                                                                                                      
Overloaded ctor                                                                                                                                                                                                                   
= operator                                                                                                                                                                                                                        
destroyed                                                                                                                                                                                                                         
destroyed                                                                                                                                                                                                                         
Next test                                                                                                                                                                                                                         
Overloaded ctor                                                                                                                                                                                                                   
destroyed  

So by inlining the if, we save a bunch of operation needed to keep a alive at the same scope as b. While it is highly probable that the condition evaluation speed is pretty equal in both scenarios, changing scope forces you to take other factors into consideration that the inline if allows you to avoid.

ComboBox- SelectionChanged event has old value, not new value

According to MSDN, e.AddedItems:

Gets a list that contains the items that were selected.

So you could use:

private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
}

You could also use SelectedItem if you use string values for the Items from the sender:

private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    string text = (sender as ComboBox).SelectedItem as string;
}

or

private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    string text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
}

Since both Content and SelectedItem are objects, a safer approach would be to use .ToString() instead of as string

HTML entity for check mark

There is HTML entity &#10003 but it doesn't work in some older browsers.

How to add a reference programmatically

Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!

Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278

Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
    Dim rw As Long, ref
    With ThisWorkbook.Sheets(1)
        .Cells.Clear
        rw = 1
        .Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
        For Each ref In ThisWorkbook.VBProject.References
            rw = rw + 1
            .Range("A" & rw & ":D" & rw) = Array(ref.Description, _
                   "v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
        Next ref
        .Range("A:D").Columns.AutoFit
    End With
End Sub

Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.

Sub ListReferencePaths() 
 'Macro purpose:  To determine full path and Globally Unique Identifier (GUID)
 'to each referenced library.  Select the reference in the Tools\References
 'window, then run this code to get the information on the reference's library

On Error Resume Next 
Dim i As Long 

Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID" 

For i = 1 To ThisWorkbook.VBProject.References.Count 
  With ThisWorkbook.VBProject.References(i) 
    Debug.Print .Name & " | " & .FullPath  & " | " & .GUID 
  End With 
Next i 
On Error GoTo 0 
End Sub 

Mapping US zip code to time zone

In addition to Doug Kavendek answer. One could use the following approach to get closer to tz_database.

  1. Download [Free Zip Code Latitude and Longitude Database]
  2. Download [A shapefile of the TZ timezones of the world]
  3. Use any free library for shapefile querying (e.g. .NET Easy GIS .NET, LGPL).
    var shapeFile = new ShapeFile(shapeFilePath);
    var shapeIndex = shapeFile.GetShapeIndexContainingPoint(new PointD(long, lat), 0D);
    var attrValues = shapeFile.GetAttributeFieldValues(shapeIndex);
    var timeZoneId = attrValues[0];

P.S. Can't insert all the links :( So please use search.

gradlew: Permission Denied

You could use "bash" before command:

bash ./gradlew compileDebug --stacktrace

Hive External Table Skip First Row

create external table table_name( 
Year int, 
Month int,
column_name data_type ) 
row format delimited fields terminated by ',' 
location '/user/user_name/example_data' TBLPROPERTIES('serialization.null.format'='', 'skip.header.line.count'='1');

Powershell: How can I stop errors from being displayed in a script?

Add -ErrorAction SilentlyContinue to your script and you'll be good to go.

Username and password in command for git push

Git will not store the password when you use URLs like that. Instead, it will just store the username, so it only needs to prompt you for the password the next time. As explained in the manual, to store the password, you should use an external credential helper. For Windows, you can use the Windows Credential Store for Git. This helper is also included by default in GitHub for Windows.

When using it, your password will automatically be remembered, so you only need to enter it once. So when you clone, you will be asked for your password, and then every further communication with the remote will not prompt you for your password again. Instead, the credential helper will provide Git with the authentication.

This of course only works for authentication via https; for ssh access ([email protected]/repository.git) you use SSH keys and those you can remember using ssh-agent (or PuTTY’s pageant if you’re using plink).

How to install PyQt4 on Windows using pip?

With current latest python 3.6.5

pip3 install PyQt5

works fine

What are the differences between .so and .dylib on osx?

The Mach-O object file format used by Mac OS X for executables and libraries distinguishes between shared libraries and dynamically loaded modules. Use otool -hv some_file to see the filetype of some_file.

Mach-O shared libraries have the file type MH_DYLIB and carry the extension .dylib. They can be linked against with the usual static linker flags, e.g. -lfoo for libfoo.dylib. They can be created by passing the -dynamiclib flag to the compiler. (-fPIC is the default and needn't be specified.)

Loadable modules are called "bundles" in Mach-O speak. They have the file type MH_BUNDLE. They can carry any extension; the extension .bundle is recommended by Apple, but most ported software uses .so for the sake of compatibility. Typically, you'll use bundles for plug-ins that extend an application; in such situations, the bundle will link against the application binary to gain access to the application’s exported API. They can be created by passing the -bundle flag to the compiler.

Both dylibs and bundles can be dynamically loaded using the dl APIs (e.g. dlopen, dlclose). It is not possible to link against bundles as if they were shared libraries. However, it is possible that a bundle is linked against real shared libraries; those will be loaded automatically when the bundle is loaded.

Historically, the differences were more significant. In Mac OS X 10.0, there was no way to dynamically load libraries. A set of dyld APIs (e.g. NSCreateObjectFileImageFromFile, NSLinkModule) were introduced with 10.1 to load and unload bundles, but they didn't work for dylibs. A dlopen compatibility library that worked with bundles was added in 10.3; in 10.4, dlopen was rewritten to be a native part of dyld and added support for loading (but not unloading) dylibs. Finally, 10.5 added support for using dlclose with dylibs and deprecated the dyld APIs.

On ELF systems like Linux, both use the same file format; any piece of shared code can be used as a library and for dynamic loading.

Finally, be aware that in Mac OS X, "bundle" can also refer to directories with a standardized structure that holds executable code and the resources used by that code. There is some conceptual overlap (particularly with "loadable bundles" like plugins, which generally contain executable code in the form of a Mach-O bundle), but they shouldn't be confused with Mach-O bundles discussed above.

Additional references:

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

How to animate CSS Translate

$('div').css({"-webkit-transform":"translate(100px,100px)"});?

http://jsfiddle.net/xWCVf/5/

How to find the last day of the month from date?

Here is a complete function:

public function get_number_of_days_in_month($month, $year) {
    // Using first day of the month, it doesn't really matter
    $date = $year."-".$month."-1";
    return date("t", strtotime($date));
}

This would output following:

echo get_number_of_days_in_month(2,2014);

Output: 28

Sending cookies with postman

Chrome apps including Postman are being deprecated as mentioned here. Now the recommendation is to go for native apps which are not detached from the sandboxed environment of the browser.

Quoting from the feature page:

FEATURES EXCLUSIVE TO THE NATIVE APPS:

COOKIES: The native apps let you work with cookies directly. Unlike the Chrome app, no separate extension (Interceptor) is needed.

BUILT-IN PROXY: The native apps come with a built-in proxy that you can use to capture network traffic.

RESTRICTED HEADERS: The latest version of the native apps let you send headers like Origin and User-Agent. These are restricted in the Chrome app. DON'T FOLLOW

REDIRECTS OPTION: This option exists in the native apps to prevent requests that return a 300-series response from being automatically redirected. Previously, users needed to use the Interceptor extension to do this in the Chrome app.

MENU BAR: The native apps are not restricted by the Chrome standards for the menu bar.

POSTMAN CONSOLE: The latest version of the native apps has a built-in console, which allows you to view the network request details for API calls.

So once you install the native Postman app from here you don't have to go looking for additional prerequisites like interceptor app just to check your cookies. I didn't have to change a single setting after installing the native postman app and all my cookies were visible in Cookies tab as shown below:

enter image description here

Graphviz's executables are not found (Python 3.4)

For all those who are facing this issue in windows 10 even after trying the above mentiond steps, this worked for me - For Windows 10 users trying to debug this same error, launch CMD as administrator (important!) and run dot -c and then run dot -v
This fixed the issue for me

How to iterate through a String

Using Guava (r07) you can do this:

for(char c : Lists.charactersOf(someString)) { ... }

This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf returns a view of the string as a List.

Printing PDFs from Windows Command Line

Looks like you are missing the printer name, driver, and port - in that order. Your final command should resemble:

AcroRd32.exe /t <file.pdf> <printer_name> <printer_driver> <printer_port>

For example:

"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe" /t "C:\Folder\File.pdf" "Brother MFC-7820N USB Printer" "Brother MFC-7820N USB Printer" "IP_192.168.10.110"

Note: To find the printer information, right click your printer and choose properties. In my case shown above, the printer name and driver name matched - but your information may differ.

Enum to String C++

You could throw the enum value and string into an STL map. Then you could use it like so.

   return myStringMap[Enum::Apple];