Programs & Examples On #Invalid postback

Comparing strings, c++

.compare() returns an integer, which is a measure of the difference between the two strings.

  • A return value of 0 indicates that the two strings compare as equal.
  • A positive value means that the compared string is longer, or the first non-matching character is greater.
  • A negative value means that the compared string is shorter, or the first non-matching character is lower.

operator== simply returns a boolean, indicating whether the strings are equal or not.

If you don't need the extra detail, you may as well just use ==.

Twitter Bootstrap - how to center elements horizontally or vertically

for bootstrap4 vertical center of few items

d-flex for flex rules

flex-column for vertical direction on items

justify-content-center for centering

style='height: 300px;' must have for set points where center be calc or use h-100 class

<div class="d-flex flex-column justify-content-center bg-secondary" style="
    height: 300px;
">
    <div class="p-2 bg-primary">Flex item</div>
    <div class="p-2 bg-primary">Flex item</div>
    <div class="p-2 bg-primary">Flex item</div>
  </div> 

How to submit an HTML form on loading the page?

You can do it by using simple one line JavaScript code and also be careful that if JavaScript is turned off it will not work. The below code will do it's job if JavaScript is turned off.

Turn off JavaScript and run the code on you own file to know it's full function.(If you turn off JavaScript here, the below Code Snippet will not work)

_x000D_
_x000D_
.noscript-error {_x000D_
  color: red;_x000D_
}
_x000D_
<body onload="document.getElementById('payment-form').submit();">_x000D_
_x000D_
  <div align="center">_x000D_
    <h1>_x000D_
      Please Waite... You Will be Redirected Shortly<br/>_x000D_
      Don't Refresh or Press Back _x000D_
    </h1>_x000D_
  </div>_x000D_
_x000D_
  <form method='post' action='acction.php' id='payment-form'>_x000D_
    <input type='hidden' name='field-name' value='field-value'>_x000D_
     <input type='hidden' name='field-name2' value='field-value2'>_x000D_
    <noscript>_x000D_
      <div align="center" class="noscript-error">Sorry, your browser does not support JavaScript!._x000D_
        <br>Kindly submit it manually_x000D_
        <input type='submit' value='Submit Now' />_x000D_
      </div>_x000D_
    </noscript>_x000D_
  </form>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

Goal Seek Macro with Goal as a Formula

I think your issue is that Range("H18") doesn't contain a formula. Also, you could make your code more efficient by eliminating x. Instead, change your code to

Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

How to delete a record in Django models?

if you want to delete one instance then write the code

entry= Account.objects.get(id= 5)
entry.delete()

if you want to delete all instance then write the code

entries= Account.objects.all()
entries.delete()

Bootstrap 3 - set height of modal window according to screen size

Pure CSS solution, using calc

.modal-body {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}

200px may be adjusted in accordance to height of header & footer

Git - What is the difference between push.default "matching" and "simple"

git push can push all branches or a single one dependent on this configuration:

Push all branches

git config --global push.default matching

It will push all the branches to the remote branch and would merge them. If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default.

Push only the current branch if its named upstream is identical

git config --global push.default simple

So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

WPF Datagrid Get Selected Cell Value

I was in such situation .. and found This:

int ColumnIndex = DataGrid.CurrentColumn.DisplayIndex;
TextBlock CellContent = DataGrid.SelectedCells[ColumnIndex].Column.GetCellContent(DataGrid.SelectedItem);

And make sure to treat custom columns' templates

In excel how do I reference the current row but a specific column?

To static either a row or a column, put a $ sign in front of it. So if you were to use the formula =AVERAGE($A1,$C1) and drag it down the entire sheet, A and C would remain static while the 1 would change to the current row

If you're on Windows, you can achieve the same thing by repeatedly pressing F4 while in the formula editing bar. The first F4 press will static both (it will turn A1 into $A$1), then just the row (A$1) then just the column ($A1)

Although technically with the formulas that you have, dragging down for the entirety of the column shouldn't be a problem without putting a $ sign in front of the column. Setting the column as static would only come into play if you're dragging ACROSS columns and want to keep using the same column, and setting the row as static would be for dragging down rows but wanting to use the same row.

How to search a Git repository by commit message?

Though a bit late, there is :/ which is the dedicated notation to specify a commit (or revision) based on the commit message, just prefix the search string with :/, e.g.:

git show :/keyword(s)

Here <keywords> can be a single word, or a complex regex pattern consisting of whitespaces, so please make sure to quote/escape when necessary, e.g.:

git log -1 -p ":/a few words"

Alternatively, a start point can be specified, to find the closest commit reachable from a specific point, e.g.:

git show 'HEAD^{/fix nasty bug}'

See: git revisions manual.

MVC [HttpPost/HttpGet] for Action

In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution

[AcceptVerbs(WebRequestMethods.Http.Get, WebRequestMethods.Http.Post)]
public IHttpActionResult Login()
{
   // Login logic
}

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

How to get selenium to wait for ajax response?

The code (C#) bellow ensures that the target element is displayed:

        internal static bool ElementIsDisplayed()
        {
          IWebDriver driver = new ChromeDriver();
          driver.Url = "http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp";
          WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
          By locator = By.CssSelector("input[value='csharp']:first-child");
          IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
          {
            return d.FindElement(locator);
          });
          return myDynamicElement.Displayed;
        }

If the page supports jQuery it can be used the jQuery.active function to ensure that the target element is retrieved after all the ajax calls are finished:

 public static bool ElementIsDisplayed()
    {
        IWebDriver driver = new ChromeDriver();
        driver.Url = "http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp";
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
        By locator = By.CssSelector("input[value='csharp']:first-child");
        return wait.Until(d => ElementIsDisplayed(d, locator));
    }

    public static bool ElementIsDisplayed(IWebDriver driver, By by)
    {
        try
        {
            if (driver.FindElement(by).Displayed)
            {
                //jQuery is supported.
                if ((bool)((IJavaScriptExecutor)driver).ExecuteScript("return window.$ != undefined"))
                {
                    return (bool)((IJavaScriptExecutor)driver).ExecuteScript("return $.active == 0");
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

Callback after all asynchronous forEach callbacks are completed

How about setInterval, to check for complete iteration count, brings guarantee. not sure if it won't overload the scope though but I use it and seems to be the one

_.forEach(actual_JSON, function (key, value) {

     // run any action and push with each iteration 

     array.push(response.id)

});


setInterval(function(){

    if(array.length > 300) {

        callback()

    }

}, 100);

Tooltips with Twitter Bootstrap

Add this into your header

<script>
    //tooltip
    $(function() {
        var tooltips = $( "[title]" ).tooltip();
        $(document)(function() {
            tooltips.tooltip( "open" );
        });
    });
</script>

Then just add the attribute title="your tooltip" to any element

Running ASP.Net on a Linux based server

The Mono project is your best option. However, it has a lot of pitfalls (like incomplete API support in some areas), and it's legally gray (people like Richard Stallman have derided the use of Mono because of the possibility of Microsoft coming down on Mono by using its patent rights, but that's another story).

Anyway, Apache supports .NET/Mono through a module, but the last time I checked the version supplied with Debian, it gave Perl language support only; I can't say if it's changed since, perhaps someone else can correct me there.

How to use QTimer

Other way is using of built-in method start timer & event TimerEvent.

Header:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    int timerId;

protected:
    void timerEvent(QTimerEvent *event);
};

#endif // MAINWINDOW_H

Source:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    timerId = startTimer(1000);
}

MainWindow::~MainWindow()
{
    killTimer(timerId);
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    qDebug() << "Update...";
}

Erasing elements from a vector

To erase 1st element you can use:

vector<int> mV{ 1, 2, 3, 4, 5 }; 
vector<int>::iterator it; 

it = mV.begin(); 
mV.erase(it); 

Adding author name in Eclipse automatically to existing files

Actually in Eclipse Indigo thru Oxygen, you have to go to the Types template Window -> Preferences -> Java -> Code Style -> Code templates -> (in right-hand pane) Comments -> double-click Types and make sure it has the following, which it should have by default:

/**
 * @author ${user}
 *
 * ${tags}
 */

and as far as I can tell, there is nothing in Eclipse to add the javadoc automatically to existing files in one batch. You could easily do it from the command line with sed & awk but that's another question.

If you are prepared to open each file individually, then selected the class / interface declaration line, e.g. public class AdamsClass { and then hit the key combo Shift + Alt + J and that will insert a new javadoc comment above, along with the author tag for your user. To experiment with other settings, go to Windows->Preferences->Java->Editor->Templates.

Cannot redeclare function php

Remove the function and check the output of:

var_dump(function_exists('parseDate'));

In which case, change the name of the function.

If you get false, you're including the file with that function twice, replace :

include

by

include_once

And replace :

require

by

require_once

EDIT : I'm just a little too late, post before beat me to it !

What does '?' do in C++?

It's the conditional operator.

a ? b : c

It's a shortcut for IF/THEN/ELSE.

means: if a is true, return b, else return c. In this case, if f==r, return 1, else return 0.

Impersonate tag in Web.Config

Put the identity element before the authentication element

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

See the "Threading" section of this page: http://msdn.microsoft.com/en-us/library/ff647786.aspx, in conjunction with the "Connections" section.

Have you tried upping the maxconnection attribute of your processModel setting?

How to get the return value from a thread in python?

Using Queue :

import threading, queue

def calc_square(num, out_queue1):
  l = []
  for x in num:
    l.append(x*x)
  out_queue1.put(l)


arr = [1,2,3,4,5,6,7,8,9,10]
out_queue1=queue.Queue()
t1=threading.Thread(target=calc_square, args=(arr,out_queue1))
t1.start()
t1.join()
print (out_queue1.get())

What is the difference between "mvn deploy" to a local repo and "mvn install"?

From the Maven docs, sounds like it's just a difference in which repository you install the package into:

  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

Maybe there is some confusion in that "install" to the CI server installs it to it's local repository, which then you as a user are sharing?

Travel/Hotel API's?

Check out api.hotelsbase.org - its a free xml hotel api No images as of yet though

Building a complete online payment gateway like Paypal

What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.

You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.

Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).

Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org

Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.

In summary then: it all depends on your region.

  • Contact a major bank and try to get through to their card acquiring arm.
  • Explain that you're setting up as a payment service provider, and request details on comms format for authorization requests and end of day settlement files
  • Set up a test merchant account and develop auth/settlement software and go through the accreditation process. Most acquirers help you through this process for free, but when you want to register as an accredited PSP some will request a fee.
  • you will need to comply with some regulations too, for example you may need to register as a payment institution

Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.

Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.

What are the advantages and disadvantages of recursion?

Expressiveness

Most problems are naturally expressed by recursion such as Fibonacci, Merge sorting and quick sorting. In this respect, the code is written for humans, not machines.

Immutability

Iterative solutions often rely on varying temporary variables which makes the code hard to read. This can be avoided with recursion.

Performance

Recursion is not stack friendly. Stack can overflow when the recursion is not well designed or tail optimization is not supported.

LINQ Join with Multiple Conditions in On Clause

Here you go with:

from b in _dbContext.Burden 
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }

How to store a list in a column of a database table

you can store it as text that looks like a list and create a function that can return its data as an actual list. example:

database:

 _____________________
|  word  | letters    |
|   me   | '[m, e]'   |
|  you   |'[y, o, u]' |  note that the letters column is of type 'TEXT'
|  for   |'[f, o, r]' |
|___in___|_'[i, n]'___|

And the list compiler function (written in python, but it should be easily translatable to most other programming languages). TEXT represents the text loaded from the sql table. returns list of strings from string containing list. if you want it to return ints instead of strings, make mode equal to 'int'. Likewise with 'string', 'bool', or 'float'.

def string_to_list(string, mode):
    items = []
    item = ""
    itemExpected = True
    for char in string[1:]:
        if itemExpected and char not in [']', ',', '[']:
            item += char
        elif char in [',', '[', ']']:
            itemExpected = True
            items.append(item)
            item = ""
    newItems = []
    if mode == "int":
        for i in items:
            newItems.append(int(i))

    elif mode == "float":
        for i in items:
            newItems.append(float(i))

    elif mode == "boolean":
        for i in items:
            if i in ["true", "True"]:
                newItems.append(True)
            elif i in ["false", "False"]:
                newItems.append(False)
            else:
                newItems.append(None)
    elif mode == "string":
        return items
    else:
        raise Exception("the 'mode'/second parameter of string_to_list() must be one of: 'int', 'string', 'bool', or 'float'")
    return newItems

Also here is a list-to-string function in case you need it.

def list_to_string(lst):
    string = "["
    for i in lst:
        string += str(i) + ","
    if string[-1] == ',':
        string = string[:-1] + "]"
    else:
        string += "]"
    return string

How to hide TabPage from TabControl

Variant 1

In order to avoid visual klikering you might need to use:

bindingSource.RaiseListChangeEvent = false 

or

myTabControl.RaiseSelectedIndexChanged = false

Remove a tab page:

myTabControl.Remove(myTabPage);

Add a tab page:

myTabControl.Add(myTabPage);

Insert a tab page at specific location:

myTabControl.Insert(2, myTabPage);

Do not forget to revers the changes:

bindingSource.RaiseListChangeEvent = true;

or

myTabControl.RaiseSelectedIndexChanged = true;

Variant 2

myTabPage.parent = null;
myTabPage.parent = myTabControl;

PHP: if !empty & empty

Here's a compact way to do something different in all four cases:

if(empty($youtube)) {
    if(empty($link)) {
        # both empty
    } else {
        # only $youtube not empty
    }
} else {
    if(empty($link)) {
        # only $link empty
    } else {
        # both not empty
    }
}

If you want to use an expression instead, you can use ?: instead:

echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                     : ( empty($link) ? 'only $link empty' : 'both not empty' );

jquery - Click event not working for dynamically created button

You create buttons dynamically because of that you need to call them with .live() method if you use jquery 1.7

but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:

$(document).on('click', 'selector', function(){ 
     // Your Code
});

For Example

If your html is something like this

<div id="btn-list">
    <div class="btn12">MyButton</div>
</div>

You can write your jquery like this

$(document).on('click', '#btn-list .btn12', function(){ 
     // Your Code
});

Adding IN clause List to a JPA Query

public List<DealInfo> getDealInfos(List<String> dealIds) {
        String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
        TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
        query.setParameter("inclList", dealIds);
        return query.getResultList();
    }

Works for me with JPA 2, Jboss 7.0.2

Is there a Wikipedia API?

Wikipedia is built on MediaWiki, and here's the MediaWiki API.

How to use SortedMap interface in Java?

A TreeMap is probably the most straightforward way of doing this. You use it exactly like a normal Map. i.e.

Map<Float,String> mySortedMap = new TreeMap<Float,MyObject>();
// Put some values in it
mySortedMap.put(1.0f,"One");
mySortedMap.put(0.0f,"Zero");
mySortedMap.put(3.0f,"Three");

// Iterate through it and it'll be in order!
for(Map.Entry<Float,String> entry : mySortedMap.entrySet()) {
    System.out.println(entry.getValue());
} // outputs Zero One Three 

It's worth taking a look at the API docs, http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html to see what else you can do with it.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Haskell

foldl (+) 0 [1,2,3,4,5]

Python

reduce(lambda a,b: a+b, [1,2,3,4,5], 0)

Obviously, that is a trivial example to illustrate a point. In Python you would just do sum([1,2,3,4,5]) and even Haskell purists would generally prefer sum [1,2,3,4,5].

For non-trivial scenarios when there is no obvious convenience function, the idiomatic pythonic approach is to explicitly write out the for loop and use mutable variable assignment instead of using reduce or a fold.

That is not at all the functional style, but that is the "pythonic" way. Python is not designed for functional purists. See how Python favors exceptions for flow control to see how non-functional idiomatic python is.

How can I convert ArrayList<Object> to ArrayList<String>?

Using Java 8 you can do:

List<Object> list = ...;
List<String> strList = list.stream()
                           .map( Object::toString )
                           .collect( Collectors.toList() );

ng-change not working on a text input

First at all i'm seing your code and you haven't any controller. So i suggest that you use a controller. I think you have to use a controller because your variable {{myStyle}} isn't compile because the 2 curly brace are visible and they shouldn't.

Second you have to use ng-model for your input, this directive will bind the value of the input to your variable.

What's the best UML diagramming tool?

If you want to model at diagram level and also have a clean metamodel the new Omondo build allows live synchronization between MOF and UML Diagrams. Just amazing to see my diagram and the xmi live synchronized each time I change something in my diagram and the model is changed. What is most incredible is that the model is also the metamodel and the MOF because everything is lived synchronized. Very powerful new concept for my point of view.

I also like Java code annotation and JPA support in the class diagram and in the model. I don't know any other tool having these 2 incredible features !!

What are valid values for the id attribute in HTML?

From the HTML 4 spec...

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

EDIT: d'oh! Beaten to the button, again!

How do I parse JSON into an int?

At first, you create a BufferedReader on a FileReader to the file.

Then, you create a new `JSONParser()´ object that parses the content read from the file.

You cast the parsed Object to a JSONObject and get the id field.

FileReader file=new FileReader("1.json");
BufferedReader write=new BufferedReader(file);
Object obj=new JSONParser().parse(write);
JSONObject jo = (JSONObject) obj;
long id=(long)jo.get("id");

Reading and writing to serial port in C on Linux

1) I'd add a /n after init. i.e. write( USB, "init\n", 5);

2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.

3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?

Edited to Add:

Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.

int tmp, serialLines;

cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);

cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;

time data does not match format

You have the month and day swapped:

'%m/%d/%Y %H:%M:%S.%f'

28 will never fit in the range for the %m month parameter otherwise.

With %m and %d in the correct order parsing works:

>>> from datetime import datetime
>>> datetime.strptime('07/28/2014 18:54:55.099000', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

You don't need to add '000'; %f can parse shorter numbers correctly:

>>> datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

How to use refs in React with Typescript

If you wont to forward your ref, in Props interface you need to use RefObject<CmpType> type from import React, { RefObject } from 'react';

Still Reachable Leak detected by Valgrind

For future readers, "Still Reachable" might mean you forgot to close something like a file. While it doesn't seem that way in the original question, you should always make sure you've done that.

Why does Maven have such a bad rep?

I looked into maven about six months ago. We were starting a new project, and didn't have any legacy to support. That said:

  • Maven is all-or-nothing. Or at least as far as I could tell from the documentation. You can't easily use maven as a drop-in replacement for ant, and gradually adopt more advanced features.
  • According to the documentation, Maven is transcendental happiness that makes all your wildest dreams come true. You just have to meditate on the manual for 10 years before you become enlightened.
  • Maven makes your build process dependent on your network connection.
  • Maven has useless error messages. Compare ant's "Target x does not exist in the project y" to mvn's "Invalid task 'run': you must specify a valid lifecycle phase, or a goal in the format plugin:goal or pluginGroupId:pluginArtifactId:pluginVersion:goal" Helpfully, it suggests I run mvn with -e for more information, which means that it will print the same message, then a stack trace for a BuildFailureException.

A large part of my dislike for maven can be explained by the following excerpt from Better Builds with Maven:

When someone wants to know what Maven is, they will usually ask “What exactly is Maven?”, and they expect a short, sound-bite answer. “Well it is a build tool or a scripting framework” Maven is more than three boring, uninspiring words. It is a combination of ideas, standards, and software, and it is impossible to distill the definition of Maven to simply digested sound-bites. Revolutionary ideas are often difficult to convey with words.

My suggestion: if you can't convey the ideas with words, you should not attempt to write a book on the subject, because I'm not going to telepathically absorb the ideas.

Efficiently replace all accented characters in a string?

I think this might work a little cleaner/better (though I haven't test it's performance):

String.prototype.stripAccents = function() {
    var translate_re = /[àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ]/g;
    var translate = 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY';
    return (this.replace(translate_re, function(match){
        return translate.substr(translate_re.source.indexOf(match)-1, 1); })
    );
};

Or if you are still too worried about performance, let's get the best of both worlds:

String.prototype.stripAccents = function() {
    var in_chrs =  'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ',
        out_chrs = 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY', 
        transl = {};
    eval('var chars_rgx = /['+in_chrs+']/g');
    for(var i = 0; i < in_chrs.length; i++){ transl[in_chrs.charAt(i)] = out_chrs.charAt(i); }
    return this.replace(chars_rgx, function(match){
        return transl[match]; });
};

EDIT (by @Tomalak)

I appreciate the idea. However, there are several things wrong with the implementation, as outlined in the comment below.

Here is how I would implement it.

var stripAccents = (function () {
  var in_chrs   = 'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ',
      out_chrs  = 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY', 
      chars_rgx = new RegExp('[' + in_chrs + ']', 'g'),
      transl    = {}, i,
      lookup    = function (m) { return transl[m] || m; };

  for (i=0; i<in_chrs.length; i++) {
    transl[ in_chrs[i] ] = out_chrs[i];
  }

  return function (s) { return s.replace(chars_rgx, lookup); }
})();

Find the files existing in one directory but not in the other

This answer optimizes one of the suggestions from @Adail-Junior by adding the -D option, which is helpful when neither of the directories being compared are git repositories:

git diff -D --no-index dir1/ dir2/

If you use -D then you won't see comparisons to /dev/null: text Binary files a/whatever and /dev/null differ

'too many values to unpack', iterating over a dict. key=>string, value=>list

Can't be iterating directly in dictionary. So you can through converting into tuple.

first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']

fields = {
    'first_names': first_names,
    'last_name': last_names,
         } 
tup_field=tuple(fields.items())
for names in fields.items():
     field,possible_values = names
     tup_possible_values=tuple(possible_values)
     for pvalue in tup_possible_values:
           print (field + "is" + pvalue)

How to get the browser viewport dimensions?

I looked and found a cross browser way:

_x000D_
_x000D_
function myFunction(){_x000D_
  if(window.innerWidth !== undefined && window.innerHeight !== undefined) { _x000D_
    var w = window.innerWidth;_x000D_
    var h = window.innerHeight;_x000D_
  } else {  _x000D_
    var w = document.documentElement.clientWidth;_x000D_
    var h = document.documentElement.clientHeight;_x000D_
  }_x000D_
  var txt = "Page size: width=" + w + ", height=" + h;_x000D_
  document.getElementById("demo").innerHTML = txt;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <body onresize="myFunction()" onload="myFunction()">_x000D_
   <p>_x000D_
    Try to resize the page._x000D_
   </p>_x000D_
   <p id="demo">_x000D_
    &nbsp;_x000D_
   </p>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Binding Combobox Using Dictionary as the Datasource

        var colors = new Dictionary < string, string > ();
        colors["10"] = "Red";

Binding to Combobox

        comboBox1.DataSource = new BindingSource(colors, null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key"; 

Full Source...Dictionary as a Combobox Datasource

Jeryy

Get city name using geolocation

geolocator.js can do that. (I'm the author).

Getting City Name (Limited Address)

geolocator.locateByIP(options, function (err, location) {
    console.log(location.address.city);
});

Getting Full Address Information

Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.

var options = {
    enableHighAccuracy: true,
    fallbackToIP: true, // fallback to IP if Geolocation fails or rejected
    addressLookup: true
};
geolocator.locate(options, function (err, location) {
    console.log(location.address.city);
});

This uses Google APIs internally (for address lookup). So before this call, you should configure geolocator with your Google API key.

geolocator.config({
    language: "en",
    google: {
        version: "3",
        key: "YOUR-GOOGLE-API-KEY"
    }
});

Geolocator supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and a lot more features...

Finding out the name of the original repository you cloned from in Git

I use this:

basename $(git remote get-url origin) .git

Which returns something like gitRepo. (Remove the .git at the end of the command to return something like gitRepo.git.)

(Note: It requires Git version 2.7.0 or later)

How to use a RELATIVE path with AuthUserFile in htaccess?

If you are trying to use XAMPP with Windows and want to use an .htaccess file on a live server and also develop on a XAMPP development machine the following works great!


1) After a fresh install of XAMPP make sure that Apache is installed as a service.

  • This is done by opening up the XAMPP Control Panel and clicking on the little red "X" to the left of the Apache module.
  • It will then ask you if you want to install Apache as a service.
  • Then it should turn to a green check mark.

2) When Apache is installed as a service add a new environment variable as a flag.

  • First stop the Apache service from the XAMPP Control Panel.
  • Next open a command prompt. (You know the little black window the simulates DOS)
  • Type "C:\Program Files (x86)\xampp\apache\bin\httpd.exe" -D "DEV" -k config.
  • This will append a new DEV flag to the environment variables that you can use later.

3) Start Apache

  • Open back up the XAMPP Control Panel and start the Apache service.

4) Create your .htaccess file with the following information...

<IfDefine DEV>
  AuthType Basic
  AuthName "Authorized access only!"
  AuthUserFile "/sandbox/web/scripts/.htpasswd"
  require valid-user
</IfDefine>

<IfDefine !DEV>
  AuthType Basic
  AuthName "Authorized access only!"
  AuthUserFile "/home/arvo/public_html/scripts/.htpasswd"
  require valid-user
</IfDefine>

To explain the above script here are a few notes...

  • My AuthUserFile is based on my setup and personal preferences.
  • I have a local test dev box that has my webpage located at c:\sandbox\web\. Inside that folder I have a folder called scripts that contains the password file .htpasswd.
  • The first entry IfDefine DEV is used for that instance. If DEV is set (which is what we did above, only on the dev machine of coarse) then it will use that entry.
  • And in turn if using the live server IfDefine !DEV will be used.

5) Create your password file (in this case named .htpasswd) with the following information...

user:$apr1$EPuSBcwO$/KtqDUttQMNUa5lGXSOzk.

A few things to note...

Force Intellij IDEA to reread all maven dependencies

In the latest IntelliJ IDEA version (2020.1.3 Ultimate Edition), You need to to click this little guy that appears on the top right of the editor window after you make a change to the pom.xml

This little guy is too small and in an unnoticeable position. I liked the previous versions where an alert shows up in the bottom right. Still can't find the option to enable auto import in this version.

enter image description here

Java compile error: "reached end of file while parsing }"

You need to enclose your class in { and }. A few extra pointers: According to the Java coding conventions, you should

  • Put your { on the same line as the method declaration:
  • Name your classes using CamelCase (with initial capital letter)
  • Name your methods using camelCase (with small initial letter)

Here's how I would write it:

public class ModMyMod extends BaseMod {

    public String version() {
         return "1.2_02";
    }

    public void addRecipes(CraftingManager recipes) {
       recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
          "#", Character.valueOf('#'), Block.dirt
       });
    }
}

@POST in RESTful web service

Please find example below, it might help you

package jersey.rest.test;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class SimpleService {
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {
        String output = "Get:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/{param}")
    public Response postMsg(@PathParam("param") String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/post")
    //@Consumes(MediaType.TEXT_XML)
    public Response postStrMsg( String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @PUT
    @Path("/{param}")
    public Response putMsg(@PathParam("param") String msg) {
        String output = "PUT: Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @DELETE
    @Path("/{param}")
    public Response deleteMsg(@PathParam("param") String msg) {
        String output = "DELETE:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @HEAD
    @Path("/{param}")
    public Response headMsg(@PathParam("param") String msg) {
        String output = "HEAD:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }
}

for testing you can use any tool like RestClient (http://code.google.com/p/rest-client/)

Recommended way to get hostname in Java

Strictly speaking - you have no choice but calling either hostname(1) or - on Unix gethostname(2). This is the name of your computer. Any attempt to determine the hostname by an IP address like this

InetAddress.getLocalHost().getHostName()

is bound to fail in some circumstances:

  • The IP address might not resolve into any name. Bad DNS setup, bad system setup or bad provider setup may be the reason for this.
  • A name in DNS can have many aliases called CNAMEs. These can only be resolved in one direction properly: name to address. The reverse direction is ambiguous. Which one is the "official" name?
  • A host can have many different IP addresses - and each address can have many different names. Two common cases are: One ethernet port has several "logical" IP addresses or the computer has several ethernet ports. It is configurable whether they share an IP or have different IPs. This is called "multihomed".
  • One Name in DNS can resolve to several IP Addresses. And not all of those addresses must be located on the same computer! (Usecase: A simple form of load-balancing)
  • Let's not even start talking about dynamic IP addresses.

Also don't confuse the name of an IP-address with the name of the host (hostname). A metaphor might make it clearer:

There is a large city (server) called "London". Inside the city walls much business happens. The city has several gates (IP addresses). Each gate has a name ("North Gate", "River Gate", "Southampton Gate"...) but the name of the gate is not the name of the city. Also you cannot deduce the name of the city by using the name of a gate - "North Gate" would catch half of the bigger cities and not just one city. However - a stranger (IP packet) walks along the river and asks a local: "I have a strange address: 'Rivergate, second left, third house'. Can you help me?" The local says: "Of course, you are on the right road, simply go ahead and you will arrive at your destination within half an hour."

This illustrates it pretty much I think.

The good news is: The real hostname is usually not necessary. In most cases any name which resolves into an IP address on this host will do. (The stranger might enter the city by Northgate, but helpful locals translate the "2nd left" part.)

In the remaining corner cases you must use the definitive source of this configuration setting - which is the C function gethostname(2). That function is also called by the program hostname.

How to update RecyclerView Adapter Data?

you have 2 options to do this: refresh UI from the adapter:

mAdapter.notifyDataSetChanged();

or refresh it from recyclerView itself:

recyclerView.invalidate();

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

Numpy matrix to array

First, Mv = numpy.asarray(M.T), which gives you a 4x1 but 2D array.

Then, perform A = Mv[0,:], which gives you what you want. You could put them together, as numpy.asarray(M.T)[0,:].

DOUBLE vs DECIMAL in MySQL

"are there any issue we should expect from only storing and retreiving a money amount in a DOUBLE column ?"

It sounds like no rounding errors can be produced in your scenario and if there were, they would be truncated by the conversion to BigDecimal.

So I would say no.

However, there is no guarantee that some change in the future will not introduce a problem.

How to select a single child element using jQuery?

<html>
<title>

    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<body>




<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
 <!-- </asp:LinkButton> -->
<!-- </asp:LinkButton> -->

<br />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>




</asp:Repeater>


</body>
<!-- Predefined JavaScript -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>

<script>

 $(function () {
        $('a').click(function() {
            $(this).parent().children('.dataContentSectionMessages').slideToggle();
        });
    });

    </script>


</html>

Is there a command line utility for rendering GitHub flavored Markdown?

I managed to use a one-line Ruby script for that purpose (although it had to go in a separate file). First, run these commands once on each client machine you'll be pushing docs from:

gem install github-markup
gem install commonmarker

Next, install this script in your client image, and call it render-readme-for-javadoc.rb:

require 'github/markup'

puts GitHub::Markup.render_s(GitHub::Markups::MARKUP_MARKDOWN, File.read('README.md'))

Finally, invoke it like this:

ruby ./render-readme-for-javadoc.rb >> project/src/main/javadoc/overview.html

ETA: This won't help you with StackOverflow-flavor Markdown, which seems to be failing on this answer.

XMLHttpRequest cannot load an URL with jQuery

Fiddle with 3 working solutions in action.

Given an external JSON:

myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'

Solution 1: $.ajax() + jsonp:

$.ajax({
  dataType: "jsonp",
  url: myurl ,
  }).done(function ( data ) {
  // do my stuff
});

Solution 2: $.ajax()+json+&calback=?:

$.ajax({
  dataType: "json",
  url: myurl + '&callback=?',
  }).done(function ( data ) {
  // do my stuff
});

Solution 3: $.getJSON()+calback=?:

$.getJSON( myurl + '&callback=?', function(data) {
  // do my stuff
});

Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/

Get a list of distinct values in List

Notes.Select(x => x.Author).Distinct();

This will return a sequence (IEnumerable<string>) of Author values -- one per unique value.

position: fixed doesn't work on iPad and iPhone

I ended up using the new jQuery Mobile v1.1: http://jquerymobile.com/blog/2012/04/13/announcing-jquery-mobile-1-1-0/

We now have a solid re-write that provides true fixed toolbars on the a lot of popular platforms and safely falls back to static toolbar positioning in other browsers.

The coolest part about this approach is that, unlike JS-based solutions that impose the unnatural scrolling physics across all platforms, our scrolling feels 100% native because it is. This means that scrolling feels right everywhere and works with touch, mousewheel and keyboard user input. As a bonus, our CSS-based solution is super lightweight and doesn’t impact compatibility or accessibility.

Markdown to create pages and table of contents?

Here is a simple bash script to generate Table of Contents. Requires no special dependencies, but bash.

https://github.com/Lirt/markdown-toc-bash

It handles well special symbols inside of headings, markdown links in headings and ignores code blocks.

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

I just created a simple application

What is the target processor of the application? I am guessing it is x86 - so either set it to x64 or anycpu.

I think the issue you are having is due to a 64bit process trying to access a 32bit dll.

Also, if you can't change the target processor you could try to enable 32-bit Applications from the Application Pools settings in IIS.

Android statusbar icons color

Yes it's possible to change it to gray (no custom colors) but this only works from API 23 and above you only need to add this in your values-v23/styles.xml

<item name="android:windowLightStatusBar">true</item>

enter image description here

Android - How to regenerate R class?

Try to add a new "Android XML file" to, for example, the /res/layout folder. This might cause the plugin to to regenerate the R class.

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

Can Google Chrome open local links?

From what I've seen of this the following is true for Firefox and Chrome;

1) If you have a HTML page open from a remote host then file:// links will not work i.e. Your address bar reads http://someserver.domain and the page contains a link such as <a href="file:///S:/sharedfile.txt">

2) If you have a HTML page open from your local host then file:// links will work i.e. your address bar reads file:///C:/mydir/index.html and the page contains a link such as <a href="file:///S:/sharedfile.txt">

For Internet Explorer point 1) does not hold true. A file on your local host can be accessed using the file:// link syntax from a webpage on a remote host. This is considered a security flaw in IE(By who? References?) (and it's there in IE8 too) because a remote host can access files on your local computer without your knowledge .... admittedly they have to get lucky with the filename but there are plenty of commonly named files there with the potential to contain personal/private information.

Call An Asynchronous Javascript Function Synchronously

You can also convert it into callbacks.

function thirdPartyFoo(callback) {    
  callback("Hello World");    
}

function foo() {    
  var fooVariable;

  thirdPartyFoo(function(data) {
    fooVariable = data;
  });

  return fooVariable;
}

var temp = foo();  
console.log(temp);

Variable that has the path to the current ansible-playbook that is executing?

I was using a playbook like this to test my roles locally:

---
- hosts: localhost
  roles:
     - role: .

but this stopped working with Ansible v2.2.

I debugged the aforementioned solution of

---
- hosts: all
  tasks:
    - name: Find out playbooks path
      shell: pwd
      register: playbook_path_output
    - debug: var=playbook_path_output.stdout

and it produced my home directory and not the "current working directory"

I settled with

---
- hosts: all
  roles:
    - role: '{{playbook_dir}}'

per the solution above.

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

How to encrypt String in Java

You might want to consider some automated tool to do the encryption / decryption code generation eg. https://www.stringencrypt.com/java-encryption/

It can generate different encryption and decryption code each time for the string or file encryption.

It's pretty handy when it comes to fast string encryption without using RSA, AES etc.

Sample results:

// encrypted with https://www.stringencrypt.com (v1.1.0) [Java]
// szTest = "Encryption in Java!"
String szTest = "\u9E3F\uA60F\uAE07\uB61B\uBE1F\uC62B\uCE2D\uD611" +
                "\uDE03\uE5FF\uEEED\uF699\uFE3D\u071C\u0ED2\u1692" +
                "\u1E06\u26AE\u2EDC";

for (int iatwS = 0, qUJQG = 0; iatwS < 19; iatwS++)
{
        qUJQG = szTest.charAt(iatwS);
        qUJQG ++;
        qUJQG = ((qUJQG << 5) | ( (qUJQG & 0xFFFF) >> 11)) & 0xFFFF;
        qUJQG -= iatwS;
        qUJQG = (((qUJQG & 0xFFFF) >> 6) | (qUJQG << 10)) & 0xFFFF;
        qUJQG ^= iatwS;
        qUJQG -= iatwS;
        qUJQG = (((qUJQG & 0xFFFF) >> 3) | (qUJQG << 13)) & 0xFFFF;
        qUJQG ^= 0xFFFF;
        qUJQG ^= 0xB6EC;
        qUJQG = ((qUJQG << 8) | ( (qUJQG & 0xFFFF) >> 8)) & 0xFFFF;
        qUJQG --;
        qUJQG = (((qUJQG & 0xFFFF) >> 5) | (qUJQG << 11)) & 0xFFFF;
        qUJQG ++;
        qUJQG ^= 0xFFFF;
        qUJQG += iatwS;
        szTest = szTest.substring(0, iatwS) + (char)(qUJQG & 0xFFFF) + szTest.substring(iatwS + 1);
}

System.out.println(szTest);

We use it all the time in our company.

Undo git pull, how to bring repos to old state

it works first use: git reflog

find your SHA of your previus state and make (HEAD@{1} is an example)

git reset --hard HEAD@{1}

Detect whether a Python string is a number or a letter

Check if string is positive digit (integer) and alphabet

You may use str.isdigit() and str.isalpha() to check whether given string is positive integer and alphabet respectively.

Sample Results:

# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True

# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False

Check for strings as positive/negative - integer/float

str.isdigit() returns False if the string is a negative number or a float number. For example:

# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False

If you want to also check for the negative integers and float, then you may write a custom function to check for it as:

def is_number(n):
    try:
        float(n)   # Type-casting the string to `float`.
                   # If string is not a valid `float`, 
                   # it'll raise `ValueError` exception
    except ValueError:
        return False
    return True

Sample Run:

>>> is_number('123')    # positive integer number
True

>>> is_number('123.4')  # positive float number
True
 
>>> is_number('-123')   # negative integer number
True

>>> is_number('-123.4') # negative `float` number
True

>>> is_number('abc')    # `False` for "some random" string
False

Discard "NaN" (not a number) strings while checking for number

The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:

>>> is_number('NaN')
True

In order to check whether the number is "NaN", you may use math.isnan() as:

>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)
True

Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:

# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False

Hence, above function is_number can be updated to return False for "NaN" as:

def is_number(n):
    is_number = True
    try:
        num = float(n)
        # check for "nan" floats
        is_number = num == num   # or use `math.isnan(num)`
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('Nan')   # not a number "Nan" string
False

>>> is_number('nan')   # not a number string "nan" with all lower cased
False

>>> is_number('123')   # positive integer
True

>>> is_number('-123')  # negative integer
True

>>> is_number('-1.12') # negative `float`
True

>>> is_number('abc')   # "some random" string
False

Allow Complex Number like "1+2j" to be treated as valid number

The above function will still return you False for the complex numbers. If you want your is_number function to treat complex numbers as valid number, then you need to type cast your passed string to complex() instead of float(). Then your is_number function will look like:

def is_number(n):
    is_number = True
    try:
        #      v type-casting the number here as `complex`, instead of `float`
        num = complex(n)
        is_number = num == num
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('1+2j')    # Valid 
True                     #      : complex number 

>>> is_number('1+ 2j')   # Invalid 
False                    #      : string with space in complex number represetantion
                         #        is treated as invalid complex number

>>> is_number('123')     # Valid
True                     #      : positive integer

>>> is_number('-123')    # Valid 
True                     #      : negative integer

>>> is_number('abc')     # Invalid 
False                    #      : some random string, not a valid number

>>> is_number('nan')     # Invalid
False                    #      : not a number "nan" string

PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.

Upload artifacts to Nexus, without Maven

Have you considering using the Maven command-line to upload files?

mvn deploy:deploy-file \
    -Durl=$REPO_URL \
    -DrepositoryId=$REPO_ID \
    -DgroupId=org.myorg \
    -DartifactId=myproj \
    -Dversion=1.2.3  \
    -Dpackaging=zip \
    -Dfile=myproj.zip

This will automatically generate the Maven POM for the artifact.

Update

The following Sonatype article states that the "deploy-file" maven plugin is the easiest solution, but it also provides some examples using curl:

https://support.sonatype.com/entries/22189106-How-can-I-programatically-upload-an-artifact-into-Nexus-

How to combine class and ID in CSS selector?

In your stylesheet:

div#content.myClass

Edit: These might help, too:

div#content.myClass.aSecondClass.aThirdClass /* Won't work in IE6, but valid */
div.firstClass.secondClass /* ditto */

and, per your example:

div#content.sectionA

Edit, 4 years later: Since this is super old and people keep finding it: don't use the tagNames in your selectors. #content.myClass is faster than div#content.myClass because the tagName adds a filtering step that you don't need. Use tagNames in selectors only where you must!

How do I append to a table in Lua

You are looking for the insert function, found in the table section of the main library.

foo = {}
table.insert(foo, "bar")
table.insert(foo, "baz")

How to Retrieve value from JTextField in Java Swing?

You can use the getText() method anywhere in your code it is instancely called by your object, So you can use the method anywhere within a calass

Count the number of occurrences of a character in a string in Javascript

You can also rest your string and work with it like an array of elements using

_x000D_
_x000D_
const mainStr = 'str1,str2,str3,str4';_x000D_
const commas = [...mainStr].filter(l => l === ',').length;_x000D_
_x000D_
console.log(commas);
_x000D_
_x000D_
_x000D_

Or

_x000D_
_x000D_
const mainStr = 'str1,str2,str3,str4';_x000D_
const commas = [...mainStr].reduce((a, c) => c === ',' ? ++a : a, 0);_x000D_
_x000D_
console.log(commas);
_x000D_
_x000D_
_x000D_

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

Your welcome page is set as That Servlet . So all css , images path should be given relative to that servlet DIR . which is a bad idea ! why do you need the servlet as a home page ? set .jsp as index page and redirect to any page from there ?

are you trying to populate any fields from db is that why you are using servlet ?

Can't connect to Postgresql on port 5432

You probably need to either open up the port to access it in your LAN (or outside of it) or bind the network address to the port (make PostgreSQL listen on your LAN instead of just on localhost)

Set Value of Input Using Javascript Function

I'm not using YUI, but in case it helps anyone else - my issue was that I had duplicate ID's on the page (was working inside a dialog and forgot about the page underneath).

Changing the ID so it was unique allowed me to use the methods listed in Sangeet's answer.

How to turn on WCF tracing?

In your web.config (on the server) add

<system.diagnostics>
 <sources>
  <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
   <listeners>
    <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\logs\Traces.svclog"/>
   </listeners>
  </source>
 </sources>
</system.diagnostics>

How to convert SecureString to System.String?

Use the System.Runtime.InteropServices.Marshal class:

String SecureStringToString(SecureString value) {
  IntPtr valuePtr = IntPtr.Zero;
  try {
    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
    return Marshal.PtrToStringUni(valuePtr);
  } finally {
    Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  }
}

If you want to avoid creating a managed string object, you can access the raw data using Marshal.ReadInt16(IntPtr, Int32):

void HandleSecureString(SecureString value) {
  IntPtr valuePtr = IntPtr.Zero;
  try {
    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
    for (int i=0; i < value.Length; i++) {
      short unicodeChar = Marshal.ReadInt16(valuePtr, i*2);
      // handle unicodeChar
    }
  } finally {
    Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  }
}

How can I get the status code from an http error in Axios?

In order to get the http status code returned from the server, you can add validateStatus: status => true to axios options:

axios({
    method: 'POST',
    url: 'http://localhost:3001/users/login',
    data: { username, password },
    validateStatus: () => true
}).then(res => {
    console.log(res.status);
});

This way, every http response resolves the promise returned from axios.

https://github.com/axios/axios#handling-errors

Plotting histograms from grouped data in a pandas DataFrame

One solution is to use matplotlib histogram directly on each grouped data frame. You can loop through the groups obtained in a loop. Each group is a dataframe. And you can create a histogram for each one.

from pandas import DataFrame
import numpy as np
x = ['A']*300 + ['B']*400 + ['C']*300
y = np.random.randn(1000)
df = DataFrame({'Letter':x, 'N':y})
grouped = df.groupby('Letter')

for group in grouped:
  figure()
  matplotlib.pyplot.hist(group[1].N)
  show()

How to generate different random numbers in a loop in C++?

Every iteration you are resetting the sequence of pseudorandom numbers because you are calling srand with the same seed (since the call to time is so frequent). Either use a different seed, or call srand once before you enter the loop.

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

The following steps could help:

  1. Right-click on project » Properties » Java Build Path
  2. Select Libraries tab
  3. Find the JRE System Library and remove it
  4. Click Add Library... button at right side » Add the JRE System Library (Workspace default JRE)

How to grep recursively, but only in files with certain extensions?

How about:

find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print

Escape text for HTML

there are some special quotes characters which are not removed by HtmlEncode and will not be displayed in Edge or IE correctly like ” and “ . you can extent replacing these characters with something like below function.

private string RemoveJunkChars(string input)
{
    return HttpUtility.HtmlEncode(input.Replace("”", "\"").Replace("“", "\""));
}

Check if SQL Connection is Open or Closed

This code is a little more defensive, before opening a connection, check state. If connection state is Broken then we should try to close it. Broken means that the connection was previously opened and not functioning correctly. The second condition determines that connection state must be closed before attempting to open it again so the code can be called repeatedly.

// Defensive database opening logic.

if (_databaseConnection.State == ConnectionState.Broken) {
    _databaseConnection.Close();
}

if (_databaseConnection.State == ConnectionState.Closed) {
    _databaseConnection.Open();
}

Why does foo = filter(...) return a <filter object>, not a list?

From the documentation

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)]

In python3, rather than returning a list; filter, map return an iterable. Your attempt should work on python2 but not in python3

Clearly, you are getting a filter object, make it a list.

shesaid = list(filter(greetings(), ["hello", "goodbye"]))

Equivalent of varchar(max) in MySQL?

Mysql Converting column from VARCHAR to TEXT when under limit size!!!

mysql> CREATE TABLE varchars1(ch3 varchar(6),ch1 varchar(3),ch varchar(4000000))
;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> SHOW WARNINGS;
+-------+------+---------------------------------------------+
| Level | Code | Message                                     |
+-------+------+---------------------------------------------+
| Note  | 1246 | Converting column 'ch' from VARCHAR to TEXT |
+-------+------+---------------------------------------------+
1 row in set (0.00 sec)

mysql>

How to kill a while loop with a keystroke?

The easiest way is to just interrupt it with the usual Ctrl-C (SIGINT).

try:
    while True:
        do_something()
except KeyboardInterrupt:
    pass

Since Ctrl-C causes KeyboardInterrupt to be raised, just catch it outside the loop and ignore it.

How to execute a Python script from the Django shell?

The << part is wrong, use < instead:

$ ./manage.py shell < myscript.py

You could also do:

$ ./manage.py shell
...
>>> execfile('myscript.py')

For python3 you would need to use

>>> exec(open('myscript.py').read())

Bootstrap 3 - 100% height of custom div inside column

My solution was to make all the parents 100% and set a specific percentage for each row:

html, body,div[class^="container"] ,.column {
    height: 100%;
}

.row0 {height: 10%;}
.row1 {height: 40%;}
.row2 {height: 50%;}

How to Increase Import Size Limit in phpMyAdmin

if you're using xampp, find the php.ini (in xampp folder itself), go to line 735 and change the post_max_size to the value you wish. ex: if you want to upgrade to 80MiB,

post_max_size = 80M

make sure to restart apache after changing the value.

That's it...

How do I pretty-print existing JSON data with Java?

Another way to use gson:

String json_String_to_print = ...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
return gson.toJson(jp.parse(json_String_to_print));

It can be used when you don't have the bean as in susemi99's post.

How to normalize a 2-dimensional numpy array in python less verbose?

I think you can normalize the row elements sum to 1 by this: new_matrix = a / a.sum(axis=1, keepdims=1). And the column normalization can be done with new_matrix = a / a.sum(axis=0, keepdims=1). Hope this can hep.

Setting a log file name to include current date in Log4j

You can set FileAppender dynamically

SimpleLayout layout = new SimpleLayout();           
FileAppender appender = new FileAppender(layout,"logname."+new Date().toLocaleString(),false);
logger.addAppender(appender); 

How to use makefiles in Visual Studio?

The VS equivalent of a makefile is a "Solution" (over-simplified, I know).

How do I catch an Ajax query post error?

A simple way is to implement ajaxError:

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time.

For example:

$('.log').ajaxError(function() {
  $(this).text('Triggered ajaxError handler.');
});

I would suggest reading the ajaxError documentation. It does more than the simple use-case demonstrated above - mainly its callback accepts a number of parameters:

$('.log').ajaxError(function(e, xhr, settings, exception) {
  if (settings.url == 'ajax/missing.html') {
    $(this).text('Triggered ajaxError handler.');
  }
});

How to post pictures to instagram using API

UPDATE It is now possible:

https://developers.facebook.com/docs/instagram-api/content-publishing

The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.

How can I remove text within parentheses with a regex?

If you can stand to use sed (possibly execute from within your program, it'd be as simple as:

sed 's/(.*)//g'

firefox proxy settings via command line

You can easily launch Firefox from the command line with a proxy server using the -proxy-server option.

This works on Mac, Windows and Linux.

path_to_firefox/firefox.exe -proxy-server %proxy_URL%

Mac Example:

/Applications/Firefox.app/Contents/MacOS/firefox -proxy-server proxy.example.com

Evaluate empty or null JSTL c tags

if you check only null or empty then you can use the with default option for this: <c:out default="var1 is empty or null." value="${var1}"/>

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

After several tries i found htmlentities function works.

$value = htmlentities($value)

Git merge reports "Already up-to-date" though there is a difference

This happens because your local copy of the branch you want to merge is out of date. I've got my branch, called MyBranch and I want to merge it into ProjectMaster.

_>git status
On branch MyBranch-Issue2
Your branch is up-to-date with 'origin/MyBranch-Issue2'.

nothing to commit, working tree clean

_>git merge ProjectMaster
Already up-to-date.

But I know that there are changes that need to be merged!

Here's the thing, when I type git merge ProjectMaster, git looks at my local copy of this branch, which might not be current. To see if this is the case, I first tell Git to check and see if my branches are out of date and fetch any changes if so using, uh, fetch. Then I hop into the branch I want to merge to see what's happening there...

_>git fetch origin

_>git checkout ProjectMaster
Switched to branch ProjectMaster
**Your branch is behind 'origin/ProjectMaster' by 85 commits, and can be fast-forwarded.**
  (use "git pull" to update your local branch)

Ah-ha! My local copy is stale by 85 commits, that explains everything! Now, I Pull down the changes I'm missing, then hop over to MyBranch and try the merge again.

_>git pull
Updating 669f825..5b49912
Fast-forward

_>git checkout MyBranch-Issue2
Switched to branch MyBranch-Issue2
Your branch is up-to-date with 'origin/MyBranch-Issue2'.

_>git merge ProjectMaster
Auto-merging Runbooks/File1.ps1
CONFLICT (content): Merge conflict in Runbooks/Runbooks/File1.ps1

Automatic merge failed; fix conflicts and then commit the result.

And now I have another issue to fix...

PHPMailer character encoding issues

$mail -> CharSet = "UTF-8";
$mail = new PHPMailer();

line $mail -> CharSet = "UTF-8"; must be after $mail = new PHPMailer(); and with no spaces!

try this

$mail = new PHPMailer();
$mail->CharSet = "UTF-8";

Can iterators be reset in Python?

While there is no iterator reset, the "itertools" module from python 2.6 (and later) has some utilities that can help there. One of then is the "tee" which can make multiple copies of an iterator, and cache the results of the one running ahead, so that these results are used on the copies. I will seve your purposes:

>>> def printiter(n):
...   for i in xrange(n):
...     print "iterating value %d" % i
...     yield i

>>> from itertools import tee
>>> a, b = tee(printiter(5), 2)
>>> list(a)
iterating value 0
iterating value 1
iterating value 2
iterating value 3
iterating value 4
[0, 1, 2, 3, 4]
>>> list(b)
[0, 1, 2, 3, 4]

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

Visual Studio Expand/Collapse keyboard shortcuts

Go to Tools->Options->Text Editor->c#->Advanced and uncheck the first checkbox Enter outlining mode when files open.

This will solve this problem forever

pytest cannot import module while python can

If it is related to python code that was originally developed in python 2.7 and now migrated into python 3.x than the problem is probably related to an import issue.

e.g. when importing an object from a file: base that is located in the same directory this will work in python 2.x:

from base import MyClass

in python 3.x you should replace with base full path or .base not doing so will cause the above problem. so try:

from .base import MyClass

Openstreetmap: embedding map in webpage (like Google Maps)

I would also take a look at CloudMade's developer tools. They offer a beautifully styled OSM base map service, an OpenLayers plugin, and even their own light-weight, very fast JavaScript mapping client. They also host their own routing service, which you mentioned as a possible requirement. They have great documentation and examples.

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

How to read strings from a Scanner in a Java console application?

Replace:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.next());

with:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.nextLine());

This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname

RecyclerView - Get view at particular position

If you guys are having null with every attempt to get a view with any int position, try to add a new constructor parameter to your adapter like this for example:

class RecyclerViewTableroAdapter(
private val fichas: Array<MFicha?>,
private val activity: View.OnClickListener,
private val indicesGanadores:MutableList<Int>
) : RecyclerView.Adapter<RecyclerViewTableroAdapter.ViewHolder>() {
//CODE 
}

I added indicesGanadores to color my cardview background if my game is won.

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
//CODE
if(indicesGanadores.contains(position)){
        holder.cardViewFicha.setCardBackgroundColor((activity as MainActivity).resources.getColor(R.color.DarkGreen))
    }
//MORE CODE
}  

If I don't have to color my background yet I just send an empty mutable list like this:

binding.recyclerViewMain.adapter = RecyclerViewTableroAdapter(fichasTablero, this@MainActivity, mutableListOf<Int>())

Happy coding!...

Gson: Is there an easier way to serialize a map

I'm pretty sure GSON serializes/deserializes Maps and multiple-nested Maps (i.e. Map<String, Map<String, Object>>) just fine by default. The example provided I believe is nothing more than just a starting point if you need to do something more complex.

Check out the MapTypeAdapterFactory class in the GSON source: http://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java

So long as the types of the keys and values can be serialized into JSON strings (and you can create your own serializers/deserializers for these custom objects) you shouldn't have any issues.

Edit line thickness of CSS 'underline' attribute

Another way to do this is using ":after" (pseudo-element) on the element you want to underline.

h2{
  position:relative;
  display:inline-block;
  font-weight:700;
  font-family:arial,sans-serif;
  text-transform:uppercase;
  font-size:3em;
}
h2:after{
  content:"";
  position:absolute;
  left:0;
  bottom:0;
  right:0;
  margin:auto;
  background:#000;
  height:1px;

}

Python strftime - date without leading 0?

Take a look at - bellow:

>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)

Convert integer to hex and hex to integer

Given:

declare @hexStr varchar(16), @intVal int

IntToHexStr:

select @hexStr = convert(varbinary, @intVal, 1)

HexStrToInt:

declare
    @query varchar(100),
    @parameters varchar(50)

select
    @query = 'select @result = convert(int,' + @hb + ')',
    @parameters = '@result int output'

exec master.dbo.Sp_executesql @query, @parameters, @intVal output

Get ASCII value at input word

simply do

int a = ch

(also this has nothing to do with android)

HTML inside Twitter Bootstrap popover

Another way to specify the popover content in a reusable way is to create a new data attribute like data-popover-content and use it like this:

HTML:

<!-- Popover #1 -->
<a class="btn btn-primary" data-placement="top" data-popover-content="#a1" data-toggle="popover" data-trigger="focus" href="#" tabindex="0">Popover Example</a>

<!-- Content for Popover #1 -->
<div class="hidden" id="a1">
  <div class="popover-heading">
    This is the heading for #1
  </div>

  <div class="popover-body">
    This is the body for #1
  </div>
</div>

JS:

$(function(){
    $("[data-toggle=popover]").popover({
        html : true,
        content: function() {
          var content = $(this).attr("data-popover-content");
          return $(content).children(".popover-body").html();
        },
        title: function() {
          var title = $(this).attr("data-popover-content");
          return $(title).children(".popover-heading").html();
        }
    });
});

This can be useful when you have a lot of html to place into your popovers.

Here is an example fiddle: http://jsfiddle.net/z824fn6b/

Array or List in Java. Which is faster?

I suggest that you use a profiler to test which is faster.

My personal opinion is that you should use Lists.

I work on a large codebase and a previous group of developers used arrays everywhere. It made the code very inflexible. After changing large chunks of it to Lists we noticed no difference in speed.

Phone mask with jQuery and Masked Input Plugin

If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.

The cleanest way:

var options =  {
    onKeyPress: function(phone, e, field, options) {
        var masks = ['(00) 0000-00000', '(00) 00000-0000'];
        var mask = (phone.length>14) ? masks[1] : masks[0];
        $('.phone-input').mask(mask, options);
    }
};

$('.phone-input').mask('(00) 0000-00000', options);

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

For UWP, I tried a different approach. I extended the ComboBox class, and processed the SelectionChanged and OnKeyUp events on the ComboBox as well as the Tapped event on the ComboBoxItems. In cases where I get a Tapped event or an Enter or Space key without first getting a SelectionChanged then I know the current item has been re-selected and I respond accordingly.

class ExtendedComboBox : ComboBox
{
    public ExtendedComboBox()
    {
        SelectionChanged += OnSelectionChanged;
    }

    protected override void PrepareContainerForItemOverride(Windows.UI.Xaml.DependencyObject element, object item)
    {
        ComboBoxItem cItem = element as ComboBoxItem;
        if (cItem != null)
        {
            cItem.Tapped += OnItemTapped;
        }

        base.PrepareContainerForItemOverride(element, item);
    }

    protected override void OnKeyUp(KeyRoutedEventArgs e)
    {
        // if the user hits the Enter or Space to select an item, then consider this a "reselect" operation
        if ((e.Key == Windows.System.VirtualKey.Space || e.Key == Windows.System.VirtualKey.Enter) && !isSelectionChanged)
        {
            // handle re-select logic here
        }

        isSelectionChanged = false;

        base.OnKeyUp(e);
    }

    // track whether or not the ComboBox has received a SelectionChanged notification
    // in cases where it has not yet we get a Tapped or KeyUp notification we will want to consider that a "re-select"
    bool isSelectionChanged = false;
    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        isSelectionChanged = true;
    }

    private void OnItemTapped(object sender, TappedRoutedEventArgs e)
    {
        if (!isSelectionChanged)
        {
            // indicates that an item was re-selected  - handle logic here
        }

        isSelectionChanged = false;
    }
}

Insert a row to pandas dataframe

I put together a short function that allows for a little more flexibility when inserting a row:

def insert_row(idx, df, df_insert):
    dfA = df.iloc[:idx, ]
    dfB = df.iloc[idx:, ]

    df = dfA.append(df_insert).append(dfB).reset_index(drop = True)

    return df

which could be further shortened to:

def insert_row(idx, df, df_insert):
    return df.iloc[:idx, ].append(df_insert).append(df.iloc[idx:, ]).reset_index(drop = True)

Then you could use something like:

df = insert_row(2, df, df_new)

where 2 is the index position in df where you want to insert df_new.

how to bypass Access-Control-Allow-Origin?

It's a really bad idea to use *, which leaves you wide open to cross site scripting. You basically want your own domain all of the time, scoped to your current SSL settings, and optionally additional domains. You also want them all to be sent as one header. The following will always authorize your own domain in the same SSL scope as the current page, and can optionally also include any number of additional domains. It will send them all as one header, and overwrite the previous one(s) if something else already sent them to avoid any chance of the browser grumbling about multiple access control headers being sent.

class CorsAccessControl
{
    private $allowed = array();

    /**
     * Always adds your own domain with the current ssl settings.
     */
    public function __construct()
    {
        // Add your own domain, with respect to the current SSL settings.
        $this->allowed[] = 'http'
            . ( ( array_key_exists( 'HTTPS', $_SERVER )
                && $_SERVER['HTTPS'] 
                && strtolower( $_SERVER['HTTPS'] ) !== 'off' ) 
                    ? 's' 
                    : null )
            . '://' . $_SERVER['HTTP_HOST'];
    }

    /**
     * Optionally add additional domains. Each is only added one time.
     */
    public function add($domain)
    {
        if ( !in_array( $domain, $this->allowed )
        {
            $this->allowed[] = $domain;
        }
    /**
     * Send 'em all as one header so no browsers grumble about it.
     */
    public function send()
    {
        $domains = implode( ', ', $this->allowed );
        header( 'Access-Control-Allow-Origin: ' . $domains, true ); // We want to send them all as one shot, so replace should be true here.
    }
}

Usage:

$cors = new CorsAccessControl();

// If you are only authorizing your own domain:
$cors->send();

// If you are authorizing multiple domains:
foreach ($domains as $domain)
{
    $cors->add($domain);
}
$cors->send();

You get the idea.

afxwin.h file is missing in VC++ Express Edition

Including the header afxwin.h signalizes use of MFC. The following instructions (based on those on CodeProject.com) could help to get MFC code compiling:

  1. Download and install the Windows Driver Kit.

  2. Select menu Tools > Options… > Projects and Solutions > VC++ Directories.

  3. In the drop-down menu Show directories for select Include files.

  4. Add the following paths (replace $(WDK_directory) with the directory where you installed Windows Driver Kit in the first step):

    $(WDK_directory)\inc\mfc42
    $(WDK_directory)\inc\atl30
    

  5. In the drop-down menu Show directories for select Library files and add (replace $(WDK_directory) like before):

    $(WDK_directory)\lib\mfc\i386
    $(WDK_directory)\lib\atl\i386
    

  6. In the $(WDK_directory)\inc\mfc42\afxwin.inl file, edit the following lines (starting from 1033):

    _AFXWIN_INLINE CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    to

    _AFXWIN_INLINE BOOL CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE BOOL CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    In other words, add BOOL after _AFXWIN_INLINE.

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

How to center a View inside of an Android Layout?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center">
    <ProgressBar
        android:id="@+id/ProgressBar01"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"></ProgressBar>
    <TextView
        android:layout_below="@id/ProgressBar01"
        android:text="@string/please_wait_authenticating"
        android:id="@+id/txtText"
        android:paddingTop="30px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></TextView>
</RelativeLayout>

Convert generic List/Enumerable to DataTable?

A small change to Marc's answer to make it work with value types like List<string> to data table:

public static DataTable ListToDataTable<T>(IList<T> data)
{
    DataTable table = new DataTable();

    //special handling for value types and string
    if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
    {

        DataColumn dc = new DataColumn("Value", typeof(T));
        table.Columns.Add(dc);
        foreach (T item in data)
        {
            DataRow dr = table.NewRow();
            dr[0] = item;
            table.Rows.Add(dr);
        }
    }
    else
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        foreach (PropertyDescriptor prop in properties)
        {
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
            {
                try
                {
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                }
                catch (Exception ex)
                {
                    row[prop.Name] = DBNull.Value;
                }
            }
            table.Rows.Add(row);
        }
    }
    return table;
}

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

The below config was the cause of my issue:

    <rewrite>
      <rules>
        <clear />
        <rule name="Redirect to HTTPS" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^.*spvitals\.com$" />
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
        </rule>
      </rules>
    </rewrite>

Note: I removed this section for local testing, as it works fine in Azure.

Removing black dots from li and ul

There you go, this is what I used to fix your problem:

CSS CODE

nav ul { list-style-type: none; }

HTML CODE

<nav>
<ul>
<li><a href="#">Milk</a>
   <ul>
   <li><a href="#">Goat</a></li>
   <li><a href="#">Cow</a></li>
   </ul>
</li>
<li><a href="#">Eggs</a>
   <ul>
   <li><a href="#">Free-range</a></li>
   <li><a href="#">Other</a></li>
   </ul>
</li>
<li><a href="#">Cheese</a>
   <ul>
   <li><a href="#">Smelly</a></li>
   <li><a href="#">Extra smelly</a></li>
   </ul>
</li>
</ul>
</nav>

How does one generate a random number in Apple's Swift language?

 let MAX : UInt32 = 9
 let MIN : UInt32 = 1

    func randomNumber()
{
    var random_number = Int(arc4random_uniform(MAX) + MIN)
    print ("random = ", random_number);
}

How do I get the picture size with PIL?

This is a complete example loading image from URL, creating with PIL, printing the size and resizing...

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

How do I delete multiple rows in Entity Framework (without foreach)

For anyone using EF5, following extension library can be used: https://github.com/loresoft/EntityFramework.Extended

context.Widgets.Delete(w => w.WidgetId == widgetId);

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

Because you're not specifying a precision and a rounding-mode. BigDecimal is complaining that it could use 10, 20, 5000, or infinity decimal places, and it still wouldn't be able to give you an exact representation of the number. So instead of giving you an incorrect BigDecimal, it just whinges at you.

However, if you supply a RoundingMode and a precision, then it will be able to convert (eg. 1.333333333-to-infinity to something like 1.3333 ... but you as the programmer need to tell it what precision you're 'happy with'.

Command line input in Python

Just Taking Input

the_input = raw_input("Enter input: ")

And that's it.

Moreover, if you want to make a list of inputs, you can do something like:

a = []

for x in xrange(1,10):
    a.append(raw_input("Enter Data: "))

In that case, you'll be asked for data 10 times to store 9 items in a list.

Output:

Enter data: 2
Enter data: 3
Enter data: 4
Enter data: 5
Enter data: 7
Enter data: 3
Enter data: 8
Enter data: 22
Enter data: 5
>>> a
['2', '3', '4', '5', '7', '3', '8', '22', '5']

You can search that list the fundamental way with something like (after making that list):

if '2' in a:
    print "Found"

else: print "Not found."

You can replace '2' with "raw_input()" like this:

if raw_input("Search for: ") in a:
    print "Found"
else: 
    print "Not found"

Taking Raw Data From Input File via Commandline Interface

If you want to take the input from a file you feed through commandline (which is normally what you need when doing code problems for competitions, like Google Code Jam or the ACM/IBM ICPC):

example.py

while(True):
    line = raw_input()
    print "input data: %s" % line

In command line interface:

example.py < input.txt

Hope that helps.

Running sites on "localhost" is extremely slow

If your using .Net then turning off debug in your Web.Config is going to improve performance no end.

<compilation defaultLanguage="c#" debug="false" batch="false" targetFramework="4.0">

Select from multiple tables without a join?

You could try something like this:

SELECT ...
FROM (
    SELECT f1,f2,f3 FROM table1
    UNION
    SELECT f1,f2,f3 FROM table2
)
WHERE ...

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

This works well for specific articles where the text is all wrapped in <p> tags. Since the web is an ugly place, it's not always the case.

Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span> or a <div>, or an <li>).

To find all text nodes in the DOM, you can use soup.find_all(text=True).

This is going to return some undesired text, like the contents of <script> and <style> tags. You'll need to filter out the text contents of elements you don't want.

blacklist = [
  'style',
  'script',
  # other elements,
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]

If you are working with a known set of tags, you can tag the opposite approach:

whitelist = [
  'p'
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]

Angular 2 http post params and body

Yes the problem is here. It's related to your syntax.

Try using this

return this.http.post(this.BASE_URL, params, options)
  .map(data => this.handleData(data))
  .catch(this.handleError);

instead of

return this.http.post(this.BASE_URL, params, options)
  .map(this.handleData)
  .catch(this.handleError);

Also, the second parameter is supposed to be the body, not the url params.

Google Maps API v3: InfoWindow not sizing correctly

I was having the same problem with IE and tried many of the fixes detailed in these responses, but was unable to remove the vertical scrollbars in IE reliably.

What worked best for me was to switch to fixed font sizes inside the infowindow -- 'px'... I was using ems. By fixing the font size I no longer needed to explicitly declare the infowindow width or height and the scrollbars were gone for good.

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)

Or

data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

Check element exists in array

EAFP vs. LBYL

I understand your dilemma, but Python is not PHP and coding style known as Easier to Ask for Forgiveness than for Permission (or EAFP in short) is a common coding style in Python.

See the source (from documentation):

EAFP - Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

So, basically, using try-catch statements here is not a last resort; it is a common practice.

"Arrays" in Python

PHP has associative and non-associative arrays, Python has lists, tuples and dictionaries. Lists are similar to non-associative PHP arrays, dictionaries are similar to associative PHP arrays.

If you want to check whether "key" exists in "array", you must first tell what type in Python it is, because they throw different errors when the "key" is not present:

>>> l = [1,2,3]
>>> l[4]

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    l[4]
IndexError: list index out of range
>>> d = {0: '1', 1: '2', 2: '3'}
>>> d[4]

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    d[4]
KeyError: 4

And if you use EAFP coding style, you should just catch these errors appropriately.

LBYL coding style - checking indexes' existence

If you insist on using LBYL approach, these are solutions for you:

  • for lists just check the length and if possible_index < len(your_list), then your_list[possible_index] exists, otherwise it doesn't:

    >>> your_list = [0, 1, 2, 3]
    >>> 1 < len(your_list) # index exist
    True
    >>> 4 < len(your_list) # index does not exist
    False
    
  • for dictionaries you can use in keyword and if possible_index in your_dict, then your_dict[possible_index] exists, otherwise it doesn't:

    >>> your_dict = {0: 0, 1: 1, 2: 2, 3: 3}
    >>> 1 in your_dict # index exists
    True
    >>> 4 in your_dict # index does not exist
    False
    

Did it help?

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

The Html.TextboxFor always creates a textbox (<input type="text" ...).

While the EditorFor looks at the type and meta information, and can render another control or a template you supply.

For example for DateTime properties you can create a template that uses the jQuery DatePicker.

Get the client IP address using PHP

The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables.

However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.

The below both functions are equivalent with the difference only in how and from where the values are retrieved.

getenv() is used to get the value of an environment variable in PHP.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

$_SERVER is an array that contains server variables created by the web server.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

Find and replace entire mysql database

Simple Soltion

UPDATE `table_name`
 SET `field_name` = replace(same_field_name, 'unwanted_text', 'wanted_text')

Codeigniter - no input file specified

My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:

<IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On

    # If your website begins from a folder e.g localhost/my_project then 
    # you have to change it to: RewriteBase /my_project/
    # If your site begins from the root e.g. example.local/ then
    # let it as it is
    RewriteBase /

    # Protect application and system files from being viewed when the index.php is missing
    RewriteCond $1 ^(application|system|private|logs)

    # Rewrite to index.php/access_denied/URL
    RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

    # Allow these directories and files to be displayed directly:
    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)

    # No rewriting
    RewriteRule ^(.*)$ - [PT,L]

    # Rewrite to index.php/URL
    RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>

Setting HTTP headers

Do not use '*' for Origin, until You really need a completely public behavior.
As Wikipedia says:

"The value of "*" is special in that it does not allow requests to supply credentials, meaning HTTP authentication, client-side SSL certificates, nor does it allow cookies to be sent."

That means, you'll get a lot of errors, especially in Chrome when you'll try to implement for example a simple authentication.

Here is a corrected wrapper:

// Code has not been tested.
func addDefaultHeaders(fn http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        if origin := r.Header.Get("Origin"); origin != "" {
            w.Header().Set("Access-Control-Allow-Origin", origin)
        }
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token")
        w.Header().Set("Access-Control-Allow-Credentials", "true")
        fn(w, r)
    }
}

And don't forget to reply all these headers to the preflight OPTIONS request.

@selector() in Swift?

Swift itself doesn't use selectors — several design patterns that in Objective-C make use of selectors work differently in Swift. (For example, use optional chaining on protocol types or is/as tests instead of respondsToSelector:, and use closures wherever you can instead of performSelector: for better type/memory safety.)

But there are still a number of important ObjC-based APIs that use selectors, including timers and the target/action pattern. Swift provides the Selector type for working with these. (Swift automatically uses this in place of ObjC's SEL type.)

In Swift 2.2 (Xcode 7.3) and later (including Swift 3 / Xcode 8 and Swift 4 / Xcode 9):

You can construct a Selector from a Swift function type using the #selector expression.

let timer = Timer(timeInterval: 1, target: object,
                  selector: #selector(MyClass.test),
                  userInfo: nil, repeats: false)
button.addTarget(object, action: #selector(MyClass.buttonTapped),
                 for: .touchUpInside)
view.perform(#selector(UIView.insertSubview(_:aboveSubview:)),
             with: button, with: otherButton)

The great thing about this approach? A function reference is checked by the Swift compiler, so you can use the #selector expression only with class/method pairs that actually exist and are eligible for use as selectors (see "Selector availability" below). You're also free to make your function reference only as specific as you need, as per the Swift 2.2+ rules for function-type naming.

(This is actually an improvement over ObjC's @selector() directive, because the compiler's -Wundeclared-selector check verifies only that the named selector exists. The Swift function reference you pass to #selector checks existence, membership in a class, and type signature.)

There are a couple of extra caveats for the function references you pass to the #selector expression:

  • Multiple functions with the same base name can be differentiated by their parameter labels using the aforementioned syntax for function references (e.g. insertSubview(_:at:) vs insertSubview(_:aboveSubview:)). But if a function has no parameters, the only way to disambiguate it is to use an as cast with the function's type signature (e.g. foo as () -> () vs foo(_:)).
  • There's a special syntax for property getter/setter pairs in Swift 3.0+. For example, given a var foo: Int, you can use #selector(getter: MyClass.foo) or #selector(setter: MyClass.foo).

General notes:

Cases where #selector doesn't work, and naming: Sometimes you don't have a function reference to make a selector with (for example, with methods dynamically registered in the ObjC runtime). In that case, you can construct a Selector from a string: e.g. Selector("dynamicMethod:") — though you lose the compiler's validity checking. When you do that, you need to follow ObjC naming rules, including colons (:) for each parameter.

Selector availability: The method referenced by the selector must be exposed to the ObjC runtime. In Swift 4, every method exposed to ObjC must have its declaration prefaced with the @objc attribute. (In previous versions you got that attribute for free in some cases, but now you have to explicitly declare it.)

Remember that private symbols aren't exposed to the runtime, too — your method needs to have at least internal visibility.

Key paths: These are related to but not quite the same as selectors. There's a special syntax for these in Swift 3, too: e.g. chris.valueForKeyPath(#keyPath(Person.friends.firstName)). See SE-0062 for details. And even more KeyPath stuff in Swift 4, so make sure you're using the right KeyPath-based API instead of selectors if appropriate.

You can read more about selectors under Interacting with Objective-C APIs in Using Swift with Cocoa and Objective-C.

Note: Before Swift 2.2, Selector conformed to StringLiteralConvertible, so you might find old code where bare strings are passed to APIs that take selectors. You'll want to run "Convert to Current Swift Syntax" in Xcode to get those using #selector.

Column name or number of supplied values does not match table definition

Dropping the table was not an option for me, since I'm keeping a running log. If every time I needed to insert I had to drop, the table would be meaningless.

My error was because I had a couple columns in the create table statement that were products of other columns, changing these fixed my problem. eg

create table foo (
field1 as int
,field2 as int
,field12 as field1 + field2 )

create table copyOfFoo (
field1 as int
,field2 as int
,field12 as field1 + field2)  --this is the problem, should just be 'as int'

insert into copyOfFoo
SELECT * FROM foo

JQuery How to extract value from href tag?

Here's a method that works by transforming the querystring into JSON...

var link = $('a').attr('href');

if (link.indexOf("?") != -1) {
    var query = link.split("?")[1];

    eval("query = {" + query.replace(/&/ig, "\",").replace(/=/ig, ":\"") + "\"};");

    if (query.page)
        alert(unescape(query.page));
    else
        alert('No page parameter');

} else {
    alert('No querystring');
}

I'd go with a library like the others suggest though... =)

Why can't radio buttons be "readonly"?

The best solution is to set the checked or unchecked state (either from client or server) and to not let the user change it after wards (i.e make it readonly) do the following:

<input type="radio" name="name" onclick="javascript: return false;" />

How to run a JAR file

You need to specify a Main-Class in the jar file manifest.

Oracle's tutorial contains a complete demonstration, but here's another one from scratch. You need two files:

Test.java:

public class Test
{
    public static void main(String[] args)
    {
        System.out.println("Hello world");
    }
}

manifest.mf:

Manifest-version: 1.0
Main-Class: Test

Note that the text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.

Then run:

javac Test.java
jar cfm test.jar manifest.mf Test.class
java -jar test.jar

Output:

Hello world

Access multiple elements of list knowing their index

Here's a simpler way:

a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [e for i, e in enumerate(a) if i in b]

Sorting a List<int>

Sort list of int descending you could just sort first and reverse

class Program
{
    static void Main(string[] args)
    {

        List<int> myList = new List<int>();

        myList.Add(38);
        myList.Add(34);
        myList.Add(35);
        myList.Add(36);
        myList.Add(37);


        myList.Sort();
        myList.Reverse();
        myList.ForEach(Console.WriteLine);


    }



}

What is the use of <<<EOD in PHP?

there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD') and heredoc(<<<EOD) strings

you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.

nowdoc strings will not expand variables just like single quotes.

ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

iOS 6 apps - how to deal with iPhone 5 screen size?

All apps will continue to work in the vertically stretched screen from what I could tell in today's presentation. They will be letterboxed or basically the extra 88 points in height would simply be black.

If you only plan to support iOS 6+, then definitely consider using Auto Layout. It removes all fixed layout handling and instead uses constraints to lay things out. Nothing will be hard-coded, and your life will become a lot simpler.

However, if you have to support older iOS's, then it really depends on your application. A majority of applications that use a standard navigation bar, and/or tab bar, could simply expand the content in the middle to use up that extra points. Set the autoresizing mask of the center content to expand in both directions.

view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

It works great out of the box for table views, however, if your app used pixel-perfect layout for displaying content, then your best bet would be to re-imagine the content so that it can accommodate varying heights.

If that's not a possibility, then the only remaining option is to have two UIs (pre iPhone 5, and iPhone 5).

If that sounds ugly, then you could go with the default letterboxed model where the extra points/pixels just show up black.

Edit

To enable your apps to work with iPhone 5, you need to add a retina version of the launcher image. It should be named [email protected]. And it has to be retina quality - there's no backward compatibility here :)

You could also select this image from within Xcode. Go to the target, and under the Summary section, look for Launch Images. The image has to be 640x1136 pixels in size. Here's a screenshot of where to find it, if that helps.

Xcode screenshot

Spring boot - Not a managed type

I have the same probblem, in version spring boot v1.3.x what i did is upgrade spring boot to version 1.5.7.RELEASE. Then the probblem gone.

How do I save a String to a text file using Java?

You could do this:

import java.io.*;
import java.util.*;

class WriteText
{
    public static void main(String[] args)
    {   
        try {
            String text = "Your sample content to save in a text file.";
            BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
            out.write(text);
            out.close();
        }
        catch (IOException e)
        {
            System.out.println("Exception ");       
        }

        return ;
    }
};

NULL vs nullptr (Why was it replaced?)

Here is Bjarne Stroustrup's wordings,

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

start/play embedded (iframe) youtube-video on click of an image

Example youtube iframe

<iframe id="video" src="https://www.youtube.com/embed/xNM7jEHgzg4" frameborder="0"></iframe>

The click to play HTML element

<div class="videoplay">Play</div> 

jQuery code to play the Video

$('.videoplay').on('click', function() {
    $("#video")[0].src += "?autoplay=1";
});

Thanks to https://codepen.io/martinwolf/pen/dyLAC

How to get the current branch name in Git?

Simply, add following lines to your ~/.bash_profile:

branch_show() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(branch_show)\[\033[00m\] $ "

In this way, you can have the current branch name in Terminal

Courtesy of Coderwall.com

Align DIV's to bottom or baseline

If you are having multiple child Div's inside your parent Div, then you can use vertical-align property something like below :

.Parent div
{
  vertical-align : bottom;
}

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

How to compare 2 files fast using .NET?

The only thing that might make a checksum comparison slightly faster than a byte-by-byte comparison is the fact that you are reading one file at a time, somewhat reducing the seek time for the disk head. That slight gain may however very well be eaten up by the added time of calculating the hash.

Also, a checksum comparison of course only has any chance of being faster if the files are identical. If they are not, a byte-by-byte comparison would end at the first difference, making it a lot faster.

You should also consider that a hash code comparison only tells you that it's very likely that the files are identical. To be 100% certain you need to do a byte-by-byte comparison.

If the hash code for example is 32 bits, you are about 99.99999998% certain that the files are identical if the hash codes match. That is close to 100%, but if you truly need 100% certainty, that's not it.

VBA check if file exists

A way that is clean and short:

Public Function IsFile(s)
    IsFile = CreateObject("Scripting.FileSystemObject").FileExists(s)
End Function

ALTER TABLE, set null in not null column, PostgreSQL 9.1

ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;

More details in the manual: http://www.postgresql.org/docs/9.1/static/sql-altertable.html

How to get the nth element of a python list or a default if not available

l[index] if index < len(l) else default

To support negative indices we can use:

l[index] if -len(l) <= index < len(l) else default

Save PHP array to MySQL?

you can insert serialized object ( array ) to mysql , example serialize($object) and you can unserize object example unserialize($object)

How do I vertically align text in a div?

This works fine:

HTML

<div class="information">
    <span>Some text</span>
    <mat-icon>info_outline</mat-icon>
</div>

Sass

.information {
    display: inline-block;
    padding: 4px 0;
    span {
        display: inline-block;
        vertical-align: middle;
    }
    mat-icon {
        vertical-align: middle;
    }
}

Without and with the image tag <mat-icon> (which is a font).

Plot inline or a separate window using Matplotlib in Spyder IDE

Magic commands such as

%matplotlib qt  

work in the iPython console and Notebook, but do not work within a script.

In that case, after importing:

from IPython import get_ipython

use:

get_ipython().run_line_magic('matplotlib', 'inline')

for inline plotting of the following code, and

get_ipython().run_line_magic('matplotlib', 'qt')

for plotting in an external window.

Edit: solution above does not always work, depending on your OS/Spyder version Anaconda issue on GitHub. Setting the Graphics Backend to Automatic (as indicated in another answer: Tools >> Preferences >> IPython console >> Graphics --> Automatic) solves the problem for me.

Then, after a Console restart, one can switch between Inline and External plot windows using the get_ipython() command, without having to restart the console.

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

Anaconda is made for the purpose you are asking. It is also an environment manager. It separates out environments. It was made because stable and legacy packages were not supported with newer/unstable versions of host languages; therefore a software was required that could separate and manage these versions on the same machine without the need to reinstall or uninstall individual host programming languages/environments.

You can find creation/deletion of environments in the Anaconda documentation.

Hope this helped.

Difference between object and class in Scala

tl;dr

  • class C defines a class, just as in Java or C++.
  • object O creates a singleton object O as instance of some anonymous class; it can be used to hold static members that are not associated with instances of some class.
  • object O extends T makes the object O an instance of trait T; you can then pass O anywhere, a T is expected.
  • if there is a class C, then object C is the companion object of class C; note that the companion object is not automatically an instance of C.

Also see Scala documentation for object and class.

object as host of static members

Most often, you need an object to hold methods and values/variables that shall be available without having to first instantiate an instance of some class. This use is closely related to static members in Java.

object A {
  def twice(i: Int): Int = 2*i
}

You can then call above method using A.twice(2).

If twice were a member of some class A, then you would need to make an instance first:

class A() {
  def twice(i: Int): Int = 2 * i
}

val a = new A()
a.twice(2)

You can see how redundant this is, as twice does not require any instance-specific data.

object as a special named instance

You can also use the object itself as some special instance of a class or trait. When you do this, your object needs to extend some trait in order to become an instance of a subclass of it.

Consider the following code:

object A extends B with C {
  ...
}

This declaration first declares an anonymous (inaccessible) class that extends both B and C, and instantiates a single instance of this class named A.

This means A can be passed to functions expecting objects of type B or C, or B with C.

Additional Features of object

There also exist some special features of objects in Scala. I recommend to read the official documentation.

  • def apply(...) enables the usual method name-less syntax of A(...)
  • def unapply(...) allows to create custom pattern matching extractors
  • if accompanying a class of the same name, the object assumes a special role when resolving implicit parameters

android EditText - finished typing event

I ended her with the same problem and I could not use the the solution with onEditorAction or onFocusChange and did not want to try the timer. A timer is too dangerous for may taste, because of all the threads and too unpredictable, as you do not know when you code is executed.

The onEditorAction do not catch when the user leave without using a button and if you use it please notice that KeyEvent can be null. The focus is unreliable at both ends the user can get focus and leave without enter any text or selecting the field and the user do not need to leave the last EditText field.

My solution use onFocusChange and a flag set when the user starts editing text and a function to get the text from the last focused view, which I call when need.

I just clear the focus on all my text fields to tricker the leave text view code, The clearFocus code is only executed if the field has focus. I call the function in onSaveInstanceState so I do not have to save the flag (mEditing) as a state of the EditText view and when important buttons is clicked and when the activity is closed.

Be careful with TexWatcher as it is call often I use the condition on focus to not react when the onRestoreInstanceState code entering text. I

final EditText mEditTextView = (EditText) getView();

    mEditTextView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!mEditing && mEditTextView.hasFocus()) {
                mEditing = true;
            }
        }
    });
    mEditTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus && mEditing) {
                mEditing = false;
                ///Do the thing
            }
        }
    });
protected void saveLastOpenField(){
    for (EditText view:getFields()){
            view.clearFocus();
    }
}

android asynctask sending callbacks to ui

I will repeat what the others said, but will just try to make it simpler...

First, just create the Interface class

public interface PostTaskListener<K> {
    // K is the type of the result object of the async task 
    void onPostTask(K result);
}

Second, create the AsyncTask (which can be an inner static class of your activity or fragment) that uses the Interface, by including a concrete class. In the example, the PostTaskListener is parameterized with String, which means it expects a String class as a result of the async task.

public static class LoadData extends AsyncTask<Void, Void, String> {

    private PostTaskListener<String> postTaskListener;

    protected LoadData(PostTaskListener<String> postTaskListener){
        this.postTaskListener = postTaskListener;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null && postTaskListener != null)
            postTaskListener.onPostTask(result);
    }
}

Finally, the part where your combine your logic. In your activity / fragment, create the PostTaskListener and pass it to the async task. Here is an example:

...
PostTaskListener<String> postTaskListener = new PostTaskListener<String>() {
    @Override
    public void onPostTask(String result) {
        //Your post execution task code
    }
}

// Create the async task and pass it the post task listener.
new LoadData(postTaskListener);

Done!

Case Insensitive String comp in C

static int ignoreCaseComp (const char *str1, const char *str2, int length)
{
    int k;
    for (k = 0; k < length; k++)
    {

        if ((str1[k] | 32) != (str2[k] | 32))
            break;
    }

    if (k != length)
        return 1;
    return 0;
}

Reference

How to sleep the thread in node.js without affecting other threads?

Please consider the deasync module, personally I don't like the Promise way to make all functions async, and keyword async/await anythere. And I think the official node.js should consider to expose the event loop API, this will solve the callback hell simply. Node.js is a framework not a language.

var node = require("deasync");
node.loop = node.runLoopOnce;

var done = 0;
// async call here
db.query("select * from ticket", (error, results, fields)=>{
    done = 1;
});

while (!done)
    node.loop();

// Now, here you go

SELECT data from another schema in oracle

In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.

From the connecting schema:

CREATE SYNONYM pi_int FOR pct.pi_int;

Then you can query pi_int as:

SELECT * FROM pi_int;

jQuery - Follow the cursor with a DIV

You don't need jQuery for this. Here's a simple working example:

<!DOCTYPE html>
<html>
    <head>
        <title>box-shadow-experiment</title>
        <style type="text/css">
            #box-shadow-div{
                position: fixed;
                width: 1px;
                height: 1px;
                border-radius: 100%;
                background-color:black;
                box-shadow: 0 0 10px 10px black;
                top: 49%;
                left: 48.85%;
            }
        </style>
        <script type="text/javascript">
            window.onload = function(){
                var bsDiv = document.getElementById("box-shadow-div");
                var x, y;
    // On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
                window.addEventListener('mousemove', function(event){
                    x = event.clientX;
                    y = event.clientY;                    
                    if ( typeof x !== 'undefined' ){
                        bsDiv.style.left = x + "px";
                        bsDiv.style.top = y + "px";
                    }
                }, false);
            }
        </script>
    </head>
    <body>
        <div id="box-shadow-div"></div>
    </body>
</html>

I chose position: fixed; so scrolling wouldn't be an issue.

Check if array is empty or null

User JQuery is EmptyObject to check whether array is contains elements or not.

var testArray=[1,2,3,4,5];
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true

Server configuration by allow_url_fopen=0 in

Use this code in your php script (first lines)

ini_set('allow_url_fopen',1);

JQuery - File attributes

If #uploadedfile is an input with type "file" :

var file = $("#uploadedfile")[0].files[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");

Normally this would fire on the change event, like so:

$("#uploadedfile").on("change", function(){
   var file = this.files[0],
       fileName = file.name,
       fileSize = file.size;
   alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
   CustomFileHandlingFunction(file);
});

FIDDLE

Loop through JSON object List

Since you are using jQuery, you might as well use the each method... Also, it seems like everything is a value of the property 'd' in this JS Object [Notation].

$.each(result.d,function(i) {
    // In case there are several values in the array 'd'
    $.each(this,function(j) {
        // Apparently doesn't work...
        alert(this.EmployeeName);
        // What about this?
        alert(result.d[i][j]['EmployeeName']);
        // Or this?
        alert(result.d[i][j].EmployeeName);
    });
});

That should work. if not, then maybe you can give us a longer example of the JSON.

Edit: If none of this stuff works then I'm starting to think there might be something wrong with the syntax of your JSON.

Select first empty cell in column F starting from row 1. (without using offset )

If all you're trying to do is select the first blank cell in a given column, you can give this a try:

Code:

Public Sub SelectFirstBlankCell()
    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
    Dim currentRowValue As String

    sourceCol = 6   'column F has a value of 6
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    'for every row, find the first blank cell and select it
    For currentRow = 1 To rowCount
        currentRowValue = Cells(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
        End If
    Next
End Sub

Before Selection - first blank cell to select:

enter image description here

After Selection:

enter image description here

jQuery "on create" event for dynamically-created elements

I Think it's worth mentioning that in some cases, this would work:

$( document ).ajaxComplete(function() {
// Do Stuff
});

PHP Email sending BCC

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: [email protected]\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";

How to set a bitmap from resource

Using this function you can get Image Bitmap. Just pass image url

 public Bitmap getBitmapFromURL(String strURL) {
      try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
      } catch (IOException e) {
        e.printStackTrace();
        return null;
      }
 }