Programs & Examples On #Perl2exe

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

gitx How do I get my 'Detached HEAD' commits back into master

If your detached HEAD is a fast forward of master and you just want the commits upstream, you can

git push origin HEAD:master

to push directly, or

git checkout master && git merge [ref of HEAD]

will merge it back into your local master.

Ajax using https on an http page

Try JSONP.

most JS libraries make it just as easy as other AJAX calls, but internally use an iframe to do the query.

if you're not using JSON for your payload, then you'll have to roll your own mechanism around the iframe.

personally, i'd just redirect form the http:// page to the https:// one

Change DataGrid cell colour based on values

To do this in the Code Behind (VB.NET)

Dim txtCol As New DataGridTextColumn

Dim style As New Style(GetType(TextBlock))
Dim tri As New Trigger With {.Property = TextBlock.TextProperty, .Value = "John"}
tri.Setters.Add(New Setter With {.Property = TextBlock.BackgroundProperty, .Value = Brushes.Green})
style.Triggers.Add(tri)

xtCol.ElementStyle = style

What is the difference between background and background-color

With background you can set all background properties like:

  • background-color
  • background-image
  • background-repeat
  • background-position
    etc.

With background-color you can just specify the color of the background

background: url(example.jpg) no-repeat center center #fff;

VS.

background-image: url(example.jpg);
background-position: center center;
background-repeat: no-repeat;
background-color: #fff;

More info

(See Caption: Background - Shorthand property)

Android Use Done button on Keyboard to click button

Kotlin and Numeric keyboard

If you are using the numeric keyboard you have to dismiss the keyboard, it will be like:

editText.setOnEditorActionListener { v, actionId, event ->
  if (action == EditorInfo.IME_ACTION_DONE || action == EditorInfo.IME_ACTION_NEXT || action == EditorInfo.IME_ACTION_UNSPECIFIED) {
      //hide the keyboard
      val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
      imm.hideSoftInputFromWindow(windowToken, 0)
      //Take action
      editValue.clearFocus()
      return true
  } else {
      return false
  }
}

In laymans terms, what does 'static' mean in Java?

Above points are correct and I want to add some more important points about Static keyword.

Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).

so you will get a doubt that what is the use of this right???

example: static int a=10;(1 program)

just now I told if you use static keyword for variables or for method it will store in permanent memory right.

so I declared same variable with keyword static in other program with different value.

example: static int a=20;(2 program)

the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.

In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.

overall i can say that,if we use static keyword
  1.we can save memory
  2.we can avoid duplicates
  3.No need of creating object in-order to access static variable with the help of class name you can access it.

Secure random token in Node.js

Random URL and filename string safe (1 liner)

Crypto.randomBytes(48).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');

Python: Tuples/dictionaries as keys, select, sort

With keys as tuples, you just filter the keys with given second component and sort it:

blue_fruit = sorted([k for k in data.keys() if k[1] == 'blue'])
for k in blue_fruit:
  print k[0], data[k] # prints 'banana 24', etc

Sorting works because tuples have natural ordering if their components have natural ordering.

With keys as rather full-fledged objects, you just filter by k.color == 'blue'.

You can't really use dicts as keys, but you can create a simplest class like class Foo(object): pass and add any attributes to it on the fly:

k = Foo()
k.color = 'blue'

These instances can serve as dict keys, but beware their mutability!

How to clear form after submit in Angular 2?

Hm, now (23 Jan 2017 with angular 2.4.3) I made it work like this:

newHero() {
    return this.model = new Hero(42, 'APPLIED VALUE', '');
}
<button type="button" class="btn btn-default" (click)="heroForm.resetForm(newHero())">New Hero</button>

What is a handle in C++?

A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.

For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense).

EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.

Convert double to BigDecimal and set BigDecimal Precision

It prints 47.48000 if you use another MathContext:

BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64);

Just pick the context you need.

In Git, how do I figure out what my current revision is?

This gives you just the revision.

git rev-parse HEAD

How to get full REST request body using Jersey?

You could use the @Consumes annotation to get the full body:

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

@Path("doc")
public class BodyResource
{
  @POST
  @Consumes(MediaType.APPLICATION_XML)
  public void post(Document doc) throws TransformerConfigurationException, TransformerException
  {
    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.transform(new DOMSource(doc), new StreamResult(System.out));
  }
}

Note: Don't forget the "Content-Type: application/xml" header by the request.

Real time data graphing on a line chart with html5

You might also give Meteor Charts a try, it's super fast (html5 canvas), has lots of tutorials, and is also well documented. Live updates work really well. You just update the model and run chart.draw() to re-render the scene graph. Here's a demo:

http://meteorcharts.com/demo

CSS: how to get scrollbars for div inside container of fixed height

FWIW, here is my approach = a simple one that works for me:

<div id="outerDivWrapper">
   <div id="outerDiv">
      <div id="scrollableContent">
blah blah blah
      </div>
   </div>
</div>

html, body {
   height: 100%;
   margin: 0em;
}

#outerDivWrapper, #outerDiv {
   height: 100%;
   margin: 0em;
}

#scrollableContent {
   height: 100%;
   margin: 0em;
   overflow-y: auto;
}

Apache HttpClient Android (Gradle)

Working gradle dependency

Try this:

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

How to use executables from a package installed locally in node_modules?

I am a Windows user and this is what worked for me:

// First set some variable - i.e. replace is with "xo"
D:\project\root> set xo="./node_modules/.bin/"

// Next, work with it
D:\project\root> %xo%/bower install

Good Luck.

How to set array length in c# dynamically

Or in C# 3.0 using System.Linq you can skip the intermediate list:

private Update BuildMetaData(MetaData[] nvPairs)
{
        Update update = new Update();
        var ip = from nv in nvPairs
                 select new InputProperty()
                 {
                     Name = "udf:" + nv.Name,
                     Val = nv.Value
                 };
        update.Items = ip.ToArray();
        return update;
}

How to Deserialize JSON data?

Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.

Step 2: Let's say you're using Java. You would use JSONArray like this:

JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
    JSONArray myInteriorArray=myArray.getJSONArray(i);
    if (i==0) {
        //this is the first one and is special because it holds the name of the query.
    }else{
        //do your stuff
        String stateCode=myInteriorArray.getString(0);
        String stateName=myInteriorArray.getString(1);
    }
}

Free space in a CMD shell

Is cscript a 3rd party app? I suggest trying Microsoft Scripting, where you can use a programming language (JScript, VBS) to check on things like List Available Disk Space.

The scripting infrastructure is present on all current Windows versions (including 2008).

How to extract the first two characters of a string in shell scripting?

colrm — remove columns from a file

To leave first two chars, just remove columns starting from 3

cat file | colrm 3

Selectors in Objective-C?

You have to be very careful about the method names. In this case, the method name is just "lowercaseString", not "lowercaseString:" (note the absence of the colon). That's why you're getting NO returned, because NSString objects respond to the lowercaseString message but not the lowercaseString: message.

How do you know when to add a colon? You add a colon to the message name if you would add a colon when calling it, which happens if it takes one argument. If it takes zero arguments (as is the case with lowercaseString), then there is no colon. If it takes more than one argument, you have to add the extra argument names along with their colons, as in compare:options:range:locale:.

You can also look at the documentation and note the presence or absence of a trailing colon.

Python glob multiple filetypes

import glob
import pandas as pd

df1 = pd.DataFrame(columns=['A'])
for i in glob.glob('C:\dir\path\*.txt'):
    df1 = df1.append({'A': i}, ignore_index=True)
for i in glob.glob('C:\dir\path\*.mdown'):
    df1 = df1.append({'A': i}, ignore_index=True)
for i in glob.glob('C:\dir\path\*.markdown):
    df1 = df1.append({'A': i}, ignore_index=True)

EnterKey to press button in VBA Userform

Be sure to avoid "magic numbers" whenever possible, either by defining your own constants, or by using the built-in vbXXX constants.

In this instance we could use vbKeyReturn to indicate the enter key's keycode (replacing YourInputControl and SubToBeCalled).

   Private Sub YourInputControl_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = vbKeyReturn Then
             SubToBeCalled
        End If
   End Sub

This prevents a whole category of compatibility issues and simple typos, especially because VBA capitalizes identifiers for us.

Cheers!

Extract directory path and filename

bash to get file name

fspec="/exp/home1/abc.txt" 
filename="${fspec##*/}"  # get filename
dirname="${fspec%/*}" # get directory/path name

other ways

awk

$ echo $fspec | awk -F"/" '{print $NF}'
abc.txt

sed

$ echo $fspec | sed 's/.*\///'
abc.txt

using IFS

$ IFS="/"
$ set -- $fspec
$ eval echo \${${#@}}
abc.txt

Mapping over values in a python dictionary

Due to PEP-0469 which renamed iteritems() to items() and PEP-3113 which removed Tuple parameter unpacking, in Python 3.x you should write Martijn Pieters? answer like this:

my_dictionary = dict(map(lambda item: (item[0], f(item[1])), my_dictionary.items()))

Select all DIV text with single mouse click

How about this simple solution? :)

<input style="background-color:white; border:1px white solid;" onclick="this.select();" id="selectable" value="http://example.com/page.htm">

Sure it is not div-construction, like you mentioned, but still it is worked for me.

Get encoding of a file in Windows

Looking for a Node.js/npm solution? Try encoding-checker:

npm install -g encoding-checker

Usage

Usage: encoding-checker [-p pattern] [-i encoding] [-v]
 
Options:
  --help                 Show help                                     [boolean]
  --version              Show version number                           [boolean]
  --pattern, -p, -d                                               [default: "*"]
  --ignore-encoding, -i                                            [default: ""]
  --verbose, -v                                                 [default: false]

Examples

Get encoding of all files in current directory:

encoding-checker

Return encoding of all md files in current directory:

encoding-checker -p "*.md"

Get encoding of all files in current directory and its subfolders (will take quite some time for huge folders; seemingly unresponsive):

encoding-checker -p "**"

For more examples refer to the npm docu or the official repository.

removing bold styling from part of a header

Better one: Instead of using extra span tags in html and increasing html code, you can do as below:

<div id="sc-nav-display">
    <table class="sc-nav-table">
      <tr>
        <th class="nav-invent-head">Inventory</th>
        <th class="nav-orders-head">Orders</th>
      </tr>
    </table>
  </div> 

Here, you can use CSS as below:

#sc-nav-display th{
    font-weight: normal;
}

You just need to use ID assigned to the respected div tag of table. I used "#sc-nav-display" with "th" in CSS, so that, every other table headings will remain BOLD until and unless you do the same to all others table head as I said.

Find where python is installed (if it isn't default dir)

If you are using wiindows OS (I am using windows 10 ) just type

where python   

in command prompt ( cmd )

It will show you the directory where you have installed .

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

Anyone who has this error, especially on Azure, try adding "tcp:" to the db-server-name in your connection string in your application. This forces the sql client to communicate with the db using tcp. I'm assuming the connection is UDP by default and there can be intermittent connection issues

How to hide the Google Invisible reCAPTCHA badge

My solution was to hide the badge, then display it when the user focuses on a form input - thus still adhering to Google's T&Cs.

Note: The reCAPTCHA I was tweaking had been generated by a WordPress plugin, so you may need to wrap the reCAPTCHA with a <div class="inv-recaptcha-holder"> ... </div> yourself.

CSS

.inv-recaptcha-holder {
  visibility: hidden;
  opacity: 0;
  transition: linear opacity 1s;
}

.inv-recaptcha-holder.show {
  visibility: visible;
  opacity: 1;
  transition: linear opacity 1s;
}

jQuery

$(document).ready(function () {
  $('form input, form textarea').on( 'focus', function() {
    $('.inv-recaptcha-holder').addClass( 'show' );
  });
});

Obviously you can change the jQuery selector to target specific forms if necessary.

How to use BeanUtils.copyProperties?

There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.

One is

org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)

Another is

org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)

Pay attention to the opposite position of parameters.

Which is faster: multiple single INSERTs or one multiple-row INSERT?

In general the less number of calls to the database the better (meaning faster, more efficient), so try to code the inserts in such a way that it minimizes database accesses. Remember, unless your using a connection pool, each databse access has to create a connection, execute the sql, and then tear down the connection. Quite a bit of overhead!

While loop in batch

It was very useful for me i have used in the following way to add user in active directory:

:: This file is used to automatically add list of user to activedirectory
:: First ask for username,pwd,dc details and run in loop
:: dsadd user cn=jai,cn=users,dc=mandrac,dc=com -pwd `1q`1q`1q`1q

@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 1"
set /p lent="Enter how many Users you want to create : "
set /p Uname="Enter the user name which will be rotated with number ex:ram then ram1 ..etc : "
set /p DcName="Enter the DC name ex:mandrac : "
set /p Paswd="Enter the password you want to give to all the users : "

cls

:while1

if %x% leq %lent% (

    dsadd user cn=%Uname%%x%,cn=users,dc=%DcName%,dc=com -pwd %Paswd%
    echo User %Uname%%x% with DC %DcName% is created
    set /a "x = x + 1"
    goto :while1
)

endlocal

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

Add the @JsonIgnoreProperties("fieldname") annotation to your POJO.

Or you can use @JsonIgnore before the name of the field you want to ignore while deserializing JSON. Example:

@JsonIgnore
@JsonProperty(value = "user_password")
public String getUserPassword() {
    return userPassword;
}

GitHub example

php var_dump() vs print_r()

We can pass multiple parameters with var_dump like:

var_dump("array1",$array1,"array2",$array2);

How to wrap text in textview in Android

By setting android:maxEms to a given value together with android:layout_weight="1" will cause the TextView to wrap once it reaches the given length of the ems.

What is the use of the square brackets [] in sql statements?

Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired....

Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named @String and a column named [String], you can rename the column to [NewString], without renaming @String to @NewString.

Using a string variable as a variable name

You will be much happier using a dictionary instead:

my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"

Android: How to overlay a bitmap and draw over a bitmap?

I can't believe no one has answered this yet! A rare occurrence on SO!

1

The question doesn't quite make sense to me. But I'll give it a stab. If you're asking about direct drawing to a canvas (polygons, shading, text etc...) vs. loading a bitmap and blitting it onto the canvas that would depend on the complexity of your drawing. As the drawing gets more complex the CPU time required will increase accordingly. However, blitting a bitmap onto a canvas will always be a constant time which is proportional to the size of the bitmap.

2

Without knowing what "something" is how can I show you how to do it? You should be able to figure out #2 from the answer for #3.

3

Assumptions:

  • bmp1 is larger than bmp2.
  • You want them both overlaid from the top left corner.

        private Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
            Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
            Canvas canvas = new Canvas(bmOverlay);
            canvas.drawBitmap(bmp1, new Matrix(), null);
            canvas.drawBitmap(bmp2, new Matrix(), null);
            return bmOverlay;
        }
    

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

I think rake must be preinstalled if you want work with bundler. Try to install rake via 'gem install' and then run 'bundle install' again:

gem install rake && bundle install

If you are using rvm ( http://rvm.io ) rake is installed by default...

How to configure XAMPP to send mail from localhost?

You can send mail from localhost with sendmail package , sendmail package is inbuild in XAMPP. So if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

PS: don't forgot to replace my-gmail-id and my-gmail-password in above code. Also, don't forget to remove duplicate keys if you copied settings from above. For example comment following line if there is another sendmail_path : sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe" in the php.ini file

Also remember to restart the server using the XAMMP control panel so the changes take effect.

For gmail please check https://support.google.com/accounts/answer/6010255 to allow access from less secure apps.

To send email on Linux (with sendmail package) through Gmail from localhost please check PHP+Ubuntu Send email using gmail form localhost.

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

tl;dr

The answer is NEVER! (unless you really know what you're doing)

9/10 times the solution can be resolved with a proper understanding of encoding/decoding.

1/10 people have an incorrectly defined locale or environment and need to set:

PYTHONIOENCODING="UTF-8"  

in their environment to fix console printing problems.

What does it do?

sys.setdefaultencoding("utf-8") (struck through to avoid re-use) changes the default encoding/decoding used whenever Python 2.x needs to convert a Unicode() to a str() (and vice-versa) and the encoding is not given. I.e:

str(u"\u20AC")
unicode("€")
"{}".format(u"\u20AC") 

In Python 2.x, the default encoding is set to ASCII and the above examples will fail with:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

(My console is configured as UTF-8, so "€" = '\xe2\x82\xac', hence exception on \xe2)

or

UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)

sys.setdefaultencoding("utf-8") will allow these to work for me, but won't necessarily work for people who don't use UTF-8. The default of ASCII ensures that assumptions of encoding are not baked into code

Console

sys.setdefaultencoding("utf-8") also has a side effect of appearing to fix sys.stdout.encoding, used when printing characters to the console. Python uses the user's locale (Linux/OS X/Un*x) or codepage (Windows) to set this. Occasionally, a user's locale is broken and just requires PYTHONIOENCODING to fix the console encoding.

Example:

$ export LANG=en_GB.gibberish
$ python
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>> print u"\u20AC"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
>>> exit()

$ PYTHONIOENCODING=UTF-8 python
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
>>> print u"\u20AC"
€

What's so bad with sys.setdefaultencoding("utf-8")?

People have been developing against Python 2.x for 16 years on the understanding that the default encoding is ASCII. UnicodeError exception handling methods have been written to handle string to Unicode conversions on strings that are found to contain non-ASCII.

From https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/

def welcome_message(byte_string):
    try:
        return u"%s runs your business" % byte_string
    except UnicodeError:
        return u"%s runs your business" % unicode(byte_string,
            encoding=detect_encoding(byte_string))

print(welcome_message(u"Angstrom (Å®)".encode("latin-1"))

Previous to setting defaultencoding this code would be unable to decode the “Å” in the ascii encoding and then would enter the exception handler to guess the encoding and properly turn it into unicode. Printing: Angstrom (Å®) runs your business. Once you’ve set the defaultencoding to utf-8 the code will find that the byte_string can be interpreted as utf-8 and so it will mangle the data and return this instead: Angstrom (U) runs your business.

Changing what should be a constant will have dramatic effects on modules you depend upon. It's better to just fix the data coming in and out of your code.

Example problem

While the setting of defaultencoding to UTF-8 isn't the root cause in the following example, it shows how problems are masked and how, when the input encoding changes, the code breaks in an unobvious way: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte

What is "entropy and information gain"?

To begin with, it would be best to understand the measure of information.

How do we measure the information?

When something unlikely happens, we say it's a big news. Also, when we say something predictable, it's not really interesting. So to quantify this interesting-ness, the function should satisfy

  • if the probability of the event is 1 (predictable), then the function gives 0
  • if the probability of the event is close to 0, then the function should give high number
  • if probability 0.5 events happens it give one bit of information.

One natural measure that satisfy the constraints is

I(X) = -log_2(p)

where p is the probability of the event X. And the unit is in bit, the same bit computer uses. 0 or 1.

Example 1

Fair coin flip :

How much information can we get from one coin flip?

Answer : -log(p) = -log(1/2) = 1 (bit)

Example 2

If a meteor strikes the Earth tomorrow, p=2^{-22} then we can get 22 bits of information.

If the Sun rises tomorrow, p ~ 1 then it is 0 bit of information.

Entropy

So if we take expectation on the interesting-ness of an event Y, then it is the entropy. i.e. entropy is an expected value of the interesting-ness of an event.

H(Y) = E[ I(Y)]

More formally, the entropy is the expected number of bits of an event.

Example

Y = 1 : an event X occurs with probability p

Y = 0 : an event X does not occur with probability 1-p

H(Y) = E[I(Y)] = p I(Y==1) + (1-p) I(Y==0) 
     = - p log p - (1-p) log (1-p)

Log base 2 for all log.

How do I clone into a non-empty directory?

Warning - this could potentially overwrite files.

git init     
git remote add origin PATH/TO/REPO     
git fetch     
git checkout -t origin/master -f

Modified from @cmcginty's answer - without the -f it didn't work for me

How do I add all new files to SVN

I am a newbie to svn version control. However, for the case when people want to add files without ignoring the already set svn:ignore properties, I solved the issue as below

  1. svn add --depth empty path/to/directory
  2. Execute "svn propset svn:ignore -F ignoreList.txt --recursive" from the location where the ignoreList.txt resides. In my case this file was residing two directories above the "path/to/directory", which I wanted to add. Note that ignoreList.txt contains the file extensions I want svn to ignore, e.g. *.aux etc.
  3. svn add --force path/to/directory/.

The above steps worked.

Testing if a site is vulnerable to Sql Injection

SQL injection is the attempt to issue SQL commands to a database through a website interface, to gain other information. Namely, this information is stored database information such as usernames and passwords.

First rule of securing any script or page that attaches to a database instance is Do not trust user input.

Your example is attempting to end a misquoted string in an SQL statement. To understand this, you first need to understand SQL statements. In your example of adding a ' to a paramater, your 'injection' is hoping for the following type of statement:

SELECT username,password FROM users WHERE username='$username'

By appending a ' to that statement, you could then add additional SQL paramaters or queries.: ' OR username --

SELECT username,password FROM users WHERE username='' OR username -- '$username

That is an injection (one type of; Query Reshaping). The user input becomes an injected statement into the pre-written SQL statement.

Generally there are three types of SQL injection methods:

  • Query Reshaping or redirection (above)
  • Error message based (No such user/password)
  • Blind Injections

Read up on SQL Injection, How to test for vulnerabilities, understanding and overcoming SQL injection, and this question (and related ones) on StackOverflow about avoiding injections.

Edit:

As far as TESTING your site for SQL injection, understand it gets A LOT more complex than just 'append a symbol'. If your site is critical, and you (or your company) can afford it, hire a professional pen tester. Failing that, this great exaxmple/proof can show you some common techniques one might use to perform an injection test. There is also SQLMap which can automate some tests for SQL Injection and database take over scenarios.

Run JavaScript code on window close or page refresh?

jQuery version:

$(window).unload(function(){
    // Do Something
});

Update: jQuery 3:

$(window).on("unload", function(e) {
    // Do Something
});

Thanks Garrett

How to convert an ArrayList containing Integers to primitive int array?

It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.

Just go with Apache Commons

Angular2 module has no exported member

This error can also occur if your interface name is different than the file it is contained in. Read about ES6 modules for details. If the SignInComponent was an interface, as was in my case, then

SignInComponent

should be in a file named SignInComponent.ts.

Sending images using Http Post

Version 4.3.5 Updated Code

  • httpclient-4.3.5.jar
  • httpcore-4.3.2.jar
  • httpmime-4.3.5.jar

Since MultipartEntity has been deprecated. Please see the code below.

String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);

HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);

if (career != null)
    builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
    builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
    builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
    builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
    builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
    builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
    builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());

post.setEntity(builder.build());

try {
    responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
//  System.out.println("Response from Server ==> " + responseBody);

    JSONObject object = new JSONObject(responseBody);
    Boolean success = object.optBoolean("success");
    String message = object.optString("error");

    if (!success) {
        responseBody = message;
    } else {
        responseBody = "success";
    }

} catch (Exception e) {
    e.printStackTrace();
} finally {
    client.getConnectionManager().shutdown();
}

Format cell color based on value in another sheet and cell

I've done this before with conditional formatting. It's a great way to visually inspect the cells in a workbook and spot the outliers in your data.

Is it safe to clean docker/overlay2/

I found this worked best for me:

docker image prune --all

By default Docker will not remove named images, even if they are unused. This command will remove unused images.

Note each layer in an image is a folder inside the /usr/lib/docker/overlay2/ folder.

How do I find which process is leaking memory?

You can run the top command (to run non-interactively, type top -b -n 1). To see applications which are leaking memory, look at the following columns:

  • RPRVT - resident private address space size
  • RSHRD - resident shared address space size
  • RSIZE - resident memory size
  • VPRVT - private address space size
  • VSIZE - total memory size

What is stdClass in PHP?

php.net manual has a few solid explanation and examples contributed by users of what stdClass is, I especially like this one http://php.net/manual/en/language.oop5.basic.php#92123, https://stackoverflow.com/a/1434375/2352773.

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

AttributeError: 'list' object has no attribute 'encode'

You need to do encode on tmp[0], not on tmp.

tmp is not a string. It contains a (Unicode) string.

Try running type(tmp) and print dir(tmp) to see it for yourself.

python - find index position in list based of partial string

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

setting an environment variable in virtualenv

Install autoenv either by

$ pip install autoenv

(or)

$ brew install autoenv

And then create .env file in your virtualenv project folder

$ echo "source bin/activate" > .env

Now everything works fine.

Exiting out of a FOR loop in a batch file?

You could simply use echo on and you will see that goto :eof or even exit /b doesn't work as expected.

The code inside of the loop isn't executed anymore, but the loop is expanded for all numbers to the end.
That's why it's so slow.

The only way to exit a FOR /L loop seems to be the variant of exit like the exsample of Wimmel, but this isn't very fast nor useful to access any results from the loop.

This shows 10 expansions, but none of them will be executed

echo on
for /l %%n in (1,1,10) do (
  goto :eof
  echo %%n
)

What is a wrapper class?

Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their corresponding class instances e.g. a boolean data type can be represented as a Boolean class instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a value to a wrapper class instance cannot be changed further.

How to find all occurrences of a substring?

this is an old thread but i got interested and wanted to share my solution.

def find_all(a_string, sub):
    result = []
    k = 0
    while k < len(a_string):
        k = a_string.find(sub, k)
        if k == -1:
            return result
        else:
            result.append(k)
            k += 1 #change to k += len(sub) to not search overlapping results
    return result

It should return a list of positions where the substring was found. Please comment if you see an error or room for improvment.

How do I check if a file exists in Java?

I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.

The following snippet

if(Files.isRegularFile(Paths.get(pathToFile))) {
    // do something
}

is perfectly satifactory, because method isRegularFile returns false if file does not exist. Therefore, no need to check if Files.exists(...).

Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.

From Java Oracle documentation

bower proxy configuration

I struggled with this from behind a proxy so I thought I should post what I did. Below one is worked for me.

-> "export HTTPS_PROXY=(yourproxy)"

Linker Error C++ "undefined reference "

Your error shows you are not compiling file with the definition of the insert function. Update your command to include the file which contains the definition of that function and it should work.

How do I disable a Pylint warning?

Edit "C:\Users\Your User\AppData\Roaming\Code\User\settings.json" and add 'python.linting.pylintArgs' with its lines at the end as shown below:

{
    "team.showWelcomeMessage": false,
    "python.dataScience.sendSelectionToInteractiveWindow": true,
    "git.enableSmartCommit": true,
    "powershell.codeFormatting.useCorrectCasing": true,
    "files.autoSave": "onWindowChange",
    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django",
        "--errors-only"
    ],
}

C++ "Access violation reading location" Error

Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

Because findVertex can return NULL if it can't find the vertex.

Otherwise this f->adj; is trying to do

NULL->adj;

Which causes access violation.

Resize Google Maps marker icon image

A complete beginner like myself to the topic may find it harder to implement one of these answers than, if within your control, to resize the image yourself with an online editor or a photo editor like Photoshop.

A 500x500 image will appear larger on the map than a 50x50 image.

No programming required.

Calling C/C++ from Python?

I love cppyy, it makes it very easy to extend Python with C++ code, dramatically increasing performance when needed.

It is powerful and frankly very simple to use,

here it is an example of how you can create a numpy array and pass it to a class member function in C++.

cppyy_test.py

import cppyy
import numpy as np
cppyy.include('Buffer.h')


s = cppyy.gbl.Buffer()
numpy_array = np.empty(32000, np.float64)
s.get_numpy_array(numpy_array.data, numpy_array.size)
print(numpy_array[:20])

Buffer.h

struct Buffer {
  void get_numpy_array(double *ad, int size) {
    for( long i=0; i < size; i++)
        ad[i]=i;
  }
};

You can also create a Python module very easily (with CMake), this way you will avoid recompile the C++ code all the times.

In a simple to understand explanation, what is Runnable in Java?

Runnable is an interface defined as so:

interface Runnable {
    public void run();
}

To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {

It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.

If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.

It should also be noted that Threads implement Runnable, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable) without overriding Thread's run method.

Catch multiple exceptions at once?

So you´re repeating lots of code within every exception-switch? Sounds like extracting a method would be god idea, doesn´t it?

So your code comes down to this:

MyClass instance;
try { instance = ... }
catch(Exception1 e) { Reset(instance); }
catch(Exception2 e) { Reset(instance); }
catch(Exception) { throw; }

void Reset(MyClass instance) { /* reset the state of the instance */ }

I wonder why no-one noticed that code-duplication.

From C#6 you furthermore have the exception-filters as already mentioned by others. So you can modify the code above to this:

try { ... }
catch(Exception e) when(e is Exception1 || e is Exception2)
{ 
    Reset(instance); 
}

Want to upgrade project from Angular v5 to Angular v6

Angular 6 has just been released.

https://blog.angular.io/version-6-of-angular-now-available-cc56b0efa7a4

Here is what worked for one of my smaller projects

  1. npm install -g @angular/cli
  2. npm install @angular/cli
  3. ng update @angular/cli --migrate-only --from=1.7.0
  4. ng update @angular/core
  5. npm install rxjs-compat
  6. ng serve

You might need to update your run scripts in package.json For eg. if you use flags like "app" and "environment" These have been updated to "project" and "configuration" respectively.

Refer https://update.angular.io/ for more detailed guide.

Awaiting multiple Tasks with different results

If you're using C# 7, you can use a handy wrapper method like this...

public static class TaskEx
{
    public static async Task<(T1, T2)> WhenAll<T1, T2>(Task<T1> task1, Task<T2> task2)
    {
        return (await task1, await task2);
    }
}

...to enable convenient syntax like this when you want to wait on multiple tasks with different return types. You'd have to make multiple overloads for different numbers of tasks to await, of course.

var (someInt, someString) = await TaskEx.WhenAll(GetIntAsync(), GetStringAsync());

However, see Marc Gravell's answer for some optimizations around ValueTask and already-completed tasks if you intend to turn this example into something real.

How to clone a Date object?

I found out that this simple assignmnent also works:

dateOriginal = new Date();
cloneDate = new Date(dateOriginal);

But I don't know how "safe" it is. Successfully tested in IE7 and Chrome 19.

Cannot find the declaration of element 'beans'

Found it on another thread that solved my problem... was using an internet connection less network.

In that case copy the xsd files from the url and place it next to the beans.xml file and change the xsi:schemaLocation as under:

 <beans xmlns="http://www.springframework.org/schema/beans" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
spring-beans-3.1.xsd">

How to deploy a war file in Tomcat 7

You can access your application from: http://localhost:8080/sample

Deploying or redeploying of war files is automatic by default - after copying/overwriting the file sample.war, check your webapps folder for an extracted folder sample.

If it doesn't open properly, check the log files (e.g. tomcat/logs/catalina.out) for problems with deployment.

Passing parameters on button action:@selector

You can sub-class a UIButton named MyButton, and pass the parameter by MyButton's properties.

Then, get the parameter back from (id)sender.

How do I delete a Git branch locally and remotely?

Use:

git push origin :bugfix  # Deletes remote branch
git branch -d bugfix     # Must delete local branch manually

If you are sure you want to delete it, run

git branch -D bugfix

Now to clean up deleted remote branches run

git remote prune origin

How to make a redirection on page load in JSF 1.x

you should use action instead of actionListener:

<h:commandLink id="close" action="#{bean.close}" value="Close" immediate="true" 
                                   />

and in close method you right something like:

public String close() {
   return "index?faces-redirect=true";
}

where index is one of your pages(index.xhtml)

Of course, all this staff should be written in our original page, not in the intermediate. And inside the close() method you can use the parameters to dynamically choose where to redirect.

how to show calendar on text box click in html

HTML Date Picker You can refer this.

PHPDoc type hinting for array of objects?

<?php foreach($this->models as /** @var Model_Object_WheelModel */ $model): ?>
    <?php
    // Type hinting now works:
    $model->getImage();
    ?>
<?php endforeach; ?>

How to add a search box with icon to the navbar in Bootstrap 3?

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
    <meta charset="utf-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <meta name="description" content="">_x000D_
    <meta name="author" content="">_x000D_
_x000D_
    <title>3 Col Portfolio - Start Bootstrap Template</title>_x000D_
_x000D_
    <!-- Bootstrap Core CSS -->_x000D_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->_x000D_
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
    <!--[if lt IE 9]>_x000D_
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>_x000D_
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>_x000D_
    <![endif]-->_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
    <!-- Navigation -->_x000D_
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
        <div class="container">_x000D_
            <!-- Brand and toggle get grouped for better mobile display -->_x000D_
            <div class="navbar-header">_x000D_
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
                <a class="navbar-brand" href="#">Start Bootstrap</a>_x000D_
            </div>_x000D_
            <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
                <ul class="nav navbar-nav">_x000D_
                    <li>_x000D_
                        <a href="#">About</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">Services</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">Contact</a>_x000D_
                    </li>_x000D_
                </ul>_x000D_
                <form class="navbar-form navbar-right">_x000D_
                    <div class="input-group">_x000D_
                        <input type="text" name="keyword" placeholder="search..." class="form-control">_x000D_
                        <span class="input-group-btn">_x000D_
                            <button class="btn btn-default">Go</button>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </form>_x000D_
            </div>_x000D_
            <!-- /.navbar-collapse -->_x000D_
        </div>_x000D_
        <!-- /.container -->_x000D_
    </nav>_x000D_
_x000D_
    <!-- Page Content -->_x000D_
    <div class="container">_x000D_
_x000D_
        <!-- Page Header -->_x000D_
        <div class="row">_x000D_
            <div class="col-lg-12">_x000D_
                <h1 class="page-header">Page Heading_x000D_
                    <small>Secondary Text</small>_x000D_
                </h1>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <hr>_x000D_
_x000D_
        <!-- Pagination -->_x000D_
        <div class="row text-center">_x000D_
            <div class="col-lg-12">_x000D_
                <ul class="pagination">_x000D_
                    <li>_x000D_
                        <a href="#">&laquo;</a>_x000D_
                    </li>_x000D_
                    <li class="active">_x000D_
                        <a href="#">1</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">2</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">3</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">4</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">5</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">&raquo;</a>_x000D_
                    </li>_x000D_
                </ul>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
    </div>_x000D_
    <!-- Footer -->_x000D_
    <footer>_x000D_
        <div class="container">_x000D_
            <div class="row">_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>About</h3>_x000D_
                    <ul>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-home"></i> Your company address here_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-earphone"></i> 0982.808.065_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-envelope"></i> [email protected]_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-flag"></i> <a href="#">Fan page</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-time"></i> 08:00-18:00 Monday to Friday_x000D_
                        </li>_x000D_
                    </ul>_x000D_
                </div>_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>Support</h3>_x000D_
                    <ul>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Terms of Service</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Privacy policy</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Warranty commitment</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Site map</a>_x000D_
                        </li>_x000D_
                    </ul>_x000D_
                </div>_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>Other</h3>_x000D_
                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod_x000D_
                    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
                    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo_x000D_
                    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse_x000D_
                    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
                    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
    </footer>_x000D_
_x000D_
    <!-- /.container -->_x000D_
_x000D_
    <!-- jQuery -->_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
    <!-- Bootstrap Core JavaScript -->_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Change the "From:" address in Unix "mail"

Plus it's good to use -F option to specify Name of sender.

Something like this:

mail -s "$SUBJECT" $MAILTO -- -F $MAILFROM -f ${MAILFROM}@somedomain.com

Or just look at available options: http://www.courier-mta.org/sendmail.html

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

How can you speed up Eclipse?

On Windows 8. Open Control panel. Find Windows Defender. Go to settings Exclude all folders where is your Spring/Eclipse and workspace

Currency format for display

public static string ToFormattedCurrencyString(
    this decimal currencyAmount,
    string isoCurrencyCode,
    CultureInfo userCulture)
{
    var userCurrencyCode = new RegionInfo(userCulture.Name).ISOCurrencySymbol;

if (userCurrencyCode == isoCurrencyCode)
{
    return currencyAmount.ToString("C", userCulture);
}

return string.Format(
    "{0} {1}", 
    isoCurrencyCode, 
    currencyAmount.ToString("N2", userCulture));

}

I want to exception handle 'list index out of range.'

for i in range (1, len(list))
    try:
        print (list[i])

    except ValueError:
        print("Error Value.")
    except indexError:
        print("Erorr index")
    except :
        print('error ')

Android ADB devices unauthorized

This worked for me:

rm ~/.android/adbkey.pub

sudo ./adb kill-server

sudo ./adb start-server

sudo ./adb -s emulator-5554 install ~/apk_to_install.apk

I'm not sure if is a good idea run adb with sudo privileges,but it was the only way I get it works. Regards.

Getting checkbox values on submit

A good method which is a favorite of mine and for many I'm sure, is to make use of foreach which will output each color you chose, and appear on screen one underneath each other.

When it comes to using checkboxes, you kind of do not have a choice but to use foreach, and that's why you only get one value returned from your array.

Here is an example using $_GET. You can however use $_POST and would need to make both directives match in both files in order to work properly.

###HTML FORM

<form action="third.php" method="get">
    Red<input type="checkbox" name="color[]" value="red">
    Green<input type="checkbox" name="color[]" value="green">
    Blue<input type="checkbox" name="color[]" value="blue">
    Cyan<input type="checkbox" name="color[]" value="cyan">
    Magenta<input type="checkbox" name="color[]" value="Magenta">
    Yellow<input type="checkbox" name="color[]" value="yellow">
    Black<input type="checkbox" name="color[]" value="black">
    <input type="submit" value="submit">
</form>

###PHP (using $_GET) using third.php as your handler

<?php

$name = $_GET['color'];

// optional
// echo "You chose the following color(s): <br>";

foreach ($name as $color){ 
    echo $color."<br />";
}

?>

Assuming having chosen red, green, blue and cyan as colors, will appear like this:

red
green
blue
cyan


##OPTION #2

You can also check if a color was chosen. If none are chosen, then a seperate message will appear.

<?php

$name = $_GET['color'];

if (isset($_GET['color'])) {
    echo "You chose the following color(s): <br>";

    foreach ($name as $color){
        echo $color."<br />";
    }
} else {
    echo "You did not choose a color.";
}

?>

##Additional options: To appear as a list: (<ul></ul> can be replaced by <ol></ol>)

<?php

$name = $_GET['color'];

if (isset($_GET['color'])) {
    echo "You chose the following color(s): <br>";
    echo "<ul>";
    foreach ($name as $color){
        echo "<li>" .$color."</li>";
    }
    echo "</ul>";
} else {
    echo "You did not choose a color.";
}

?>

Format date as dd/MM/yyyy using pipes

Angular: 8.2.11

<td>{{ data.DateofBirth | date }}</td>

Output: Jun 9, 1973

<td>{{ data.DateofBirth | date: 'dd/MM/yyyy' }}</td>

Output: 09/06/1973

<td>{{ data.DateofBirth | date: 'dd/MM/yyyy hh:mm a' }}</td>

Output: 09/06/1973 12:00 AM

Programmatically set image to UIImageView with Xcode 6.1/Swift

In Swift 4, if the image is returned as nil.

Click on image, on the right hand side (Utilities) -> Check Target Membership

How to write data with FileOutputStream without losing old data?

Use the constructor for appending material to the file:

FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

So to append to a file say "abc.txt" use

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);

How do I record audio on iPhone with AVAudioRecorder?

Its really helpful. The only problem i had was the size of sound file created after recording. I needed to reduce the file size so i did some changes in settings.

NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:16000.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];

File size reduced from 360kb to just 25kb (2 seconds recording).

Difference between os.getenv and os.environ.get

In Python 2.7 with iPython:

>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
    """Get an environment variable, return None if it doesn't exist.
    The optional second argument can specify an alternate default."""
    return environ.get(key, default)
File:      ~/venv/lib/python2.7/os.py
Type:      function

So we can conclude os.getenv is just a simple wrapper around os.environ.get.

How to make a local variable (inside a function) global

Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:

def foo():
    global bar
    bar = 32

I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.

How to kill a child process by the parent process?

Send a SIGTERM or a SIGKILL to it:

http://en.wikipedia.org/wiki/SIGKILL

http://en.wikipedia.org/wiki/SIGTERM

SIGTERM is polite and lets the process clean up before it goes, whereas, SIGKILL is for when it won't listen >:)

Example from the shell (man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?kill )

kill -9 pid

In C, you can do the same thing using the kill syscall:

kill(pid, SIGKILL);

See the following man page: http://linux.die.net/man/2/kill

Sublime Text 2: How do I change the color that the row number is highlighted?

On windows 7, find

C:\Users\Simion\AppData\Roaming\Sublime Text 2\Packages\Color Scheme - Default

Find your color scheme file, open it, and find lineHighlight.
Ex:

<key>lineHighlight</key>
<string>#ccc</string>

replace #ccc with your preferred background color.

Setting new value for an attribute using jQuery

It is working you have to check attr after assigning value

LiveDemo

$('#amount').attr( 'datamin','1000');

alert($('#amount').attr( 'datamin'));?

Getting URL parameter in java and extract a specific text from that URL

I wrote this last month for Joomla Module when implementing youtube videos (with the Gdata API). I've since converted it to java.

Import These Libraries

    import java.net.URL;
    import java.util.regex.*;

Copy/Paste this function

    public String getVideoId( String videoId ) throws Exception {
        String pattern = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(videoId);
        int youtu = videoId.indexOf("youtu");
        if(m.matches() && youtu != -1){
            int ytu = videoId.indexOf("http://youtu.be/");
            if(ytu != -1) { 
                String[] split = videoId.split(".be/");
                return split[1];
            }
            URL youtube = new URL(videoId);
            String[] split = youtube.getQuery().split("=");
            int query = split[1].indexOf("&");
            if(query != -1){
                String[] nSplit = split[1].split("&");
                return nSplit[0];
            } else return split[1];
        }
        return null; //throw something or return what you want
    }

URL's it will work with

http://www.youtube.com/watch?v=k0BWlvnBmIE (General URL)
http://youtu.be/k0BWlvnBmIE (Share URL)
http://www.youtube.com/watch?v=UWb5Qc-fBvk&list=FLzH5IF4Lwgv-DM3CupM3Zog&index=2 (Playlist URL)

WMI "installed" query different from add/remove programs list?

All that Add/Remove Programs is really doing is reading this Registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall

Automated way to convert XML files to SQL database?

If there is XML file with 2 different tables then will:

LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1 
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2

work

SQL Server ON DELETE Trigger

Better to use:

DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key

Escape double quotes in a string

In C#, there are at least 4 ways to embed a quote within a string:

  1. Escape quote with a backslash
  2. Precede string with @ and use double quotes
  3. Use the corresponding ASCII character
  4. Use the Hexadecimal Unicode character

Please refer this document for detailed explanation.

Opening a .ipynb.txt File

Below is the easiest way in case if Anaconda is already installed.

1) Under "Files", there is an option called,"Upload".

2) Click on "Upload" button and it asks for the path of the file and select the file and click on upload button present beside the file.

How to print a certain line of a file with PowerShell?

Just for fun, here some test:

#Added this for @Graimer's request ;) (not same computer, but one with HD little more #performant...)

measure-command { Get-Content ita\ita.txt -TotalCount 260000 | Select-Object -Last 1 }

Days              : 0
Hours             : 0

Minutes           : 0
Seconds           : 28
Milliseconds      : 893
Ticks             : 288932649
TotalDays         : 0,000334412788194444
TotalHours        : 0,00802590691666667
TotalMinutes      : 0,481554415
TotalSeconds      : 28,8932649
TotalMilliseconds : 28893,2649


> measure-command { (gc "c:\ps\ita\ita.txt")[260000] }


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 9
Milliseconds      : 257
Ticks             : 92572893
TotalDays         : 0,000107144552083333
TotalHours        : 0,00257146925
TotalMinutes      : 0,154288155
TotalSeconds      : 9,2572893
TotalMilliseconds : 9257,2893


> measure-command { ([System.IO.File]::ReadAllLines("c:\ps\ita\ita.txt"))[260000] }


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 234
Ticks             : 2348059
TotalDays         : 2,71766087962963E-06
TotalHours        : 6,52238611111111E-05
TotalMinutes      : 0,00391343166666667
TotalSeconds      : 0,2348059
TotalMilliseconds : 234,8059



> measure-command {get-content .\ita\ita.txt | select -index 260000}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 36
Milliseconds      : 591
Ticks             : 365912596
TotalDays         : 0,000423509949074074
TotalHours        : 0,0101642387777778
TotalMinutes      : 0,609854326666667
TotalSeconds      : 36,5912596
TotalMilliseconds : 36591,2596

the winner is : ([System.IO.File]::ReadAllLines( path ))[index]

How to disable <br> tags inside <div> by css?

or hide any br that follows the p tag, which are obviously not wanted

p + br {
    display: none;
}

Rails: call another controller action from a controller

You can use url_for to get the URL for a controller and action and then use redirect_to to go to that URL.

redirect_to url_for(:controller => :controller_name, :action => :action_name)

How can I check if string contains characters & whitespace, not just whitespace?

if (!myString.replace(/^\s+|\s+$/g,""))
  alert('string is only whitespace');

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

The following are tried, tested and proven methods to check if a row exists.

(Some of which I use myself, or have used in the past).

Edit: I made an previous error in my syntax where I used mysqli_query() twice. Please consult the revision(s).

I.e.:

if (!mysqli_query($con,$query)) which should have simply read as if (!$query).

  • I apologize for overlooking that mistake.

Side note: Both '".$var."' and '$var' do the same thing. You can use either one, both are valid syntax.

Here are the two edited queries:

$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");

    if (!$query)
    {
        die('Error: ' . mysqli_error($con));
    }

if(mysqli_num_rows($query) > 0){

    echo "email already exists";

}else{

    // do something

}

and in your case:

$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");

    if (!$query)
    {
        die('Error: ' . mysqli_error($dbl));
    }

if(mysqli_num_rows($query) > 0){

    echo "email already exists";

}else{

    // do something

}

You can also use mysqli_ with a prepared statement method:

$query = "SELECT `email` FROM `tblUser` WHERE email=?";

if ($stmt = $dbl->prepare($query)){

        $stmt->bind_param("s", $email);

        if($stmt->execute()){
            $stmt->store_result();

            $email_check= "";         
            $stmt->bind_result($email_check);
            $stmt->fetch();

            if ($stmt->num_rows == 1){

            echo "That Email already exists.";
            exit;

            }
        }
    }

Or a PDO method with a prepared statement:

<?php
$email = $_POST['email'];

$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';

try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
     exit( $e->getMessage() );
}

// assuming a named submit button
if(isset($_POST['submit']))
    {

        try {
            $stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
            $stmt->bindParam(1, $_POST['email']); 
            $stmt->execute();
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            }
        }
        catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }

    if($stmt->rowCount() > 0){
        echo "The record exists!";
    } else {
        echo "The record is non-existant.";
    }


    }
?>
  • Prepared statements are best to be used to help protect against an SQL injection.

N.B.:

When dealing with forms and POST arrays as used/outlined above, make sure that the POST arrays contain values, that a POST method is used for the form and matching named attributes for the inputs.

  • FYI: Forms default to a GET method if not explicity instructed.

Note: <input type = "text" name = "var"> - $_POST['var'] match. $_POST['Var'] no match.

  • POST arrays are case-sensitive.

Consult:

Error checking references:

Please note that MySQL APIs do not intermix, in case you may be visiting this Q&A and you're using mysql_ to connect with (and querying with).

  • You must use the same one from connecting to querying.

Consult the following about this:

If you are using the mysql_ API and have no choice to work with it, then consult the following Q&A on Stack:

The mysql_* functions are deprecated and will be removed from future PHP releases.

  • It's time to step into the 21st century.

You can also add a UNIQUE constraint to (a) row(s).

References:

Creating a dynamic choice field

You can declare the field as a first-class attribute of your form and just set choices dynamically:

class WaypointForm(forms.Form):
    waypoints = forms.ChoiceField(choices=[])

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        waypoint_choices = [(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        self.fields['waypoints'].choices = waypoint_choices

You can also use a ModelChoiceField and set the queryset on init in a similar manner.

Which version of MVC am I using?

Another solution is to search for mvc in nuget (right click on your MVC project in visual studio and select "Manage Nuget Packages").

This will show you the version currently installed -enter image description here

And it'll also allow you to update the MVC version - enter image description here

Importing two classes with same name. How to handle?

You can omit the import statements and refer to them using the entire path. Eg:

java.util.Date javaDate = new java.util.Date()
my.own.Date myDate = new my.own.Date();

But I would say that using two classes with the same name and a similiar function is usually not the best idea unless you can make it really clear which is which.

What is the recommended project structure for spring boot rest projects?

Please use Spring Tool Suite (Eclipse-based development environment that is customized for developing Spring applications).
Create a Spring Starter Project, it will create the directory structure for you with the spring boot maven dependencies.

How to use Class<T> in Java?

Using the generified version of class Class allows you, among other things, to write things like

Class<? extends Collection> someCollectionClass = someMethod();

and then you can be sure that the Class object you receive extends Collection, and an instance of this class will be (at least) a Collection.

Count number of objects in list

length(x)

Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.

lengths(x)

Get the length of each element of a list or atomic vector (is.atomic) as an integer or numeric vector.

make script execution to unlimited

As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush(), but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:

set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

In my case I had created a SB app from the SB Initializer and had included a fair number of deps in it to other things. I went in and commented out the refs to them in the build.gradle file and so was left with:

implementation 'org.springframework.boot:spring-boot-starter-hateoas'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.hsqldb:hsqldb'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'

as deps. Then my bare-bones SB app was able to build and get running successfully. As I go to try to do things that may need those commented-out libs I will add them back and see what breaks.

How do I search within an array of hashes by hash values in ruby?

(Adding to previous answers (hope that helps someone):)

Age is simpler but in case of string and with ignoring case:

  • Just to verify the presence:

@fathers.any? { |father| father[:name].casecmp("john") == 0 } should work for any case in start or anywhere in the string i.e. for "John", "john" or "JoHn" and so on.

  • To find first instance/index:

@fathers.find { |father| father[:name].casecmp("john") == 0 }

  • To select all such indices:

@fathers.select { |father| father[:name].casecmp("john") == 0 }

How can I see the current value of my $PATH variable on OS X?

By entering $PATH on its own at the command prompt, you're trying to run it. This isn't like Windows where you can get your path output by simply typing path.

If you want to see what the path is, simply echo it:

echo $PATH

No resource found that matches the given name '@style/Theme.AppCompat.Light'

What are the steps for that? where is AppCompat located?

Download the support library here:

http://developer.android.com/tools/support-library/setup.html

If you are using Eclipse:

Go to the tabs at the top and select ( Windows -> Android SDK Manager ). Under the 'extras' section, check 'Android Support Library' and check it for installation.

enter image description here

After that, the AppCompat library can be found at:

android-sdk/extras/android/support/v7/appcompat

You need to reference this AppCompat library in your Android project.

Import the library into Eclipse.

  1. Right click on your Android project.
  2. Select properties.
  3. Click 'add...' at the bottom to add a library.
  4. Select the support library
  5. Clean and rebuild your project.

Python unexpected EOF while parsing

What you can try is writing your code as normal for python using the normal input command. However the trick is to add at the beginning of you program the command input=raw_input.

Now all you have to do is disable (or enable) depending on if you're running in Python/IDLE or Terminal. You do this by simply adding '#' when needed.

Switched off for use in Python/IDLE

    #input=raw_input 

And of course switched on for use in terminal.

    input=raw_input 

I'm not sure if it will always work, but its a possible solution for simple programs or scripts.

What does the DOCKER_HOST variable do?

Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:

$(boot2docker shellinit)

I had tested these commands:

>>  docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>>  boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
    export DOCKER_HOST=tcp://192.168.59.103:2376
    export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
    export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory

Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)...

>>  $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>>  docker info
Containers: 3
...

How do I determine the size of my array in C?

For multidimensional arrays it is a tad more complicated. Oftenly people define explicit macro constants, i.e.

#define g_rgDialogRows   2
#define g_rgDialogCols   7

static char const* g_rgDialog[g_rgDialogRows][g_rgDialogCols] =
{
    { " ",  " ",    " ",    " 494", " 210", " Generic Sample Dialog", " " },
    { " 1", " 330", " 174", " 88",  " ",    " OK",        " " },
};

But these constants can be evaluated at compile-time too with sizeof:

#define rows_of_array(name)       \
    (sizeof(name   ) / sizeof(name[0][0]) / columns_of_array(name))
#define columns_of_array(name)    \
    (sizeof(name[0]) / sizeof(name[0][0]))

static char* g_rgDialog[][7] = { /* ... */ };

assert(   rows_of_array(g_rgDialog) == 2);
assert(columns_of_array(g_rgDialog) == 7);

Note that this code works in C and C++. For arrays with more than two dimensions use

sizeof(name[0][0][0])
sizeof(name[0][0][0][0])

etc., ad infinitum.

How to delete all files and folders in a directory?

System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");

foreach (FileInfo file in di.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
    dir.Delete(true); 
}

If your directory may have many files, EnumerateFiles() is more efficient than GetFiles(), because when you use EnumerateFiles() you can start enumerating it before the whole collection is returned, as opposed to GetFiles() where you need to load the entire collection in memory before begin to enumerate it. See this quote here:

Therefore, when you are working with many files and directories, EnumerateFiles() can be more efficient.

The same applies to EnumerateDirectories() and GetDirectories(). So the code would be:

foreach (FileInfo file in di.EnumerateFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
    dir.Delete(true); 
}

For the purpose of this question, there is really no reason to use GetFiles() and GetDirectories().

Linux: command to open URL in default browser

on ubuntu you can try gnome-open.

$ gnome-open http://www.google.com

Load CSV data into MySQL in Python

If it is a pandas data frame you could do:

Sending the data

csv_data.to_sql=(con=mydb, name='<the name of your table>',
  if_exists='replace', flavor='mysql')

to avoid the use of the for.

How do I merge a specific commit from one branch into another in Git?

SOURCE: https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#Integrating-Contributed-Work

The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this:

enter image description here

If you want to pull commit e43a6 into your master branch, you can run

$ git cherry-pick e43a6
Finished one cherry-pick.
[master]: created a0a41a9: "More friendly message when locking the index fails."
 3 files changed, 17 insertions(+), 3 deletions(-)

This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this:

enter image description here

Now you can remove your topic branch and drop the commits you didn’t want to pull in.

Swift: Reload a View Controller

This might be a little late, but did you try calling loadView()?

How to prevent tensorflow from allocating the totality of a GPU memory?

config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)

https://github.com/tensorflow/tensorflow/issues/1578

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

Using REQUIRES_NEW is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED - it will create a new transaction.

That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional, it will create a new transaction.

So, with that in mind, if using REQUIRES_NEW makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.

On rollback - using REQUIRES_NEW will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.

how to check confirm password field in form without reloading page

   <form id="form" name="form" method="post" action="registration.php" onsubmit="return check()"> 
       ....
   </form>

<script>
  $("#form").submit(function(){
     if($("#password").val()!=$("#confirm_password").val())
     {
         alert("password should be same");
         return false;
     }
 })
</script>

hope it may help you

How to use environment variables in docker compose

I have a simple bash script I created for this it just means running it on your file before use: https://github.com/antonosmond/subber

Basically just create your compose file using double curly braces to denote environment variables e.g:

app:
    build: "{{APP_PATH}}"
ports:
    - "{{APP_PORT_MAP}}"

Anything in double curly braces will be replaced with the environment variable of the same name so if I had the following environment variables set:

APP_PATH=~/my_app/build
APP_PORT_MAP=5000:5000

on running subber docker-compose.yml the resulting file would look like:

app:
    build: "~/my_app/build"
ports:
    - "5000:5000"

Install numpy on python3.3 - Install pip for python3

On fedora/rhel/centos you need to

sudo yum install -y python3-devel

before

mkvirtualenv -p /usr/bin/python3.3 test-3.3
pip install numpy

otherwise you'll get

SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel.

Disable cross domain web security in Firefox

Check out my addon that works with the latest Firefox version, with beautiful UI and support JS regex: https://addons.mozilla.org/en-US/firefox/addon/cross-domain-cors

Update: I just add Chrome extension for this https://chrome.google.com/webstore/detail/cross-domain-cors/mjhpgnbimicffchbodmgfnemoghjakai

enter image description here

Finding the second highest number in array

If time complexity is not an issue, then You can run bubble sort and within two iterations, you will get your second highest number because in the first iteration of the loop, the largest number will be moved to the last. In the second iteration, the second largest number will be moved next to last.

Bootstrap 3 Glyphicons are not working

This is due to wrong coding in bootstrap.css and bootstrap.min.css. When you download Bootstrap 3.0 from the Customizer the following code is missing:

@font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

Since this is the main code for using Glyphicons, it won't work ofc...

Download the css-files from the full package and this code will be implemented.

Add a list item through javascript

Try something like this:

var node=document.createElement("LI");
var textnode=document.createTextNode(firstname);
node.appendChild(textnode);
document.getElementById("demo").appendChild(node);

Fiddle: http://jsfiddle.net/FlameTrap/3jDZd/

How to parse a JSON object to a TypeScript Object

First of all you need to be sure that all attributes of that comes from the service are named the same in your class. Then you can parse the object and after that assign it to your new variable, something like this:

const parsedJSON = JSON.parse(serverResponse);
const employeeObj: Employee = parsedJSON as Employee;

Try that!

select certain columns of a data table

DataView dv = new DataView(Your DataTable);

DataTable dt = dv.ToTable(true, "Your Specific Column Name");

The dt contains only selected column values.

How to give a pandas/matplotlib bar graph custom colors

You can specify the color option as a list directly to the plot function.

from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np  # I find np.random.randint to be better

# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)

# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))

# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)

To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.

my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.

The last example yields the follow simple gradient of colors for me:

enter image description here

I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.

In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.

Where does Android app package gets installed on phone

You will find the application folder at:

/data/data/"your package name"

you can access this folder using the DDMS for your Emulator. you can't access this location on a real device unless you have a rooted device.

Add borders to cells in POI generated Excel File

Setting up borders in the style used in the cells will accomplish this. Example:

style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

Show ImageView programmatically

//LinearLayOut Setup
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));

//ImageView Setup
ImageView imageView = new ImageView(this);

//setting image resource
imageView.setImageResource(R.drawable.play);

//setting image position
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
LayoutParams.WRAP_CONTENT));

//adding view to layout
linearLayout.addView(imageView);
//make visible to program
setContentView(linearLayout);

Error - is not marked as serializable

You need to add a Serializable attribute to the class which you want to serialize.

[Serializable]
public class OrgPermission

HttpServletRequest - how to obtain the referring URL?

As all have mentioned it is

request.getHeader("referer");

I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.

More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them.

The Source Origin check recommended here relies on three of these protected headers: Origin, Referer, and Host, making it a pretty strong CSRF defense all on its own.

You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.

Python `if x is not None` or `if not x is None`?

Both Google and Python's style guide is the best practice:

if x is not None:
    # Do something about x

Using not x can cause unwanted results.

See below:

>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0]         # You don't want to fall in this one.
>>> not x
False

You may be interested to see what literals are evaluated to True or False in Python:


Edit for comment below:

I just did some more testing. not x is None doesn't negate x first and then compared to None. In fact, it seems the is operator has a higher precedence when used that way:

>>> x
[0]
>>> not x is None
True
>>> not (x is None)
True
>>> (not x) is None
False

Therefore, not x is None is just, in my honest opinion, best avoided.


More edit:

I just did more testing and can confirm that bukzor's comment is correct. (At least, I wasn't able to prove it otherwise.)

This means if x is not None has the exact result as if not x is None. I stand corrected. Thanks bukzor.

However, my answer still stands: Use the conventional if x is not None. :]

Convert a String In C++ To Upper Case

Short solution using C++11 and toupper().

for (auto & c: str) c = toupper(c);

How to Delete Session Cookie?

Be sure to supply the exact same path as when you set it, i.e.

Setting:

$.cookie('foo','bar', {path: '/'});

Removing:

$.cookie('foo', null, {path: '/'});

Note that

$.cookie('foo', null); 

will NOT work, since it is actually not the same cookie.

Hope that helps. The same goes for the other options in the hash

How to convert OutputStream to InputStream?

As input and output streams are just start and end point, the solution is to temporary store data in byte array. So you must create intermediate ByteArrayOutputStream, from which you create byte[] that is used as input for new ByteArrayInputStream.

public void doTwoThingsWithStream(InputStream inStream, OutputStream outStream){ 
  //create temporary bayte array output stream
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  doFirstThing(inStream, baos);
  //create input stream from baos
  InputStream isFromFirstData = new ByteArrayInputStream(baos.toByteArray()); 
  doSecondThing(isFromFirstData, outStream);
}

Hope it helps.

How to use an array list in Java?

You should read collections framework tutorial first of all.

But to answer your question this is how you should do it:

ArrayList<String> strings = new ArrayList<String>();
strings.add("String1");
strings.add("String2");

// To access a specific element:
System.out.println(strings.get(1));
// To loop through and print all of the elements:
for (String element : strings) {
    System.out.println(element);
}

How to change python version in anaconda spyder

In Preferences, select Python Interpreter

Under Python Interpreter, change from "Default" to "Use the following Python interpreter"

The path there should be the default Python executable. Find your Python 2.7 executable and use that.

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

CROSS JOIN vs INNER JOIN in SQL

It depends on the output you expect.

A cross join matches all rows in one table to all rows in another table. An inner join matches on a field or fields. If you have one table with 10 rows and another with 10 rows then the two joins will behave differently.

The cross join will have 100 rows returned and they won't be related, just what is called a Cartesian product. The inner join will match records to each other. Assuming one has a primary key and that is a foreign key in the other you would get 10 rows returned.

A cross join has limited general utility, but exists for completeness and describes the result of joining tables with no relations added to the query. You might use a cross join to make lists of combinations of words or something similar. An inner join on the other hand is the most common join.

Regex replace (in Python) - a simpler way?

>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a callable, it's passed the match object and must return
    a replacement string to be used.

<select> HTML element with height

You can also "center" the text with:

vertical-align: middle;

input type=file show only button

This HTML code show up only Upload File button

<form action="/action_page.php">
    <input type="button" id="id" value="Upload File"  onclick="document.getElementById('file').click();" />
    <input type="file" style="display:none;" id="file" name="file" onchange="this.form.submit()"/>  
</form>

What is the difference between Html.Hidden and Html.HiddenFor

Html.Hidden and Html.HiddenFor used to generate name-value pairs which waited by action method in controller. Sample Usage(*):

@using (Html.BeginForm("RemoveFromCart", "Cart")) {
                    @Html.Hidden("ProductId", line.Product.ProductID)
                    @Html.HiddenFor(x => x.ReturnUrl)
                    <input class="btn btn-sm btn-warning"
                           type="submit" value="Remove" />
                }

If your action method wait for "ProductId" you have to generate this name in form via using (Html.Hidden or Html.HiddenFor) For the case it is not possible to generate this name with strongly typed model you simple write this name with a string thats "ProductId".

public ViewResult RemoveFromCart(int productId, string returnUrl){...}

If I had written Html.HiddenFor(x => line.Product.ProductID), the helper would render a hidden field with the name "line.Product.ProductID". The name of the field would not match the names of the parameters for the "RemoveFromCart" action method which waiting the name of "ProductId". This would prevent the default model binders from working, so the MVC Framework would not be able to call the method.

*Adam Freeman (Apress - Pro ASP.Net MVC 5)

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

In order of activity, demos/examples available, and simplicity:

Related:

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

Extract subset of key-value pairs from Python dictionary object?

interesting_keys = ('l', 'm', 'n')
subdict = {x: bigdict[x] for x in interesting_keys if x in bigdict}

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

The answer to your question is that you need to have permissions. Type the following code in your manifest.xml file:

<uses-sdk  android:minSdkVersion="8"   android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_OWNER_DATA"></uses-permission>
<uses-permission android:name="android.permission.READ_OWNER_DATA"></uses-permission>`

It worked for me...

Timeout function if it takes too long to finish

The process for timing out an operations is described in the documentation for signal.

The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.

Note that this will only work on UNIX.

Here's an implementation that creates a decorator (save the following code as timeout.py).

from functools import wraps
import errno
import os
import signal

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

This creates a decorator called @timeout that can be applied to any long running functions.

So, in your application code, you can use the decorator like so:

from timeout import timeout

# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
    ...

# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
    ...

# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
    ...

Laravel 4: how to run a raw SQL?

The accepted way to rename a table in Laravel 4 is to use the Schema builder. So you would want to do:

Schema::rename('photos', 'images');

From http://laravel.com/docs/4.2/schema#creating-and-dropping-tables

If you really want to write out a raw SQL query yourself, you can always do:

DB::statement('alter table photos rename to images');

Note: Laravel's DB class also supports running raw SQL select, insert, update, and delete queries, like:

$users = DB::select('select id, name from users');

For more info, see http://laravel.com/docs/4.2/database#running-queries.

vba: get unique values from array

I don't know of any built-in functionality in VBA. The best would be to use a collection using the value as key and only add to it if a value doesn't exist.

Failed to connect to mailserver at "localhost" port 25

PHP mail function can send email in 2 scenarios:

a. Try to send email via unix sendmail program At linux it will exec program "sendmail", put all params to sendmail and that all.

OR

b. Connect to mail server (using smtp protocol and host/port/username/pass from php.ini) and try to send email.

If php unable to connect to email server it will give warning (and you see such workning in your logs) To solve it, install smtp server on your local machine or use any available server. How to setup / configure smtp you can find on php.net

pySerial write() won't take my string

I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.

I'm omitting the com port settings here:

>>>import serial

>>>ser = serial.Serial(5)

>>>ser.close()

>>>ser.open()

>>>ser.write("1".encode())

1

>>>

Clear the entire history stack and start a new activity on Android

For me none of the above methods not work.

Just do this to clear all previous activity:

finishAffinity() // if you are in fragment use activity.finishAffinity()
Intent intent = new Intent(this, DestActivity.class); // with all flags you want
startActivity(intent)

Replace Fragment inside a ViewPager

To replace a fragment inside a ViewPager you can move source codes of ViewPager, PagerAdapter and FragmentStatePagerAdapter classes into your project and add following code.

into ViewPager:

public void notifyItemChanged(Object oldItem, Object newItem) {
    if (mItems != null) {
            for (ItemInfo itemInfo : mItems) {
                        if (itemInfo.object.equals(oldItem)) {
                                itemInfo.object = newItem;
                        }
                    }
       }
       invalidate();
    }

into FragmentStatePagerAdapter:

public void replaceFragmetns(ViewPager container, Fragment oldFragment, Fragment newFragment) {
       startUpdate(container);

       // remove old fragment

       if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
       int position = getFragmentPosition(oldFragment);
        while (mSavedState.size() <= position) {
            mSavedState.add(null);
        }
        mSavedState.set(position, null);
        mFragments.set(position, null);

        mCurTransaction.remove(oldFragment);

        // add new fragment

        while (mFragments.size() <= position) {
            mFragments.add(null);
        }
        mFragments.set(position, newFragment);
        mCurTransaction.add(container.getId(), newFragment);

       finishUpdate(container);

       // ensure getItem returns newFragemtn after calling handleGetItemInbalidated()
       handleGetItemInbalidated(container, oldFragment, newFragment);

       container.notifyItemChanged(oldFragment, newFragment);
    }

protected abstract void handleGetItemInbalidated(View container, Fragment oldFragment, Fragment newFragment);
protected abstract int  getFragmentPosition(Fragment fragment);

handleGetItemInvalidated() ensures that after next call of getItem() it return newFragment getFragmentPosition() returns position of the fragment in your adapter.

Now, to replace fragments call

mAdapter.replaceFragmetns(mViewPager, oldFragment, newFragment);

If you interested in an example project ask me for the sources.

Set Radiobuttonlist Selected from Codebehind

The best option, in my opinion, is to use the Value property for the ListItem, which is available in the RadioButtonList.

I must remark that ListItem does NOT have an ID property.

So, in your case, to select the second element (option2) that would be:

// SelectedValue expects a string
radio1.SelectedValue = "1"; 

Alternatively, yet in very much the same vein you may supply an int to SelectedIndex.

// SelectedIndex expects an int, and are identified in the same order as they are added to the List starting with 0.
radio1.SelectedIndex = 1; 

How do I find the mime-type of a file with php?

If you are sure you're only ever working with images, you can check out the getimagesize() exif_imagetype() PHP function, which attempts to return the image mime-type.

If you don't mind external dependencies, you can also check out the excellent getID3 library which can determine the mime-type of many different file types.

Lastly, you can check out the mime_content_type() function - but it has been deprecated for the Fileinfo PECL extension.

Counting repeated characters in a string in Python

dict = {}
for i in set(str):
    b = str.count(i, 0, len(str))
    dict[i] = b
print dict

If my string is:

str = "this is string!"

Above code will print:

{'!': 1, ' ': 2, 'g': 1, 'i': 3, 'h': 1, 'n': 1, 's': 3, 'r': 1, 't': 2}

Create hive table using "as select" or "like" and also specify delimiter

Both the answers provided above work fine.

  1. CREATE TABLE person AS select * from employee;
  2. CREATE TABLE person LIKE employee;

How to extract the decimal part from a floating point number in C?

Even I was thinking how to do it. But I found a way. Try this code

printf("Enter a floating number");
scanf("%d%c%d", &no, &dot, &dec);
printf("Number=%d Decimal part=%d", no, dec);

Output:-

Enter a floating number
23.13
Number=23 Decimal part=13

TCPDF not render all CSS properties

In the first place, you should note that PDF and HTML and different formats that hardly have anything in common. If TCPDF allows you to provide input data using HTML and CSS it's because it implements a simple parser for these two languages and tries to figure out how to translate that into PDF. So it's logical that TCPDF only supports a little subset of the HTML and CSS specification and, even in supported stuff, it's probably not as perfect as in first class web browsers.

Said that, the question is: what's supported and what's not? The documentation basically skips the issue and let's you enjoy the trial and error method.

Having a look at the source code, we can see there's a protected method called TCPDF::getHtmlDomArray() that, among other things, parses CSS declarations. I can see stuff like font-family, list-style-type or text-indent but there's no margin or padding as far as I can see and, definitively, there's no float at all.

To sum up: with TCPDF, you can use CSS for some basic formatting. If you need to convert from HTML to PDF, it's the wrong tool. (If that's the case, may I suggest wkhtmltopdf?)

Fitting a Normal distribution to 1D data

To see both the normal distribution and your actual data you should plot your data as a histogram, then draw the probability density function over this. See the example on https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.normal.html for exactly how to do this.

How to convert List<string> to List<int>?

Convert string value into integer list

var myString = "010"; 
int myInt;
List<int> B = myString.ToCharArray().Where(x => int.TryParse(x.ToString(), out myInt)).Select(x => int.Parse(x.ToString())).ToList();

Execute php file from another php

exec is shelling to the operating system, and unless the OS has some special way of knowing how to execute a file, then it's going to default to treating it as a shell script or similar. In this case, it has no idea how to run your php file. If this script absolutely has to be executed from a shell, then either execute php passing the filename as a parameter, e.g

exec ('/usr/local/bin/php -f /opt/lampp/htdocs/.../name.php)') ;

or use the punct at the top of your php script

#!/usr/local/bin/php
<?php ... ?>

How to delete stuff printed to console by System.out.println()?

I've found that in Eclipse Mars, if you can safely assume that the line you replace it with will be at least as long as the line you are erasing, simply printing '\r' (a carriage return) will allow your cursor to move back to the beginning of the line to overwrite any characters you see. I suppose if the new line is shorter, you can just make up the different with spaces.

This method is pretty handy in eclipse for live-updating progress percentages, such as in this code snippet I ripped out of one of my programs. It's part of a program to download media files from a website.

    URL url=new URL(link);
    HttpURLConnection connection=(HttpURLConnection)url.openConnection();
    connection.connect();
    if(connection.getResponseCode()!=HttpURLConnection.HTTP_OK)
    {
        throw new RuntimeException("Response "+connection.getResponseCode()+": "+connection.getResponseMessage()+" on url "+link);
    }
    long fileLength=connection.getContentLengthLong();
    File newFile=new File(ROOT_DIR,link.substring(link.lastIndexOf('/')));
    try(InputStream input=connection.getInputStream();
        OutputStream output=new FileOutputStream(newFile);)
    {
        byte[] buffer=new byte[4096];
        int count=input.read(buffer);
        long totalRead=count;
        System.out.println("Writing "+url+" to "+newFile+" ("+fileLength+" bytes)");
        System.out.printf("%.2f%%",((double)totalRead/(double)fileLength)*100.0);
        while(count!=-1)
        {
            output.write(buffer,0,count);
            count=input.read(buffer);
            totalRead+=count;
            System.out.printf("\r%.2f%%",((double)totalRead/(double)fileLength)*100.0);
        }
        System.out.println("\nFinished index "+INDEX);
    }

How do I convert a byte array to Base64 in Java?

In case you happen to be using Spring framework along with java, there is an easy way around.

  1. Import the following.

    import org.springframework.util.Base64Utils;
  2. Convert like this.

    byte[] bytearr ={0,1,2,3,4};
    String encodedText = Base64Utils.encodeToString(bytearr);
    

    To decode you can use the decodeToString method of the Base64Utils class.

Spring Boot War deployed to Tomcat

If your goal is to deploy your Spring Boot application to AWS, Boxfuse gives you a very easy solution.

All you need to do is:

boxfuse run my-spring-boot-app-1.0.jar -env=prod

This will:

  • Fuse a minimal OS image tailor-made for your app (about 100x smaller than a typical Linux distribution)
  • Push it to a secure online repository
  • Convert it into an AMI in about 30 seconds
  • Create and configure a new Elastic IP or ELB
  • Assign a new domain name to it
  • Launch one or more instances based on your new AMI

All images are generated in seconds and are immutable. They can be run unchanged on VirtualBox (dev) and AWS (test & prod).

All updates are performed as zero-downtime blue/green deployments and you can also enable auto-scaling with just one command.

Boxfuse also understands your Spring Boot config will automatically configure security groups and ELB health checks based upon your application.properties.

Here is a tutorial to help you get started: https://boxfuse.com/getstarted/springboot

Disclaimer: I am the founder and CEO of Boxfuse

How do I programmatically click on an element in JavaScript?

The document.createEvent documentation says that "The createEvent method is deprecated. Use event constructors instead."

So you should use this method instead:

var clickEvent = new MouseEvent("click", {
    "view": window,
    "bubbles": true,
    "cancelable": false
});

and fire it on an element like this:

element.dispatchEvent(clickEvent);

as shown here.

How to delete an array element based on key?

this looks like PHP to me. I'll delete if it's some other language.

Simply unset($arr[1]);

How to round up a number in Javascript?

I've been using @AndrewMarshall answer for a long time, but found some edge cases. The following tests doesn't pass:

equals(roundUp(9.69545, 4), 9.6955);
equals(roundUp(37.760000000000005, 4), 37.76);
equals(roundUp(5.83333333, 4), 5.8333);

Here is what I now use to have round up behave correctly:

// Closure
(function() {
  /**
   * Decimal adjustment of a number.
   *
   * @param {String}  type  The type of adjustment.
   * @param {Number}  value The number.
   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
   * @returns {Number} The adjusted value.
   */
  function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // If the value is negative...
    if (value < 0) {
      return -decimalAdjust(type, -value, exp);
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }

  // Decimal round
  if (!Math.round10) {
    Math.round10 = function(value, exp) {
      return decimalAdjust('round', value, exp);
    };
  }
  // Decimal floor
  if (!Math.floor10) {
    Math.floor10 = function(value, exp) {
      return decimalAdjust('floor', value, exp);
    };
  }
  // Decimal ceil
  if (!Math.ceil10) {
    Math.ceil10 = function(value, exp) {
      return decimalAdjust('ceil', value, exp);
    };
  }
})();

// Round
Math.round10(55.55, -1);   // 55.6
Math.round10(55.549, -1);  // 55.5
Math.round10(55, 1);       // 60
Math.round10(54.9, 1);     // 50
Math.round10(-55.55, -1);  // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1);      // -50
Math.round10(-55.1, 1);    // -60
Math.round10(1.005, -2);   // 1.01 -- compare this with Math.round(1.005*100)/100 above
Math.round10(-1.005, -2);  // -1.01
// Floor
Math.floor10(55.59, -1);   // 55.5
Math.floor10(59, 1);       // 50
Math.floor10(-55.51, -1);  // -55.6
Math.floor10(-51, 1);      // -60
// Ceil
Math.ceil10(55.51, -1);    // 55.6
Math.ceil10(51, 1);        // 60
Math.ceil10(-55.59, -1);   // -55.5
Math.ceil10(-59, 1);       // -50

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

Can't bind to 'dataSource' since it isn't a known property of 'table'

Remember to add MatTableModule in your app.module's imports i.e.

In Angular 9+

import { MatTableModule } from '@angular/material/table'  

@NgModule({
  imports: [
    // ...
    MatTableModule
    // ...
  ]
})

Less than Angular 9

import { MatTableModule } from '@angular/material'  

@NgModule({
  imports: [
    // ...
    MatTableModule
    // ...
  ]
})

How to link to apps on the app store

I can confirm that if you create an app in iTunes connect you get your app id before you submit it.

Therefore..

itms-apps://itunes.apple.com/app/id123456789

NSURL *appStoreURL = [NSURL URLWithString:@"itms-apps://itunes.apple.com/app/id123456789"];
    if ([[UIApplication sharedApplication]canOpenURL:appStoreURL])
        [[UIApplication sharedApplication]openURL:appStoreURL];

Works a treat

Can't resolve module (not found) in React.js

Deleted the package-lock.json file & then ran

npm install

Read further

Laravel form html with PUT method for PUT routes

in your view blade change to

{{ Form::open(['action' => 'postcontroller@edit', 'method' => 'PUT', 'class' = 'your class here']) }}

<div>
{{ Form::textarea('textareanamehere', 'default value here', ['placeholder' => 'your place holder here', 'class' => 'your class here']) }}
</div>

<div>
{{ Form::submit('Update', ['class' => 'btn class here'])}}
</div>

{{ Form::close() }}

actually you can use raw form like your question. but i dont recomended it. dan itulah salah satu alasan agan belajar framework, simple, dan cepat. so kenapa pake raw form kalo ada yang lebih mudah. hehe. proud to be indonesian.

reference: Laravel Blade Form

How do I check form validity with angularjs?

You can also use myform.$invalid

E.g.

if($scope.myform.$invalid){return;}

How can I truncate a string to the first 20 words in PHP?

This looks pretty good to me:

A common problem when creating dynamic web pages (where content is sourced from a database, content management system or external source such as an RSS feed) is that the input text can be too long and cause the page layout to 'break'.

One solution is to truncate the text so that it fits on the page. This sounds simple, but often the results aren't as expected due to words and sentences being cut off at inappropriate points.

start MySQL server from command line on Mac OS Lion

Try /usr/local/mysql/bin/mysqld_safe

Example:

shell> sudo /usr/local/mysql/bin/mysqld_safe
(Enter your password, if necessary)
(Press Control-Z)
shell> bg
(Press Control-D or enter "exit" to exit the shell)

You can also add these to your bash startup scripts:

export MYSQL_HOME=/usr/local/mysql
alias start_mysql='sudo $MYSQL_HOME/bin/mysqld_safe &'
alias stop_mysql='sudo $MYSQL_HOME/bin/mysqladmin shutdown'

Chart.js v2 - hiding grid lines

options: {
    scales: {
        xAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }],
        yAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }]
    }
}

Website screenshots

There are many open source projects that can generate screenshots. For example PhantomJS, webkit2png etc

The big problem with these projects is that they are based on older browser technology and have problems rendering many sites, especially sites that use webfonts, flexbox, svg and various other additions to the HTML5 and CSS spec over the last couple of months/years.

I've tried a few of the third party services, and most are based on PhantomJS, meaning they also produce poor quality screenshots. The best third party service for generating website screenshots is urlbox.io. It is a paid service, although there is a free 7-day trial to test it out without committing to any paid plan.

Here is a link to the documentation, and below are simple steps to get it working in PHP with composer.

// 1 . Get the urlbox/screenshots composer package (on command line):
composer require urlbox/screenshots

// 2. Set up the composer package with Urlbox API credentials:
$urlbox = UrlboxRenderer::fromCredentials('API_KEY', 'API_SECRET');

// 3. Set your options (all options such as full page/full height screenshots, retina resolution, viewport dimensions, thumbnail width etc can be set here. See the docs for more.)
$options['url'] = 'example.com';

// 4. Generate the Urlbox url
$urlboxUrl = $urlbox->generateUrl($options);
// $urlboxUrl is now 'https://api.urlbox.io/v1/API_KEY/TOKEN/png?url=example.com'

// 5. Now stick it in an img tag, when the image is loaded in browser, the API call to urlbox will be triggered and a nice PNG screenshot will be generated!
<img src="$urlboxUrl" />

For e.g. here's a full height screenshot of this very page:

https://api.urlbox.io/v1/ca482d7e-9417-4569-90fe-80f7c5e1c781/8f1666d1f4195b1cb84ffa5f992ee18992a2b35e/png?url=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F757675%2Fwebsite-screenshots-using-php%2F43652083%2343652083&full_page=true

full page screenshot of stackoverflow.com question powered by urlbox.io

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

I am assuming what you are trying to achieve is to insert a line after the first few lines of of a textfile.

head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt

If you don't want to rest of the lines from the file, just skip the tail part.